From lie.1296 at gmail.com Tue Dec 1 00:01:21 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Tue, 01 Dec 2009 16:01:21 +1100 Subject: Variables with cross-module usage In-Reply-To: References: <4b11e7fc.0706c00a.63b5.545a@mx.google.com> <4b135424$1@dnews.tpgi.com.au> Message-ID: <4b14a38e$1@dnews.tpgi.com.au> On 12/1/2009 7:51 AM, Terry Reedy wrote: >> In everyday life and natural languages, a single name can be used to >> refer to multiple objects just by context without referring any >> namespace. > > Namespace are contexts. They were (re)invented in programming just to > make it easier to have single name could refer to different objects -- > in different contexts. Names bound within a function are interpreted as > being within the default local context without explicitly referring to > it. Indeed, one cannot explicitly refer to the local namespace of > functions, only to a dict copy thereof. Let's stop with the silly analogies. > > Let's not start making analogism between nature and silicon. > > There are several things wrong with this. > > You meant 'analogies'. No, I meant "analogism". My spellchecker lined that red, but I know what I meant. Let me define this word, which apparently is not (at least yet) in the dictionary: - analogism: the way of thinking that analogy must be perfectly similar to the "real thing" in every single way, to the point of making grand and complex story that is even more complicated than the "real thing" itself. > I did not go into that counterclaim, but indeed, many people who program > in C, for instance, use C names as if they were object names instead of > location names (or location,increment tuple names). Sometimes they even > forget that they are really just location names. One too-common result > of that confusion has been buffer overruns and virus programs that > exploit them. These are impossible in Python. "address names" and "object names", those are a good definition; stop at that. Any more layers of analogies, with boxes, with strings, with how human uses "name" in social life, or with how snakes align themselves with stars are much less useful than just learning how the "name" itself behave. Let's stop teaching with excessive analogies, they just provide layers and layers of thinking that would confuse people when the analogy doesn't match the "real thing". Just learn how they behave, directly. Analogy are fine to describe when first explaining how roughly something works, but don't expect things to be the same down to the details; and worse, don't make more analogies to cover up for the points the previous analogy doesn't cover. Just stop the "analogism" [1]! [1] there I used the word again. From grimsqueaker13 at gmail.com Tue Dec 1 00:31:21 2009 From: grimsqueaker13 at gmail.com (Grimsqueaker) Date: Mon, 30 Nov 2009 21:31:21 -0800 (PST) Subject: python logging filters References: <889b8e46-1f99-4e9d-bdd4-59b9a8a32886@k17g2000yqh.googlegroups.com> <895b561e-4aed-40e9-b6a9-036bc5e8fe56@p35g2000yqh.googlegroups.com> <0eaf51df-ed54-4f63-9514-76077a378ee6@v30g2000yqm.googlegroups.com> <6704aaa3-b3d1-4da7-a486-06833cbb0509@p33g2000vbn.googlegroups.com> Message-ID: <6957c81d-28da-444e-b15d-c3241c7957cc@l13g2000yqb.googlegroups.com> My logging behaves as I expect now and I have a better understanding of how the module functions. Thank you for taking the time to explain those points to me. :) On Nov 30, 4:10?pm, Vinay Sajip wrote: > On Nov 30, 6:52?am, Grimsqueaker wrote: > > > > > So would I be correct in saying that Filters apply only the the object > > they are attached to and have no effect on how messages are propagated > > through thelogginghierarchy? If this is the case my next question > > would be: How can I affect whether or not a message is propagated > > further up the tree? > > You are correct about how Filters work. To prevent propagation, use > the propagate attribute, documented here: > > http://docs.python.org/library/logging.html#logger-objects > > Most times, you don't need to use this. For example, if you want > events in the A hierarchy to go to one place and events in the B > hierarchy to go to another place (e.g. two different log files), you > just attach different handlers (e.g. two different FileHandlers) to > loggers A and B. If you want a combined log as well, add an > appropriate handler to the root logger. > > I find that things usually work OK if I just determine what handlers I > need and attach them to the appropriate loggers, setting the levels on > handlers and loggers appropriately. If I need filtering logic for a > logger or handler which is more involved than just an integer > threshold (which happens less often), I use Filters. Even less often, > if I need to block events from a part of the logger hierarchy from > bubbling upwards, then I use the propagate attribute. > > Regards, > > Vinay Sajip From grimsqueaker13 at gmail.com Tue Dec 1 00:31:26 2009 From: grimsqueaker13 at gmail.com (Grimsqueaker) Date: Mon, 30 Nov 2009 21:31:26 -0800 (PST) Subject: python logging filters References: <889b8e46-1f99-4e9d-bdd4-59b9a8a32886@k17g2000yqh.googlegroups.com> <895b561e-4aed-40e9-b6a9-036bc5e8fe56@p35g2000yqh.googlegroups.com> <0eaf51df-ed54-4f63-9514-76077a378ee6@v30g2000yqm.googlegroups.com> <6704aaa3-b3d1-4da7-a486-06833cbb0509@p33g2000vbn.googlegroups.com> Message-ID: <62ba22e6-758b-4b51-84e0-9468191ab68d@a32g2000yqm.googlegroups.com> My logging behaves as I expect now and I have a better understanding of how the module functions. Thank you for taking the time to explain those points to me. :) On Nov 30, 4:10?pm, Vinay Sajip wrote: > On Nov 30, 6:52?am, Grimsqueaker wrote: > > > > > So would I be correct in saying that Filters apply only the the object > > they are attached to and have no effect on how messages are propagated > > through thelogginghierarchy? If this is the case my next question > > would be: How can I affect whether or not a message is propagated > > further up the tree? > > You are correct about how Filters work. To prevent propagation, use > the propagate attribute, documented here: > > http://docs.python.org/library/logging.html#logger-objects > > Most times, you don't need to use this. For example, if you want > events in the A hierarchy to go to one place and events in the B > hierarchy to go to another place (e.g. two different log files), you > just attach different handlers (e.g. two different FileHandlers) to > loggers A and B. If you want a combined log as well, add an > appropriate handler to the root logger. > > I find that things usually work OK if I just determine what handlers I > need and attach them to the appropriate loggers, setting the levels on > handlers and loggers appropriately. If I need filtering logic for a > logger or handler which is more involved than just an integer > threshold (which happens less often), I use Filters. Even less often, > if I need to block events from a part of the logger hierarchy from > bubbling upwards, then I use the propagate attribute. > > Regards, > > Vinay Sajip From grimsqueaker13 at gmail.com Tue Dec 1 00:31:31 2009 From: grimsqueaker13 at gmail.com (Grimsqueaker) Date: Mon, 30 Nov 2009 21:31:31 -0800 (PST) Subject: python logging filters References: <889b8e46-1f99-4e9d-bdd4-59b9a8a32886@k17g2000yqh.googlegroups.com> <895b561e-4aed-40e9-b6a9-036bc5e8fe56@p35g2000yqh.googlegroups.com> <0eaf51df-ed54-4f63-9514-76077a378ee6@v30g2000yqm.googlegroups.com> <6704aaa3-b3d1-4da7-a486-06833cbb0509@p33g2000vbn.googlegroups.com> Message-ID: <393ed6f2-8066-4d89-8e3f-d118f356497b@j24g2000yqa.googlegroups.com> My logging behaves as I expect now and I have a better understanding of how the module functions. Thank you for taking the time to explain those points to me. :) On Nov 30, 4:10?pm, Vinay Sajip wrote: > On Nov 30, 6:52?am, Grimsqueaker wrote: > > > > > So would I be correct in saying that Filters apply only the the object > > they are attached to and have no effect on how messages are propagated > > through thelogginghierarchy? If this is the case my next question > > would be: How can I affect whether or not a message is propagated > > further up the tree? > > You are correct about how Filters work. To prevent propagation, use > the propagate attribute, documented here: > > http://docs.python.org/library/logging.html#logger-objects > > Most times, you don't need to use this. For example, if you want > events in the A hierarchy to go to one place and events in the B > hierarchy to go to another place (e.g. two different log files), you > just attach different handlers (e.g. two different FileHandlers) to > loggers A and B. If you want a combined log as well, add an > appropriate handler to the root logger. > > I find that things usually work OK if I just determine what handlers I > need and attach them to the appropriate loggers, setting the levels on > handlers and loggers appropriately. If I need filtering logic for a > logger or handler which is more involved than just an integer > threshold (which happens less often), I use Filters. Even less often, > if I need to block events from a part of the logger hierarchy from > bubbling upwards, then I use the propagate attribute. > > Regards, > > Vinay Sajip From mensanator at aol.com Tue Dec 1 01:08:52 2009 From: mensanator at aol.com (Mensanator) Date: Mon, 30 Nov 2009 22:08:52 -0800 (PST) Subject: ANN: GMPY 1.11rc1 is available References: Message-ID: <32bb657f-fa32-4db3-89f6-26f8bdbd7fe1@j4g2000yqe.googlegroups.com> On Nov 29, 9:04?pm, casevh wrote: > Everyone, > > I'm pleased to annouce that a new version of GMPY is available. > GMPY is a wrapper for the MPIR or GMP multiple-precision > arithmetic library. GMPY 1.11rc1 is available for download from: > > http://code.google.com/p/gmpy/ > > In addition to support for Python 3.x, there are several new > features in this release: > > - Even faster conversion to/from Python longs. > - Performance improvements by reducing function overhead. > - Performance improvements by improved caching. > - Support for cdivmod, fdivmod, and tdivmod. > - Unicode strings are accepted on Python 2.x and 3.x. > - Fixed regression in GMPY 1.10 where True/False were no > ? longer recognized. > > Comments on provided binaries > > The 32-bit Windows installers were compiled with MinGW32 using MPIR > 1.3.0rc3 and will automatically recognize the CPU type and use code > optimized for the CPU at runtime. The 64-bit Windows installers were > compiled Microsoft's SDK compilers using MPRI 1.3.0rc3. Detailed > instructions are included if you want to compile your own binary. > > Future plans > > On releasing the GIL: I have compared releasing the GIL versus the > multiprocessing module and the multiprocessing module offers better > and more predictable performance for embarrassingly parallel tasks > than releasing the GIL. If there are requests, I can add a compile- > time option to enable threading support but it is unlikely to > become the default. > > On mutable integers: The performance advantages of mutable integers > appears to be 20% to 30% for some operations. I plan to add a new > mutable integer type in the next release of GMPY. If you want to > experiment with mutable integers now, GMPY can be compiled with > mutable version of the standard 'mpz' type. Please see the file > "mutable_mpz.txt" for more information. > > Please report any issues! By lucky coincidence I happen to be working on a Python implementation of Brent's Cycle Detection algorithm to locate large loop cycles in 3n+C of the Collatz conjecture. I had the algorithm worked up in pure Python but needed to implement it using gmpy to do the heavy lifting (due to the breakdown of my C version). I am happy to report that my initial tests using version 1.11 seem to be a big improvement: ## home, vista, python 3.1, gmpy 1.10 ## i: 2 ## f1: 101 ## f2: 401 ## C: 40501 ## loop @: 29593 ## found in: 0.000 sec ## len(sv) 88 determined in: 0.000 sec ## ## i: 3 ## f1: 1009 ## f2: 4001 ## C: 4037009 ## loop @: 12799165 ## found in: 0.000 sec ## len(sv) 76 determined in: 0.000 sec ## ## i: 4 ## f1: 10007 ## f2: 40009 ## C: 400370063 ## loop @: 933402925 ## found in: 0.000 sec ## len(sv) 780 determined in: 0.000 sec ## ## i: 5 ## f1: 100003 ## f2: 400009 ## C: 40002100027 ## loop @: 13522904574967 ## found in: 0.015 sec ## len(sv) 2233 determined in: 0.000 sec ## ## i: 6 ## f1: 1000003 ## f2: 4000037 ## C: 4000049000111 ## loop @: 1712218136639 ## found in: 0.032 sec ## len(sv) 7789 determined in: 0.015 sec ## ## i: 7 ## f1: 10000019 ## f2: 40000003 ## C: 400000790000057 ## loop @: 2519240916548647 ## found in: 0.219 sec ## len(sv) 51270 determined in: 0.078 sec ## ## i: 8 ## f1: 100000007 ## f2: 400000009 ## C: 40000003700000063 ## loop @: 7032060392244193 ## found in: 0.452 sec ## len(sv) 110238 determined in: 0.172 sec ## ## i: 9 ## f1: 1000000007 ## f2: 4000000007 ## C: 4000000035000000049 ## loop @: 7486962189408734959 ## found in: 3.276 sec ## len(sv) 668255 determined in: 1.014 sec ## ## i: 10 ## f1: 10000000019 ## f2: 40000000003 ## C: 400000000790000000057 ## loop @: 2513183598585048828239 ## found in: 15.974 sec ## len(sv) 4104051 determined in: 6.240 sec ## ## i: 11 ## f1: 100000000003 ## f2: 400000000019 ## C: 40000000003100000000057 ## loop @: 43826676662614800299839 ## found in: 104.754 sec ## len(sv) 20780131 determined in: 31.840 sec Compare that to using version 1.11 (all else equal): ## home, vista, python 3.1, gmpy 1.11 ## ## i: 2 ## f1: 101 ## f2: 401 ## C: 40501 ## loop @: 29593 ## found in: 0.000 sec ## len(sv) 88 determined in: 0.000 sec ## ## i: 3 ## f1: 1009 ## f2: 4001 ## C: 4037009 ## loop @: 12799165 ## found in: 0.000 sec ## len(sv) 76 determined in: 0.000 sec ## ## i: 4 ## f1: 10007 ## f2: 40009 ## C: 400370063 ## loop @: 933402925 ## found in: 0.015 sec ## len(sv) 780 determined in: 0.000 sec ## ## i: 5 ## f1: 100003 ## f2: 400009 ## C: 40002100027 ## loop @: 13522904574967 ## found in: 0.000 sec ## len(sv) 2233 determined in: 0.000 sec ## ## i: 6 ## f1: 1000003 ## f2: 4000037 ## C: 4000049000111 ## loop @: 1712218136639 ## found in: 0.016 sec ## len(sv) 7789 determined in: 0.015 sec ## ## i: 7 ## f1: 10000019 ## f2: 40000003 ## C: 400000790000057 ## loop @: 2519240916548647 ## found in: 0.140 sec ## len(sv) 51270 determined in: 0.047 sec ## ## i: 8 ## f1: 100000007 ## f2: 400000009 ## C: 40000003700000063 ## loop @: 7032060392244193 ## found in: 0.296 sec ## len(sv) 110238 determined in: 0.109 sec ## ## i: 9 ## f1: 1000000007 ## f2: 4000000007 ## C: 4000000035000000049 ## loop @: 7486962189408734959 ## found in: 2.200 sec ## len(sv) 668255 determined in: 0.624 sec ## ## i: 10 ## f1: 10000000019 ## f2: 40000000003 ## C: 400000000790000000057 ## loop @: 2513183598585048828239 ## found in: 10.624 sec ## len(sv) 4104051 determined in: 3.931 sec ## ## i: 11 ## f1: 100000000003 ## f2: 400000000019 ## C: 40000000003100000000057 ## loop @: 43826676662614800299839 ## found in: 69.295 sec ## len(sv) 20780131 determined in: 19.516 sec Good work! > > casevh From greg.ewing at canterbury.ac.nz Tue Dec 1 01:19:18 2009 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Tue, 01 Dec 2009 19:19:18 +1300 Subject: python and vc numbers In-Reply-To: References: <7ngl1gF3ml76pU1@mid.individual.net> <20091130082059.GA10079@gwsc.vic.edu.au> <20091130100200.GB12885@gwsc.vic.edu.au> <50697b2c0911300226j126d0dfen6e22e053ccca6243@mail.gmail.com> Message-ID: <7njqr5F3mqp1oU1@mid.individual.net> Daniel Dalton wrote: > I can't find a reliable way to > determine the current console number with python or any bash tool. When > I say console number, I mean the actual console number, not screen > window or device it is sending to or whatever. You may be able to tell by looking at the DISPLAY environment variable. Usually it has a form like localhost:X.Y where X and Y are numbers identifying the display device and screen. -- Greg From juneng603 at gmail.com Tue Dec 1 01:39:49 2009 From: juneng603 at gmail.com (junyoung) Date: Mon, 30 Nov 2009 22:39:49 -0800 (PST) Subject: how to debug extended module? Message-ID: Hi, I am a newbie who want to implement a extend module to use native python language with my own shared library. to test wrapper library(extend module, name is 'test.so'), I created some test-cases. There are some errors what I couldn't figure our reasons. ex) SystemError: error return without exception set .... ... so, I ran the ddd with python and then I set test.py as a argument of it. ex) ddd python in ddd run with arguments : test.py but in this situation, I couldn't step in my own shared library (compiled as the debug mode). Is there any clear way to debug my extend module(that it, debug shared library)?? From jspies at sun.ac.za Tue Dec 1 01:51:20 2009 From: jspies at sun.ac.za (Johann Spies) Date: Tue, 1 Dec 2009 08:51:20 +0200 Subject: peppy Message-ID: <20091201065118.GA28424@sun.ac.za> After reading about peppy on Freshmeat I decided to try it out after installing it using easy_install. But: $ peppy Traceback (most recent call last): File "/usr/bin/peppy", line 5, in pkg_resources.run_script('peppy==0.13.2', 'peppy') File "/usr/lib/python2.5/site-packages/pkg_resources.py", line 452, in run_script self.require(requires)[0].run_script(script_name, ns) File "/usr/lib/python2.5/site-packages/pkg_resources.py", line 1179, in run_script execfile(script_filename, namespace, namespace) File "/usr/lib/python2.5/site-packages/peppy-0.13.2-py2.5.egg/EGG-INFO/scripts/peppy", line 13, in import peppy.main File "/usr/lib/python2.5/site-packages/peppy-0.13.2-py2.5.egg/peppy/main.py", line 16, in from peppy.buffers import * File "/usr/lib/python2.5/site-packages/peppy-0.13.2-py2.5.egg/peppy/buffers.py", line 11, in from peppy.actions import * File "/usr/lib/python2.5/site-packages/peppy-0.13.2-py2.5.egg/peppy/actions/__init__.py", line 31, in from peppy.lib.multikey import KeyAccelerator File "/usr/lib/python2.5/site-packages/peppy-0.13.2-py2.5.egg/peppy/lib/multikey.py", line 120, in 'C-': wx.ACCEL_CMD, AttributeError: 'module' object has no attribute 'ACCEL_CMD' This is on Debian squeeze. How do I solve this? Regards Johann -- Johann Spies Telefoon: 021-808 4599 Informasietegnologie, Universiteit van Stellenbosch "Lo, children are an heritage of the LORD: and the fruit of the womb is his reward." Psalms 127:3 From nobody at nowhere.com Tue Dec 1 02:20:29 2009 From: nobody at nowhere.com (Nobody) Date: Tue, 01 Dec 2009 07:20:29 +0000 Subject: python and vc numbers References: <7ngl1gF3ml76pU1@mid.individual.net> <20091130082059.GA10079@gwsc.vic.edu.au> Message-ID: On Mon, 30 Nov 2009 21:02:00 +1100, Daniel Dalton wrote: >> That did the trick, thanks, after I append >> [-2] > > Further testing under screen says otherwise -- it seems to give me the > tty number, not the virtual console number. Is there any way to figure > out what virtual console I'm am in I'm sure that there are all kinds of heuristics you could try, but ultimately the question is meaningless. E.g. you can start a screen session on one terminal (which may not be a VC, but an xterm, ssh login, etc), detach it, attach it to a different terminal, or even attach it to multiple terminals. The child process only knows about its controlling terminal. If that happens to be a pty slave, you could try looking for any processes connected to the pty master. But you aren't guaranteeed to find any such processes; if a process is running under a different account, you won't be able to enumerate its descriptors. And you might find that the master is owned by e.g. sshd, in which case there really isn't any way to find out what's on the other end of the connection. If the process happens to be part of a "screen" session, you can use "screen -ls" to list sessions, and find out which terminal they are attached to (although they might be detached, or they might be attached to something other than a VC). From showell30 at yahoo.com Tue Dec 1 02:30:06 2009 From: showell30 at yahoo.com (Steve Howell) Date: Mon, 30 Nov 2009 23:30:06 -0800 (PST) Subject: a 100-line indentation-based preprocessor for HTML References: <7df64b08-8d81-4159-9f24-ab0945d82cf8@g1g2000pra.googlegroups.com> Message-ID: On Nov 28, 4:46?am, "Colin W." wrote: > On 27-Nov-09 22:04 PM, Steve Howell wrote: > > > > > Python has this really neat idea called indentation-based syntax, and > > there are folks that have caught on to this idea in the HTML > > community. > > > AFAIK the most popular indentation-based solution for generating HTML > > is a tool called HAML, which actually is written in Ruby. > > > I have been poking around with the HAML concepts in Python, with the > > specific goal of integrating with Django. ? But before releasing that, > > I thought it would be useful to post code that distills the basic > > concept with no assumptions about your target renderer. ?I hope it > > also serves as a good example of what you can do in exactly 100 lines > > of Python code. > > > Here is what it does... > > > ? ? ?You can use indentation syntax for HTML tags like table. > > > ? ? ?From this... > > > ? ? ?table > > ? ? ? ? ?tr > > ? ? ? ? ? ? ?td > > ? ? ? ? ? ? ? ? ?Left > > ? ? ? ? ? ? ?td > > ? ? ? ? ? ? ? ? ?Center > > ? ? ? ? ? ? ?td > > ? ? ? ? ? ? ? ? ?Right > > > ? ? ?...you get this: > > ?... > > [snip] > > This is a neat idea but would a two character indentation not be enough? > The code actually preserves whatever indent style you give as input, as long as you are consistent. I used 4-space indents in my examples since that seems to be the convention in Python, but when I did my stint in Ruby, I got pretty comfortable with 2-space indents as well, and I think it can make sense for HTML, where you do get pretty deep sometimes with idioms like table/tr/td. From nobody at nowhere.com Tue Dec 1 02:35:52 2009 From: nobody at nowhere.com (Nobody) Date: Tue, 01 Dec 2009 07:35:52 +0000 Subject: peppy References: Message-ID: On Tue, 01 Dec 2009 08:51:20 +0200, Johann Spies wrote: > After reading about peppy on Freshmeat I decided to try it out after > installing it using easy_install. But: > > $ peppy > File "/usr/lib/python2.5/site-packages/peppy-0.13.2-py2.5.egg/peppy/lib/multikey.py", line 120, in > 'C-': wx.ACCEL_CMD, > AttributeError: 'module' object has no attribute 'ACCEL_CMD' wx.ACCEL_CMD exists in wxPython 2.8 but not in 2.6, so I'd guess that peppy requires 2.8 but you have 2.6 (or if you have both, 2.6 is the default). > This is on Debian squeeze. > > How do I solve this? First, ensure that wxPython 2.8 is installed. If you have both 2.6 and 2.8, you may need to add the following at the beginning of the main "peppy" script: import wxversion wxversion.select("2.8") This will cause subsequent "import wx" commands to use wxPython 2.8. From mertensb.mazda at gmail.com Tue Dec 1 02:42:29 2009 From: mertensb.mazda at gmail.com (Bram Mertens) Date: Tue, 01 Dec 2009 08:42:29 +0100 Subject: Bored. In-Reply-To: <87y6lno89b.fsf@benfinney.id.au> References: <16097008-372c-4522-889d-a78319c3575c@b2g2000yqi.googlegroups.com> <87y6lno89b.fsf@benfinney.id.au> Message-ID: <4B14C8E5.1030303@gmail.com> Ben Finney wrote: > geremy condra writes: > >> On Mon, Nov 30, 2009 at 5:14 PM, Necronymouse wrote: >>> Hello, I am learning python for about 2 years and I am bored. Not >>> with python but I have a little problem, when i want to write >>> something I realise that somebody had alredy written it! > > That's great news: it means you can learn by example, and also learn the > more important skills of collaborating with other developers. > >> I'd find a big project and contribute to it. There's a lot more to >> being a developer than writing code, and its hard to learn much about >> that side of things by working on your own projects all the time. >> Plus, it can be very satisfying to make a widely used piece of >> software better. > > This is good advice. > > I would also say that it can be very satisfying contributing on a > *small* project: there is usually less communication overhead since > there are fewer people that need to communicate (the principles explored > in ?The Mythical Man-Month?). On a small project, too, you can often > have a bigger impact which for many people is more satisfying. > > So, in general: when you realise someone has already written something > you want to use, then start using it! You will quickly find that it > doesn't quite do everything you want, so that's your opportunity to make > improvements and start working with the existing developers. > How about http://sourceforge.net/search/?type_of_search=soft&words=python ? Pick a project you like I'd be surprised if you'd be turned down when offering help to any of these. From Nadav.C at qualisystems.com Tue Dec 1 03:15:51 2009 From: Nadav.C at qualisystems.com (Nadav Chernin) Date: Tue, 1 Dec 2009 10:15:51 +0200 Subject: Function parameters list Message-ID: <97FB089C6E1F404CB0132AC3BB3E5C2701947DA4@exchange.qualisystems.local> Hello, all I need to know dynamically parameters of any function (prototype). Is there some way to get it? Thanks, Nadav -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Tue Dec 1 03:21:20 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 1 Dec 2009 00:21:20 -0800 Subject: Function parameters list In-Reply-To: <97FB089C6E1F404CB0132AC3BB3E5C2701947DA4@exchange.qualisystems.local> References: <97FB089C6E1F404CB0132AC3BB3E5C2701947DA4@exchange.qualisystems.local> Message-ID: <50697b2c0912010021t535ec880y2d543e8c3e6fbb9b@mail.gmail.com> On Tue, Dec 1, 2009 at 12:15 AM, Nadav Chernin wrote: > Hello, all > > I need to know dynamically parameters of any function (prototype). > > Is there some way to get it? The `inspect` module: http://docs.python.org/library/inspect.html#inspect.getargspec http://docs.python.org/library/inspect.html#inspect.formatargspec Cheers, Chris -- http://blog.rebertia.com From joncle at googlemail.com Tue Dec 1 04:14:00 2009 From: joncle at googlemail.com (Jon Clements) Date: Tue, 1 Dec 2009 01:14:00 -0800 (PST) Subject: Python Programming Challenges for beginners? References: <09ea817f-57a9-44a6-b815-299ae3ce75d3@x5g2000prf.googlegroups.com> Message-ID: On Nov 30, 9:13?pm, f... at mauve.rahul.net (Edward A. Falk) wrote: > In article <09ea817f-57a9-44a6-b815-299ae3ce7... at x5g2000prf.googlegroups.com>, > > alex23 ? wrote: > >On Nov 27, 1:24?pm, astral orange <457r0... at gmail.com> wrote: > >> I would like to test out what I know so far by solving programming > >> challenges. > > >Project Euler can be a lot of fun:http://projecteuler.net/ > > Oooh, that *does* look like fun. > > -- > ? ? ? ? -Ed Falk, f... at despams.r.us.com > ? ? ? ?http://thespamdiaries.blogspot.com/ Only problem is (quoting Douglas Adams): "I love deadlines. I like the whooshing sound they make as they fly by." scipy is extremely useful to have installed, and if you get *really* into it, then the sage library|system at http://sagemath.org is *extremely* useful... Jon. From deets at nospam.web.de Tue Dec 1 04:14:58 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 01 Dec 2009 10:14:58 +0100 Subject: how to debug extended module? In-Reply-To: References: Message-ID: <7nk54jF3m6bppU1@mid.uni-berlin.de> junyoung schrieb: > Hi, I am a newbie who want to implement a extend module to use native > python language with my own shared library. If it's a C shared library, don't bother extending it. Use ctypes to wrap it. Much easier, and no need for a compiler. > > to test wrapper library(extend module, name is 'test.so'), I created > some test-cases. > > There are some errors what I couldn't figure our reasons. > > ex) > SystemError: error return without exception set > .... > ... This indicates that you violated the exception protocol. http://docs.python.org/c-api/exceptions.html > so, I ran the ddd with python and then I set test.py as a argument of > it. > > ex) > ddd python > > in ddd > run with arguments : test.py > > > but in this situation, I couldn't step in my own shared library > (compiled as the debug mode). > > Is there any clear way to debug my extend module(that it, debug shared > library)?? I do it like this: # gdb python gdb $ set args test.py gdb $ run You can only debug a binary program (test.py isn't one, python is). But trough the args, you get yours script running. It *might* help to have a python debug build, I personally never needed that. Diez From maris at chown.lv Tue Dec 1 05:07:22 2009 From: maris at chown.lv (Maris Ruskulis) Date: Tue, 01 Dec 2009 12:07:22 +0200 Subject: Multiprocessing recycle worker if max request reached Message-ID: <4B14EADA.7040306@chown.lv> Hello! Currently I'm writing little xmlrpc server, because of one c library used there is memory leak, which couldn't be fixed. So I decide to use multiprocessing, spawn pool of workers and recycle worker if it reaches max request count. I managed to set counter for worker, but I could not figure out how to recycle worker if counter reaches some value. Is there some well known solution to solve this? Such functionality seems is not part of multiprocessing package. Thank You! -------------- next part -------------- A non-text attachment was scrubbed... Name: maris.vcf Type: text/x-vcard Size: 206 bytes Desc: not available URL: From Nadav.C at qualisystems.com Tue Dec 1 05:24:23 2009 From: Nadav.C at qualisystems.com (Nadav Chernin) Date: Tue, 1 Dec 2009 12:24:23 +0200 Subject: Inspect module - getargspec raise TypeError for built-in functions Message-ID: <97FB089C6E1F404CB0132AC3BB3E5C2701947E15@exchange.qualisystems.local> Hi, all When I use getargspec(func) for user-defined function, all is working OK, but using it for built-in functions raise TypeError: >>> import sys >>> getargspec(sys.getsizeof) Traceback (most recent call last): File "", line 1, in getargspec(sys.getsizeof) File "C:\Python26\lib\inspect.py", line 803, in getargspec raise TypeError('arg is not a Python function') TypeError: arg is not a Python function -------------- next part -------------- An HTML attachment was scrubbed... URL: From kevintylr at gmail.com Tue Dec 1 05:47:02 2009 From: kevintylr at gmail.com (Ethos) Date: Tue, 1 Dec 2009 02:47:02 -0800 (PST) Subject: NumPy installation won't import correctly Message-ID: <661c84c0-4f7a-4a77-9418-193aa9cacadf@13g2000prl.googlegroups.com> I installed NumPy for python 2.6 on my leopard macbook, using the nifty mac installer they now provide. I have the 2.6 official python distro installed on my computer, in addition to the 2.5 that is native on the mac. When I went to test out the installation, with 2.6, it gave me this: >>> import numpy Traceback (most recent call last): File "", line 1, in File "/Library/Frameworks/Python.framework/Versions/2.6/lib/ python2.6/site-packages/numpy/__init__.py", line 132, in import add_newdocs File "/Library/Frameworks/Python.framework/Versions/2.6/lib/ python2.6/site-packages/numpy/add_newdocs.py", line 9, in from lib import add_newdoc File "/Library/Frameworks/Python.framework/Versions/2.6/lib/ python2.6/site-packages/numpy/lib/__init__.py", line 4, in from type_check import * File "/Library/Frameworks/Python.framework/Versions/2.6/lib/ python2.6/site-packages/numpy/lib/type_check.py", line 8, in import numpy.core.numeric as _nx File "/Library/Frameworks/Python.framework/Versions/2.6/lib/ python2.6/site-packages/numpy/core/__init__.py", line 5, in import multiarray ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/2.6/ lib/python2.6/site-packages/numpy/core/multiarray.so, 2): no suitable image found. Did find: /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site- packages/numpy/core/multiarray.so: unknown required load command 0x80000022 The file that it claims it can't find a suitable image for does in fact exist in that directory. I'm stumped. Funny thing is, when I imported it using python2.5, it worked just fine. numpy.test(1,10) ran without a hitch. Thanks for the help. Please redirect me if this question belongs elsewhere. From lists at cheimes.de Tue Dec 1 05:57:12 2009 From: lists at cheimes.de (Christian Heimes) Date: Tue, 01 Dec 2009 11:57:12 +0100 Subject: Inspect module - getargspec raise TypeError for built-in functions In-Reply-To: <97FB089C6E1F404CB0132AC3BB3E5C2701947E15@exchange.qualisystems.local> References: <97FB089C6E1F404CB0132AC3BB3E5C2701947E15@exchange.qualisystems.local> Message-ID: Nadav Chernin wrote: > When I use getargspec(func) for user-defined function, all is working > OK, but using it for built-in functions raise TypeError: That's just fine and to be expected. It's not possible to inspect a C function. Only functions implemented in Python have the necessary metadata. Christian From d.dalton at iinet.net.au Tue Dec 1 06:01:22 2009 From: d.dalton at iinet.net.au (Daniel Dalton) Date: Tue, 1 Dec 2009 22:01:22 +1100 Subject: python and vc numbers In-Reply-To: <4b141261$1@dnews.tpgi.com.au> References: <7ngl1gF3ml76pU1@mid.individual.net> <20091130082059.GA10079@gwsc.vic.edu.au> <20091130100200.GB12885@gwsc.vic.edu.au> <50697b2c0911300226j126d0dfen6e22e053ccca6243@mail.gmail.com> <4b141261$1@dnews.tpgi.com.au> Message-ID: <20091201110122.GA19850@gwsc.vic.edu.au> > Can you make do with the tempfile module? Or you'd need to identify > from an external process which console is locked? Perhaps, I wrote a small hack: - Manually set environment variable TTYNUMBER in .bash_profile - Then use this in the script, to establish what tty I'm working with. Thanks -- Cheers, Dan http://members.iinet.net.au/~ddalton/ -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 198 bytes Desc: Digital signature URL: From floris.bruynooghe at gmail.com Tue Dec 1 06:12:02 2009 From: floris.bruynooghe at gmail.com (Floris Bruynooghe) Date: Tue, 1 Dec 2009 03:12:02 -0800 (PST) Subject: Bored. References: <16097008-372c-4522-889d-a78319c3575c@b2g2000yqi.googlegroups.com> Message-ID: On Nov 30, 11:52?pm, Stef Mientki wrote: > Well I thought that after 2 years you would know every detail of a > language ;-) Ouch, I must be especially stupid then! ;-) Floris From deets at nospam.web.de Tue Dec 1 06:33:27 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 01 Dec 2009 12:33:27 +0100 Subject: NumPy installation won't import correctly References: <661c84c0-4f7a-4a77-9418-193aa9cacadf@13g2000prl.googlegroups.com> Message-ID: <7nkd87F3mdj8mU1@mid.uni-berlin.de> Ethos wrote: > I installed NumPy for python 2.6 on my leopard macbook, using the > nifty mac installer they now provide. I have the 2.6 official python > distro installed on my computer, in addition to the 2.5 that is native > on the mac. When I went to test out the installation, with 2.6, it > gave me this: > >>>> import numpy > Traceback (most recent call last): > File "", line 1, in > File "/Library/Frameworks/Python.framework/Versions/2.6/lib/ > python2.6/site-packages/numpy/__init__.py", line 132, in > import add_newdocs > File "/Library/Frameworks/Python.framework/Versions/2.6/lib/ > python2.6/site-packages/numpy/add_newdocs.py", line 9, in > from lib import add_newdoc > File "/Library/Frameworks/Python.framework/Versions/2.6/lib/ > python2.6/site-packages/numpy/lib/__init__.py", line 4, in > from type_check import * > File "/Library/Frameworks/Python.framework/Versions/2.6/lib/ > python2.6/site-packages/numpy/lib/type_check.py", line 8, in > import numpy.core.numeric as _nx > File "/Library/Frameworks/Python.framework/Versions/2.6/lib/ > python2.6/site-packages/numpy/core/__init__.py", line 5, in > import multiarray > ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/2.6/ > lib/python2.6/site-packages/numpy/core/multiarray.so, 2): no suitable > image found. Did find: > /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site- > packages/numpy/core/multiarray.so: unknown required load command > 0x80000022 > > The file that it claims it can't find a suitable image for does in > fact exist in that directory. I'm stumped. > > Funny thing is, when I imported it using python2.5, it worked just > fine. numpy.test(1,10) ran without a hitch. Looks like a binary format issue to me. What does file /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/numpy/core/multiarray.so give you, and how does it compare to file /Library/Frameworks/Python.framework/Versions/2.6/bin/python Maybe you need to strip the binaries to your native arch, using lipo. Diez From mohsen at pahlevanzadeh.org Tue Dec 1 06:47:42 2009 From: mohsen at pahlevanzadeh.org (Mohsen Pahlevanzadeh) Date: Tue, 01 Dec 2009 15:17:42 +0330 Subject: Function parameters list In-Reply-To: <97FB089C6E1F404CB0132AC3BB3E5C2701947DA4@exchange.qualisystems.local> References: <97FB089C6E1F404CB0132AC3BB3E5C2701947DA4@exchange.qualisystems.local> Message-ID: <1259668062.3524.4.camel@debian> You need to define a function same following definition: def myfunc(*arglist): yourbody ####calling function: myfunc("it's first argument","It's second argument","It's thr argument") On Tue, 2009-12-01 at 10:15 +0200, Nadav Chernin wrote: > Hello, all > > > > I need to know dynamically parameters of any function (prototype). > > > > Is there some way to get it? > > > > Thanks, Nadav > > From jpiitula at ling.helsinki.fi Tue Dec 1 07:20:58 2009 From: jpiitula at ling.helsinki.fi (Jussi Piitulainen) Date: 01 Dec 2009 14:20:58 +0200 Subject: problem with lambda / closures References: Message-ID: Terry Reedy writes: > definitions. Lambda expressions create functions just like def > statements and are not closures and do not create closure unless > nested within another function definition. Thinking otherwise is Seems quite closed in the top level environment to me: Python 2.3.4 (#1, Jul 16 2009, 07:03:37) >>> k = 'outer' >>> f = lambda : k >>> def test(): ... k = 'inner' ... return f() ... >>> test() 'outer' >>> k = 'thing' >>> test() 'thing' From cournape at gmail.com Tue Dec 1 07:26:51 2009 From: cournape at gmail.com (David Cournapeau) Date: Tue, 1 Dec 2009 21:26:51 +0900 Subject: NumPy installation won't import correctly In-Reply-To: <661c84c0-4f7a-4a77-9418-193aa9cacadf@13g2000prl.googlegroups.com> References: <661c84c0-4f7a-4a77-9418-193aa9cacadf@13g2000prl.googlegroups.com> Message-ID: <5b8d13220912010426r15d2615cn412c75afddd0083c@mail.gmail.com> On Tue, Dec 1, 2009 at 7:47 PM, Ethos wrote: > ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/2.6/ > lib/python2.6/site-packages/numpy/core/multiarray.so, 2): no suitable > image found. ?Did find: > ? ? ? ?/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site- > packages/numpy/core/multiarray.so: unknown required load command > 0x80000022 I have never seen this error, but it seems pretty common (for other software, even unrelated to pyhon), from a quick google search. We have just released the first RC for numpy 1.4.0. Could you check whether you still see the problem with it ? Note that numpy questions are more likely to be answered on the numpy Mailing List, cheers, David From Nadav.C at qualisystems.com Tue Dec 1 07:27:11 2009 From: Nadav.C at qualisystems.com (Nadav Chernin) Date: Tue, 1 Dec 2009 14:27:11 +0200 Subject: Python-list Digest, Vol 75, Issue 6 In-Reply-To: References: Message-ID: <97FB089C6E1F404CB0132AC3BB3E5C2701947E69@exchange.qualisystems.local> Nadav Chernin wrote: > When I use getargspec(func) for user-defined function, all is working > OK, but using it for built-in functions raise TypeError: That's just fine and to be expected. It's not possible to inspect a C function. Only functions implemented in Python have the necessary metadata. Christian OK, so how to know prototype of C functions? From victorsubervi at gmail.com Tue Dec 1 08:05:21 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Tue, 1 Dec 2009 08:05:21 -0500 Subject: os.remove() permission problem In-Reply-To: References: <4dc0cfea0911301121u50efa2aat807e245c2ef05f59@mail.gmail.com> Message-ID: <4dc0cfea0912010505s121d6951xa580feeca05ce2f8@mail.gmail.com> On Mon, Nov 30, 2009 at 5:06 PM, Christian Heimes wrote: > Victor Subervi wrote: > > When I go into the python interpreter and execute that statement, it > > succeeds. What have I missed? > > You are confusing the permissions of a Unix file system. In order to > create or a remove a file from a directory you need the x and w > permission to enter the directory (x) and to modify (w) the directory > entry. > Well, that's what I've tried. I've loaded the permissions up, 0777, and it still throws the same error. I've also tried os.chmod(file, 0777) from the script, and I get the same permissions error. I can do all of this from the python prompt. I've set the ownership of the file attempting these commands to root.root. Nothing works. Please advise. V -------------- next part -------------- An HTML attachment was scrubbed... URL: From lists at cheimes.de Tue Dec 1 08:12:13 2009 From: lists at cheimes.de (Christian Heimes) Date: Tue, 01 Dec 2009 14:12:13 +0100 Subject: os.remove() permission problem In-Reply-To: <4dc0cfea0912010505s121d6951xa580feeca05ce2f8@mail.gmail.com> References: <4dc0cfea0911301121u50efa2aat807e245c2ef05f59@mail.gmail.com> <4dc0cfea0912010505s121d6951xa580feeca05ce2f8@mail.gmail.com> Message-ID: <4B15162D.5080301@cheimes.de> Victor Subervi wrote: > Well, that's what I've tried. I've loaded the permissions up, 0777, and it > still throws the same error. I've also tried os.chmod(file, 0777) from the > script, and I get the same permissions error. I can do all of this from the > python prompt. I've set the ownership of the file attempting these commands > to root.root. Nothing works. Please advise. You have to set the write and execute permssion on *directory*, not on the file. unlink (aka remove) requires write permission on the directory in order to remove the file. It's like in the real world. You may be allowed to modify a document (w permission on the file) but you may not be allowed to remove it from its cabinet (w permission on the directory). Christian From gnarlodious at gmail.com Tue Dec 1 08:27:22 2009 From: gnarlodious at gmail.com (Gnarlodious) Date: Tue, 1 Dec 2009 05:27:22 -0800 (PST) Subject: Can't print Chinese to HTTP References: <4b13c039$0$7478$9b622d9e@news.freenet.de> Message-ID: <8810fcc1-3e2d-42ce-839c-d03774e02ea1@l13g2000yqb.googlegroups.com> On Nov 30, 5:53?am, "Martin v. L?wis" wrote: > #!/usr/bin/python > print("Content-type:text/plain;charset=utf-8\n\n") > sys.stdout.buffer.write('?\n'.encode("utf-8")) Does this work for anyone? Because all I get is a blank page. Nothing. If I can establish what SHOULD work, maybe I can diagnose this problem. -- Gnarlie From lie.1296 at gmail.com Tue Dec 1 08:41:37 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Wed, 02 Dec 2009 00:41:37 +1100 Subject: Python-list Digest, Vol 75, Issue 6 In-Reply-To: References: Message-ID: <4b151d7e@dnews.tpgi.com.au> On 12/1/2009 11:27 PM, Nadav Chernin wrote: > Nadav Chernin wrote: > > When I use getargspec(func) for user-defined function, all is > working > > OK, but using it for built-in functions raise TypeError: > > That's just fine and to be expected. It's not possible to > inspect a C function. Only functions implemented in Python have the > necessary metadata. > > Christian > > OK, so how to know prototype of C functions? read the docs.. From victorsubervi at gmail.com Tue Dec 1 08:41:50 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Tue, 1 Dec 2009 08:41:50 -0500 Subject: os.remove() permission problem In-Reply-To: <4B15162D.5080301@cheimes.de> References: <4dc0cfea0911301121u50efa2aat807e245c2ef05f59@mail.gmail.com> <4dc0cfea0912010505s121d6951xa580feeca05ce2f8@mail.gmail.com> <4B15162D.5080301@cheimes.de> Message-ID: <4dc0cfea0912010541u31e72467l9557a4c7b6dac83f@mail.gmail.com> On Tue, Dec 1, 2009 at 8:12 AM, Christian Heimes wrote: > Victor Subervi wrote: > > Well, that's what I've tried. I've loaded the permissions up, 0777, and > it > > still throws the same error. I've also tried os.chmod(file, 0777) from > the > > script, and I get the same permissions error. I can do all of this from > the > > python prompt. I've set the ownership of the file attempting these > commands > > to root.root. Nothing works. Please advise. > > You have to set the write and execute permssion on *directory*, not on > the file. unlink (aka remove) requires write permission on the directory > in order to remove the file. > That worked! > > It's like in the real world. You may be allowed to modify a document (w > permission on the file) but you may not be allowed to remove it from its > cabinet (w permission on the directory). > THANK YOU for this analogy. Hopefully, that will help me remember it the next time it occurs ;) V -------------- next part -------------- An HTML attachment was scrubbed... URL: From list at qtrac.plus.com Tue Dec 1 09:03:36 2009 From: list at qtrac.plus.com (Mark Summerfield) Date: Tue, 1 Dec 2009 06:03:36 -0800 (PST) Subject: Moving from Python 2 to Python 3: A 4 page "cheat sheet" Message-ID: <291d64cb-cc5c-4109-822c-84d58ed7b18b@k17g2000yqh.googlegroups.com> I've produced a 4 page document that provides a very concise summary of Python 2<->3 differences plus the most commonly used new Python 3 features. It is aimed at existing Python 2 programmers who want to start writing Python 3 programs and want to use Python 3 idioms rather than those from Python 2 where the idioms differ. It uses Python 3.1 syntax since that looks like being the standard for a few years in view of the language moratorium. The document is U.S. Letter size but will also print fine on A4 printers. It is available as a free PDF download (no registration or anything) from InformIT's website. Here's the direct link: http://ptgmedia.pearsoncmg.com/imprint_downloads/informit/promotions/python/python2python3.pdf And of course, if you want more on Python 3, there's always the documentation---or my book:-) "Programming in Python 3 (Second Edition)" ISBN-10: 0321680561. From fetchinson at googlemail.com Tue Dec 1 09:22:07 2009 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Tue, 1 Dec 2009 15:22:07 +0100 Subject: Moving from Python 2 to Python 3: A 4 page "cheat sheet" In-Reply-To: <291d64cb-cc5c-4109-822c-84d58ed7b18b@k17g2000yqh.googlegroups.com> References: <291d64cb-cc5c-4109-822c-84d58ed7b18b@k17g2000yqh.googlegroups.com> Message-ID: > I've produced a 4 page document that provides a very concise summary > of Python 2<->3 differences plus the most commonly used new Python 3 > features. It is aimed at existing Python 2 programmers who want to > start writing Python 3 programs and want to use Python 3 idioms rather > than those from Python 2 where the idioms differ. > > It uses Python 3.1 syntax since that looks like being the standard for > a few years in view of the language moratorium. This really looks very useful, thanks a lot! I've been wishing something like this existed for a while, really handy. Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From jlconlin at gmail.com Tue Dec 1 09:29:17 2009 From: jlconlin at gmail.com (Jeremy) Date: Tue, 1 Dec 2009 06:29:17 -0800 (PST) Subject: How to prevent re.split() from removing part of string References: Message-ID: On Nov 30, 5:24?pm, MRAB wrote: > Jeremy wrote: > > I am using re.split to... well, split a string into sections. ?I want > > to split when, following a new line, there are 4 or fewer spaces. ?The > > pattern I use is: > > > ? ? ? ? sections = re.split('\n\s{,4}[^\s]', lineoftext) > > > This splits appropriately but I lose the character matched by [^s]. ?I > > know I can put parentheses around [^s] and keep the matched character, > > but the character is placed in it's own element of the list instead of > > with the rest of the lineoftext. > > > Does anyone know how I can accomplish this without losing the matched > > character? > > First of all, \s matches any character that's _whitespace_, such as > space, "\t", "\n", "\r", "\f". There's also \S, which matches any > character that's not whitespace. Thanks for the reminder. I knew \S existed, but must have forgotten about it. > > But in answer to your question, use a look-ahead: > > ? ? ?sections = re.split('\n {,4}(?=\S)', lineoftext) Yep, that does the trick. Thanks for the help! Jeremy From steve at REMOVE-THIS-cybersource.com.au Tue Dec 1 09:38:01 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 01 Dec 2009 14:38:01 GMT Subject: Feature request: String-inferred names References: <17a26a8c-3358-4152-8871-2dcaa7e97220@g23g2000vbr.googlegroups.com> <87skc0zstu.fsf@benfinney.id.au> Message-ID: <009eaec9$0$26893$c3e8da3@news.astraweb.com> On Mon, 30 Nov 2009 18:55:46 -0800, The Music Guy wrote: > Lie Ryan, I think I see what you're saying about using __dict__ to add > members to a class, but it's not quite the same. __dict__ is only for > attributes, NOT properties, methods, etc. which all come from the class > of an object rather than the object's __dict__. Almost but not quite. It's just special double-underscore methods like __init__ __add__ etc that have to be in the class rather than the instance. (To be precise, you can add such a method to the instance, but it won't be called automatically.) Likewise staticmethods and classmethods won't work correctly unless they are in the class. But ordinary methods work fine: the only tricky bit is creating them in the first place. >>> class K(object): ... pass ... >>> k = K() >>> import types >>> k.method = types.MethodType(lambda self: "I am %s" % self, k) >>> k.method() 'I am <__main__.K object at 0xb7cc7d4c>' -- Steven From gnarlodious at gmail.com Tue Dec 1 09:42:13 2009 From: gnarlodious at gmail.com (Gnarlodious) Date: Tue, 1 Dec 2009 06:42:13 -0800 (PST) Subject: Moving from Python 2 to Python 3: A 4 page "cheat sheet" References: <291d64cb-cc5c-4109-822c-84d58ed7b18b@k17g2000yqh.googlegroups.com> Message-ID: On Dec 1, 7:03?am, Mark Summerfield wrote: > "Programming in Python 3 (Second Edition)" ISBN-10: 0321680561. I ordered it... -- Gnarlie http://Gnarlodious.com From necronymouse at gmail.com Tue Dec 1 10:08:34 2009 From: necronymouse at gmail.com (Necronymouse) Date: Tue, 1 Dec 2009 07:08:34 -0800 (PST) Subject: Bored. References: <16097008-372c-4522-889d-a78319c3575c@b2g2000yqi.googlegroups.com> Message-ID: <3d634342-d98e-4023-949a-6819c74a1025@u7g2000yqm.googlegroups.com> Thanks for reaction, I will prohably choose some project as you said... From lie.1296 at gmail.com Tue Dec 1 10:36:09 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Wed, 02 Dec 2009 02:36:09 +1100 Subject: Can't print Chinese to HTTP In-Reply-To: <8810fcc1-3e2d-42ce-839c-d03774e02ea1@l13g2000yqb.googlegroups.com> References: <4b13c039$0$7478$9b622d9e@news.freenet.de> <8810fcc1-3e2d-42ce-839c-d03774e02ea1@l13g2000yqb.googlegroups.com> Message-ID: <4b153863@dnews.tpgi.com.au> On 12/2/2009 12:27 AM, Gnarlodious wrote: > On Nov 30, 5:53 am, "Martin v. L?wis" wrote: > >> #!/usr/bin/python >> print("Content-type:text/plain;charset=utf-8\n\n") >> sys.stdout.buffer.write('?\n'.encode("utf-8")) > > Does this work for anyone? Because all I get is a blank page. Nothing. > If I can establish what SHOULD work, maybe I can diagnose this > problem. > with a minor fix (import sys) that runs without errors in Python 3.1 (Vista), but the result is a bit disturbing... -------------------------- ? Content-type:text/plain;charset=utf-8 -------------------------- (is this a bug? or just undefined behavior?) the following works correctly in python 3.1: --------------------------- #!/usr/bin/python import sys print = lambda s: sys.stdout.buffer.write(s.encode('utf-8')) print("Content-type:text/plain;charset=utf-8\n\n") print('?\n') ---------------------------- (and that code will definitely fail with python2 because of the print assignment, an insurance if your server happens to be misconfigured to run python2) From drobinow at gmail.com Tue Dec 1 10:38:38 2009 From: drobinow at gmail.com (David Robinow) Date: Tue, 1 Dec 2009 10:38:38 -0500 Subject: Python PIL and Vista/Windows 7 .. show() not working ... In-Reply-To: References: Message-ID: <4eb0089f0912010738k6fcd3e26ob88832d87182019a@mail.gmail.com> On Mon, Nov 30, 2009 at 12:57 PM, Esmail wrote: > Hello all. > > I am using the PIL 1.1.6 and Python 2.6.x under XP without any > problems. However, I can't display any images under Vista > or Windows 7. I could understand Windows 7 as it's relatively > new, but Vista has been around for a bit. > > Sample code: > > ?import Image > > ?im = Image.open('c://mypic.jpg') > ?im.show() > > > this will work fine under XP, but under Windows 7 and Vista > the default image viewer will come up with some error message > that the image can't be found. > > I tried with an external image view program and tried to supply > it via the command parameter to show - but that too didn't work. > > Definition: ? ? im.show(self, title=None, command=None) > > Any suggestions/help/workarounds? If you can get this to work > with Vista or Windows 7 I'd ?love to hear from you. > > Thanks! > Esmail > > -- > http://mail.python.org/mailman/listinfo/python-list > show() executes a command like: os.system("start /wait TempFile.BMP && del /f TempFile.BMP") On Vista, HELP START displays the following: ... If Command Extensions are enabled, external command invocation through the command line or the START command changes as follows: ... When executing an application that is a 32-bit GUI application, CMD.EXE does not wait for the application to terminate before returning to the command prompt. This new behavior does NOT occur if executing within a command script. ... The "/wait" apparently does nothing and the image file is deleted before the image viewer gets a chance to open it. (I think) [I don't understand why it works in XP since "HELP START" says basically the same thing] I haven't tried to fix it yet but a likely solution is to split up the command. os.system("start TempFile.BMP") wait a second os.system(del /f TempFile.BMP") From gnarlodious at gmail.com Tue Dec 1 10:51:19 2009 From: gnarlodious at gmail.com (Gnarlodious) Date: Tue, 1 Dec 2009 07:51:19 -0800 (PST) Subject: Can't print Chinese to HTTP References: <4b13c039$0$7478$9b622d9e@news.freenet.de> <8810fcc1-3e2d-42ce-839c-d03774e02ea1@l13g2000yqb.googlegroups.com> <4b153863@dnews.tpgi.com.au> Message-ID: On Dec 1, 8:36?am, Lie Ryan wrote: > #!/usr/bin/python > import sys > print = lambda s: sys.stdout.buffer.write(s.encode('utf-8')) > print("Content-type:text/plain;charset=utf-8\n\n") > print('?\n') HA! IT WORKS! Thank you thank you thank you. I don't understand the lambda functionality but will figure it out. BTW this is OSX 10.6 and Python 3.1.1. Again, thank you for the help. -- Gnarlie From bruno.42.desthuilliers at websiteburo.invalid Tue Dec 1 10:58:00 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 01 Dec 2009 16:58:00 +0100 Subject: Feature request: String-inferred names In-Reply-To: References: <17a26a8c-3358-4152-8871-2dcaa7e97220@g23g2000vbr.googlegroups.com> <87skc0zstu.fsf@benfinney.id.au> Message-ID: <4b153d02$0$11568$426a74cc@news.free.fr> The Music Guy a ?crit : (snip) > Lie Ryan, I think I see what you're saying about using __dict__ to add > members No "members" in Python - only attributes. > to a class, but it's not quite the same. __dict__ is only for > attributes, NOT properties, methods, etc. which all come from the > class of an object rather than the object's __dict__. properties and methods (well, functions actually) ARE attributes... of the class object. And you can of course access the obj.__class__.__dict__ Just for the record... From aahz at pythoncraft.com Tue Dec 1 11:45:13 2009 From: aahz at pythoncraft.com (Aahz) Date: 1 Dec 2009 08:45:13 -0800 Subject: UnicodeDecodeError? Argh! Nothing works! I'm tired and hurting and... References: <031bc732$0$1336$c3e8da3@news.astraweb.com> Message-ID: In article <031bc732$0$1336$c3e8da3 at news.astraweb.com>, Steven D'Aprano wrote: > >Good grief, it's about six weeks away from 2010 and Thunderbird still >uses mbox as it's default mail box format. Hello, the nineties called, >they want their mail formats back! Are the tbird developers on crack or >something? I can't believe that they're still using that crappy format. Just to be contrary, I *like* mbox. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ The best way to get information on Usenet is not to ask a question, but to post the wrong information. From robert.kern at gmail.com Tue Dec 1 12:33:26 2009 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 01 Dec 2009 12:33:26 -0500 Subject: The Strong Relationship between MatLab and MatPlotLib? What One Needs to Know? In-Reply-To: References: Message-ID: On 2009-11-29 15:39 PM, W. eWatson wrote: > Although MatPlotLib has plenty of examples, they do not seem to cover > the fundamentals like figure. It seems as though in someway this is > dependent upon a user's knowledge of MatLab. Is this true, or oes > MatPlotLib provide some description of how forming a figure works? The matplotlib mailing list is over here: https://lists.sourceforge.net/lists/listinfo/matplotlib-users -- 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 gd_usenet at spamfence.net Tue Dec 1 12:36:08 2009 From: gd_usenet at spamfence.net (=?UTF-8?Q?G=C3=BCnther?= Dietrich) Date: Tue, 01 Dec 2009 18:36:08 +0100 Subject: NumPy installation won't import correctly References: <661c84c0-4f7a-4a77-9418-193aa9cacadf@13g2000prl.googlegroups.com> Message-ID: <9p0gu6-7pj.ln1@spamfence.net> Ethos wrote: >I installed NumPy for python 2.6 on my leopard macbook, using the >nifty mac installer they now provide. I have the 2.6 official python >distro installed on my computer, in addition to the 2.5 that is native >on the mac. When I went to test out the installation, with 2.6, it >gave me this: > >>>> import numpy >Traceback (most recent call last): > File "", line 1, in > File "/Library/Frameworks/Python.framework/Versions/2.6/lib/ >python2.6/site-packages/numpy/__init__.py", line 132, in > import add_newdocs > File "/Library/Frameworks/Python.framework/Versions/2.6/lib/ >python2.6/site-packages/numpy/add_newdocs.py", line 9, in > from lib import add_newdoc > File "/Library/Frameworks/Python.framework/Versions/2.6/lib/ >python2.6/site-packages/numpy/lib/__init__.py", line 4, in > from type_check import * > File "/Library/Frameworks/Python.framework/Versions/2.6/lib/ >python2.6/site-packages/numpy/lib/type_check.py", line 8, in > import numpy.core.numeric as _nx > File "/Library/Frameworks/Python.framework/Versions/2.6/lib/ >python2.6/site-packages/numpy/core/__init__.py", line 5, in > import multiarray >ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/2.6/ >lib/python2.6/site-packages/numpy/core/multiarray.so, 2): no suitable >image found. Did find: > /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site- >packages/numpy/core/multiarray.so: unknown required load command >0x80000022 I had the same problem when I tried to use the MacPorts installation of python3 within blender2.5alpha0 (I pointed the PYTHONPATH to the respective MacPorts python3 folder). I figured out, that the blender binary is a 64bit one, but the libraries of the MacPorts python3 are 32bit ones and these two don't fit together. Then I found out, that -- as opposed to blender 2.4x -- blender 2.5 comes with all the standard python library bundled. So I'm fine with the pure blender 2.5 for the testing. Best regards, G?nther From dickinsm at gmail.com Tue Dec 1 12:50:06 2009 From: dickinsm at gmail.com (Mark Dickinson) Date: Tue, 1 Dec 2009 09:50:06 -0800 (PST) Subject: Moving from Python 2 to Python 3: A 4 page "cheat sheet" References: <291d64cb-cc5c-4109-822c-84d58ed7b18b@k17g2000yqh.googlegroups.com> Message-ID: On Dec 1, 2:03?pm, Mark Summerfield wrote: > I've produced a 4 page document that provides a very concise summary > of Python 2<->3 differences plus the most commonly used new Python 3 > features. Very nice indeed! My only quibble is with the statement on the first page that the 'String % operator is deprecated'. I'm not sure that's true, for all values of 'deprecated'. There don't appear to be any definite plans for getting rid of it just yet. Mark From python at rcn.com Tue Dec 1 13:21:03 2009 From: python at rcn.com (Raymond Hettinger) Date: Tue, 1 Dec 2009 10:21:03 -0800 (PST) Subject: Feature request: String-inferred names References: <7n6p0qF3krjueU1@mid.individual.net> Message-ID: <9a3e8bcd-245e-4a5d-bc9e-34b016303767@k17g2000yqh.googlegroups.com> [Gregory Ewing] > >>I just posted to my blog about a feature that I'd like to see added to > >>Python. > > >>http://alphaios.blogspot.com/2009/11/python-string-inferred-names-wor... > > I don't think getattr and setattr are used anywhere near > frequently enough to justify special syntax. Perhaps that would change if we had the proposed syntax. I would expect that powerful and expressive idioms would emerge. > (A frequent question asked by newcomers from certain > other kinds of languages is something like "How do I > assign to a variable whose name is in another variable?" > The answer is almost always "Don't do that, use a > dictionary.") The proposed syntax works better with class namespaces which automatically provide inheritance logic and method binding. Dictionaries don't provide equivalent support. Raymond From lie.1296 at gmail.com Tue Dec 1 13:30:12 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Wed, 02 Dec 2009 05:30:12 +1100 Subject: Moving from Python 2 to Python 3: A 4 page "cheat sheet" In-Reply-To: <291d64cb-cc5c-4109-822c-84d58ed7b18b@k17g2000yqh.googlegroups.com> References: <291d64cb-cc5c-4109-822c-84d58ed7b18b@k17g2000yqh.googlegroups.com> Message-ID: <4b156121$1@dnews.tpgi.com.au> On 12/2/2009 1:03 AM, Mark Summerfield wrote: > I've produced a 4 page document that provides a very concise summary > of Python 2<->3 differences plus the most commonly used new Python 3 > features. It is aimed at existing Python 2 programmers who want to > start writing Python 3 programs and want to use Python 3 idioms rather > than those from Python 2 where the idioms differ. > > It uses Python 3.1 syntax since that looks like being the standard for > a few years in view of the language moratorium. > > The document is U.S. Letter size but will also print fine on A4 > printers. > > It is available as a free PDF download (no registration or anything) > from InformIT's website. Here's the direct link: > http://ptgmedia.pearsoncmg.com/imprint_downloads/informit/promotions/python/python2python3.pdf > > And of course, if you want more on Python 3, there's always the > documentation---or my book:-) > "Programming in Python 3 (Second Edition)" ISBN-10: 0321680561. Nice. I suggest changing the lambda example a bit, the current example says: Python 2 Python 3 lambda (a,b): a + b lambda t: t[0] + t[1] lambda a, b: a + b into something like: Python 2 Python 3 lambda (a,b),c: a + b + c lambda t, c: t[0] + t[1] + c lambda a, b, c: a + b + c it is unclear at first sight that it refers to tuple argument unpacking. There should also some mention that tuple argument unpacking for regular function (def) is also gone. Also, I'm not sure what this change is referring to: Python 2 Python 3 L = list(seq) L = sorted(seq) L.sort() L.sort is still available in python, and sorted() have been available since python 2. Both list.sort() and sorted() are for different purpose, and neither will be deprecated. What's the change here? From jabronson at gmail.com Tue Dec 1 13:31:34 2009 From: jabronson at gmail.com (Joshua Bronson) Date: Tue, 1 Dec 2009 10:31:34 -0800 (PST) Subject: python bijection References: <5a99def7-e182-4782-9054-f1035affa34d@x5g2000prf.googlegroups.com> <7n39ojF3jj6iuU1@mid.individual.net> <12c55890-118d-4655-b6c0-c908c9734a17@a32g2000yqm.googlegroups.com> Message-ID: <85100df7-a8b0-47e9-a854-ba8a8a2f3b98@r31g2000vbi.googlegroups.com> On Nov 27, 1:12?pm, Francis Carr wrote: > I was really inspired by this discussion thread! :-) > > After much tinkering, I think I have a simpler solution. ?Just make > the inverse mapping accessible via an attribute, -AND- bind the > inverse of -THAT- mapping back to the original. ?The result is a > python dict with NO NEW METHODS except this inverse-mapping > attribute. ?I have posted it on code.activestate.com as href="http://code.activestate.com/recipes/576968/">Recipe 576968: > Flipdict -- python dict that also maintains a one-to-one inverse > mapping > > ?-- F. Carr I noticed the phonebook example in your ActiveState recipe and thought you might consider changing it to something like husbands to wives, since the names-to-phone-numbers relation is many-to-many. The built- in htmlentifydefs module provides fodder for a real-world example: It maintains name2codepoint and codepoint2name as two separate dicts. Raymond, do you think there might be any future in including a built- in bidict data structure in Python? At least there's one built-in module that might benefit from it. P.S. I moved bidict to its own repo at http://bitbucket.org/jab/bidict/ and released it to PyPI as http://pypi.python.org/pypi/bidict. From victorsubervi at gmail.com Tue Dec 1 13:32:41 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Tue, 1 Dec 2009 14:32:41 -0400 Subject: getattr problem Message-ID: <4dc0cfea0912011032s3fc0be8doa361bb390697682f@mail.gmail.com> Hi; I have the following code that execute without a problem: import sys,os sys.path.append(os.getcwd()) import options storesTables = [] junkStores = string.join(addStore(), ', ') for table in optionsTables(): if table not in ('particulars', junkStores): storesTables.append(table) for table in storesTables: try: fn = getattr(options, table) print fn() except: pass I need to change the obvious line to this or something similar (that actually works): fn = getattr(options, '%s("names")' % table) That is, I need to pass the variable "names" to each table as it is called. How do I do this? TIA, Victor -------------- next part -------------- An HTML attachment was scrubbed... URL: From subhakolkata1234 at gmail.com Tue Dec 1 14:06:11 2009 From: subhakolkata1234 at gmail.com (joy99) Date: Tue, 1 Dec 2009 11:06:11 -0800 (PST) Subject: Question on Python as career Message-ID: <614b8dde-324b-4d54-8e73-7a96e4c0b1cf@a21g2000yqc.googlegroups.com> Dear Group, I am a researcher in India's one of the premier institutes.(Indian Institute of Science,Bangalore). I have done one MA in Linguistics, did a PhD in Natural Language Processing and doing a Post Doctoral now. Earlier I knew C/C++ and presently work on Python on WinXP. I use IDLE to as gui. My area of work are: (i) Statistical Modeling, (ii) Neural Networks; (iii) Machine Learning. I have developed the following toolkits: (i) A web based crawler; (ii) A Bayesian classifier; (iii) One NER engine; (iv) One XML parser; (v) One PoS Tagger; (vi) One Parser based on CRF; (vii) One MLE training system; (viii) One Spell Checker; (ix) One Transliteration System; I have developed them either in Python2.5 and Python2.6. After I complete my Post Doctoral which may be only 2-3 months away, with this knowledge can I join IT? Or Do I have to learn anything new? Are there any India based opportunities- as I checked Python job board it is very less. If I get anything after completing my Post Doc with present base of knowledge what profiles I may expect? If I have to learn anything what they may be and how much time generally a person needs to learn them and what may be the profile expectancy? As this room is filled up with many expert IT professionals if any body can suggest me on these. Best Regards, Subhabrata Banerjee. From nad at acm.org Tue Dec 1 14:07:53 2009 From: nad at acm.org (Ned Deily) Date: Tue, 01 Dec 2009 11:07:53 -0800 Subject: Can't print Chinese to HTTP References: <4b13c039$0$7478$9b622d9e@news.freenet.de> Message-ID: In article , Gnarlodious wrote: > I symlinked to the new Python, and no I do not want to roll it back > because it is work (meaning I would have to type "sudo"). > ls /usr/bin/python > lrwxr-xr-x 1 root wheel 63 Nov 20 21:24 /usr/bin/python -> /Library/ > Frameworks/Python.framework/Versions/3.1/bin/python3.1 > Ugh, I have not been able to program in 11 days. You should *not* do this. The files in /usr/bin are installed and controlled by Apple and, in particular, /usr/bin/python is the Apple supplied python. By changing /usr/bin/python, you are risking incorrect operation of other system programs that may depend on it plus it is quite likely that an OS X software update will overwrite this location breaking your applications. Use /usr/local/bin/python3.1 instead. -- Ned Deily, nad at acm.org From python at rcn.com Tue Dec 1 14:11:39 2009 From: python at rcn.com (Raymond Hettinger) Date: Tue, 1 Dec 2009 11:11:39 -0800 (PST) Subject: python bijection References: <5a99def7-e182-4782-9054-f1035affa34d@x5g2000prf.googlegroups.com> <7n39ojF3jj6iuU1@mid.individual.net> <12c55890-118d-4655-b6c0-c908c9734a17@a32g2000yqm.googlegroups.com> <85100df7-a8b0-47e9-a854-ba8a8a2f3b98@r31g2000vbi.googlegroups.com> Message-ID: [Joshua Bronson] > Raymond, do you think there might be any future in including a built- > in bidict data structure in Python? I don't think so. There are several forces working against it: * the recipe is new, so it hasn't had a chance to mature or to gain a fan club. * there are many approaches to the solving the problem and there is no reason to assume this one is the best. * it extends the language with arcane syntax tricks instead of using the language as designed by Guido. That makes it harder to learn and remember. * we've already got one (actually two). The two dictionary approach uses plain python, requires no new learning, and is more flexible. Also, sqlite3 provides another way to use multiple lookups to a single record. The database approach is much more general (extending to trijections, allowing multiple sort orders, providing persistence, etc). * the semantics of a bijection aren't obvious: b['x'] = 'ex' # first record: ('x', 'ex') b['y'] = 'why' # second record: ('y', 'why') b[:'why'] = 'x' # do two records collapse into one? is there an error? * the proposed syntax doesn't address the issue covered in my previous post. Since bijections are symmetrical, they do not have an obvious direction (which is the primary key, the husband or the wife?). The syntax needs to allow user names to make it clear which is being accessed: marriages.h2w['john'] = 'amy' marriages.w2h['amy'] = 'john' Contrast this with: marriages['jordan'] = 'taylor' # are you sure you got the order correct? marriages[:'taylor'] = 'jordan' # this is easy to get backwards Raymond From jeanmichel at sequans.com Tue Dec 1 14:17:39 2009 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Tue, 01 Dec 2009 20:17:39 +0100 Subject: getattr problem In-Reply-To: <4dc0cfea0912011032s3fc0be8doa361bb390697682f@mail.gmail.com> References: <4dc0cfea0912011032s3fc0be8doa361bb390697682f@mail.gmail.com> Message-ID: <4B156BD3.1020601@sequans.com> Victor Subervi wrote: > Hi; > I have the following code that execute without a problem: > > import sys,os > sys.path.append(os.getcwd()) > import options > storesTables = [] > junkStores = string.join(addStore(), ', ') > for table in optionsTables(): > if table not in ('particulars', junkStores): > storesTables.append(table) > for table in storesTables: > try: > fn = getattr(options, table) > print fn() > except: > pass > > I need to change the obvious line to this or something similar (that > actually works): > > fn = getattr(options, '%s("names")' % table) > > That is, I need to pass the variable "names" to each table as it is > called. How do I do this? > TIA, > Victor I'm not sure I understood what your are trying to do. try: fn = getattr(options, table) fn(names) except: pass Coud be the answer, providing that table is a callable object. But I dont see any variable names defined in your code example, so I'm a little bit confused JM From victorsubervi at gmail.com Tue Dec 1 14:32:02 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Tue, 1 Dec 2009 15:32:02 -0400 Subject: getattr problem In-Reply-To: <4B156BD3.1020601@sequans.com> References: <4dc0cfea0912011032s3fc0be8doa361bb390697682f@mail.gmail.com> <4B156BD3.1020601@sequans.com> Message-ID: <4dc0cfea0912011132h1242cfdeuc736cbe2d3ebd177@mail.gmail.com> On Tue, Dec 1, 2009 at 3:17 PM, Jean-Michel Pichavant < jeanmichel at sequans.com> wrote: > Victor Subervi wrote: > >> Hi; >> I have the following code that execute without a problem: >> >> import sys,os >> sys.path.append(os.getcwd()) >> import options >> storesTables = [] >> junkStores = string.join(addStore(), ', ') >> for table in optionsTables(): >> if table not in ('particulars', junkStores): >> storesTables.append(table) >> for table in storesTables: >> try: >> fn = getattr(options, table) >> print fn() >> except: >> pass >> >> I need to change the obvious line to this or something similar (that >> actually works): >> >> fn = getattr(options, '%s("names")' % table) >> >> That is, I need to pass the variable "names" to each table as it is >> called. How do I do this? >> TIA, >> Victor >> > I'm not sure I understood what your are trying to do. > > > try: > fn = getattr(options, table) > fn(names) > except: > pass > Thank you. V -------------- next part -------------- An HTML attachment was scrubbed... URL: From nad at acm.org Tue Dec 1 14:35:48 2009 From: nad at acm.org (Ned Deily) Date: Tue, 01 Dec 2009 11:35:48 -0800 Subject: PIL build error on Snow Leopard References: <785f1942-6aec-4a5a-934a-8db50648b1ae@e22g2000vbm.googlegroups.com> Message-ID: In article <785f1942-6aec-4a5a-934a-8db50648b1ae at e22g2000vbm.googlegroups.com>, Xiao wrote: > I haven't fully understood the nuances in the difference between > Apple's system Python and MacPython. But I have just installed Python > 2.6.4 from python.org. Now I'm trying to install a fresh downloaded > PIL 1.1.6 but couldn't. > python setup.py install gives: > lipo: can't open input file: /var/tmp//ccfwpQd6.out (No such file or > directory) > Everything worked fine on Apple's Python 2.6.1 Building PIL on OS X is annoyingly non-trivial and this subject is one that comes up frequently on the Mac python list (http://dir.gmane.org/gmane.comp.python.apple); you may want to search the archives or ask further questions there. Typically, the problem is that PIL depends on some libraries that do not ship with OS X and you need to provide them in the proper architectures to satisfy the python build you are using. The easiest approach is to use a complete solution from MacPorts since it includes PIL and python2.6 ports: $ sudo port py26-pil will pull in and build everything including a new python2.6. If you'd rather not do that, you can use MacPorts or Fink to build the necessary libraries. Another approach that should work (but I haven't tested on 10.6) is to install the UnixImageIO and FreeType frameworks from here: http://www.kyngchaos.com/software:frameworks -- Ned Deily, nad at acm.org From stef.mientki at gmail.com Tue Dec 1 14:39:17 2009 From: stef.mientki at gmail.com (Stef Mientki) Date: Tue, 01 Dec 2009 20:39:17 +0100 Subject: Bored. In-Reply-To: References: <16097008-372c-4522-889d-a78319c3575c@b2g2000yqi.googlegroups.com> Message-ID: <4B1570E5.6030804@gmail.com> Floris Bruynooghe wrote: > On Nov 30, 11:52 pm, Stef Mientki wrote: > >> Well I thought that after 2 years you would know every detail of a >> language ;-) >> > > Ouch, I must be especially stupid then! > > ;-) > > Sorry if I insulted you Floris! btw, I'm too still learning Python after I started 2 years ago. cheers, Stef > Floris > > From pavlovevidence at gmail.com Tue Dec 1 15:52:19 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Tue, 1 Dec 2009 12:52:19 -0800 (PST) Subject: Feature request: String-inferred names References: <7n6p0qF3krjueU1@mid.individual.net> <9a3e8bcd-245e-4a5d-bc9e-34b016303767@k17g2000yqh.googlegroups.com> Message-ID: On Dec 1, 10:21?am, Raymond Hettinger wrote: > [Gregory Ewing] > > > >>I just posted to my blog about a feature that I'd like to see added to > > >>Python. > > > >>http://alphaios.blogspot.com/2009/11/python-string-inferred-names-wor... > > > I don't think getattr and setattr are used anywhere near > > frequently enough to justify special syntax. > > Perhaps that would change if we had the proposed syntax. > I would expect that powerful and expressive idioms would emerge. I doubt it. Such expressive idioms haven't emerged in languages that do this (e.g., Javascript, Matlab) as far as I can tell. The objects end up being used as nothing more than a poor replacement for dictionaries. > > (A frequent question asked by newcomers from certain > > other kinds of languages is something like "How do I > > assign to a variable whose name is in another variable?" > > The answer is almost always "Don't do that, use a > > dictionary.") > > The proposed syntax works better with class namespaces > which automatically provide inheritance logic and > method binding. ?Dictionaries don't provide equivalent > support. The right approach to having "inheritance-like behavior" AND "typically don't know the name of the thing being accessed at compile time" in the same object--and I doubt that would be widely useful--is to add an option to dictionaries to support inheritance. Carl Banks From mckenzie.c at gmail.com Tue Dec 1 15:56:35 2009 From: mckenzie.c at gmail.com (cmckenzie) Date: Tue, 1 Dec 2009 12:56:35 -0800 (PST) Subject: Python reflection and loading/calling external module classes Message-ID: Hi! I've been putting off playing with Python for sometime now and I recently came up with a worthwhile project for my first hack. One technical challenge I'm trying to work out is dynamically loading modules from a directory (glob'd for a specific filename format) then importing them for calling later. Basically my modules follow this structure: class sample(): From phlip2005 at gmail.com Tue Dec 1 16:11:21 2009 From: phlip2005 at gmail.com (Phlip) Date: Tue, 01 Dec 2009 13:11:21 -0800 Subject: Question on Python as career In-Reply-To: <614b8dde-324b-4d54-8e73-7a96e4c0b1cf@a21g2000yqc.googlegroups.com> References: <614b8dde-324b-4d54-8e73-7a96e4c0b1cf@a21g2000yqc.googlegroups.com> Message-ID: <_DfRm.61945$rE5.35795@newsfe08.iad> joy99 wrote: > I have developed the following toolkits: > (i) A web based crawler; > (ii) A Bayesian classifier; > (iii) One NER engine; > (iv) One XML parser; > (v) One PoS Tagger; > (vi) One Parser based on CRF; > (vii) One MLE training system; > (viii) One Spell Checker; > (ix) One Transliteration System; > > I have developed them either in Python2.5 and Python2.6. > > After I complete my Post Doctoral which may be only 2-3 months away, > with this knowledge can I join IT? All your items are computer science. IT is about software engineering. That means _avoiding_ new research in preference for efficiently implementing business solutions. > Or Do I have to learn anything new? Test Driven Development. Active Record (ORM models) HTML & webby technologies platforms & deployment issues GNU, open source, and version controlling Behavior Driven Development > Are there any India based opportunities- as I checked Python job board > it is very less. Ideally, IT should get the job done using a soft language like Python, Ruby, or Lua. IT should not waste its time using a hard language like C++. That is for system programming - making the modules that IT reuses. > If I get anything after completing my Post Doc with present base of > knowledge what profiles I may expect? How about videogames? They always need hard algorithms & computer science. -- Phlip http://c2.com/cgi/wiki?ZeekLand From jabronson at gmail.com Tue Dec 1 16:19:22 2009 From: jabronson at gmail.com (Joshua Bronson) Date: Tue, 1 Dec 2009 13:19:22 -0800 (PST) Subject: python bijection References: <5a99def7-e182-4782-9054-f1035affa34d@x5g2000prf.googlegroups.com> <7n39ojF3jj6iuU1@mid.individual.net> <12c55890-118d-4655-b6c0-c908c9734a17@a32g2000yqm.googlegroups.com> <85100df7-a8b0-47e9-a854-ba8a8a2f3b98@r31g2000vbi.googlegroups.com> Message-ID: <159c4889-b885-42d4-b765-2b8347a36913@g1g2000vbr.googlegroups.com> On Dec 1, 2:11?pm, Raymond Hettinger wrote: > [Joshua Bronson] > > > Raymond, do you think there might be any future in including a built- > > in bidict data structure in Python? > > I don't think so. ?There are several forces working against it: > > * the recipe is new, so it hasn't had a chance to mature > ? or to gain a fan club. > > * there are many approaches to the solving the problem and > ? there is no reason to assume this one is the best. > > * it extends the language with arcane syntax tricks instead of > ? using the language as designed by Guido. ?That makes it harder > ? to learn and remember. > > * we've already got one (actually two). ?The two dictionary approach > ? uses plain python, requires no new learning, and is more flexible. > ? Also, sqlite3 provides another way to use multiple lookups to a > ? single record. ?The database approach is much more general > ? (extending to trijections, allowing multiple sort orders, > ? providing persistence, etc). all good points. > * the semantics of a bijection aren't obvious: > > ? ? ?b['x'] = 'ex' ? ? ?# first record: ?('x', 'ex') > ? ? ?b['y'] = 'why' ? ? # second record: ('y', 'why') > ? ? ?b[:'why'] = 'x' ? ?# do two records collapse into one? is there > an error? In my implementation the two records collapse into one, on the theory that if you say it you mean it, but you're right that the semantics aren't obvious, especially since in sql this would be an error. Thank you for pointing this out, it totally slipped my mind to document it! (Noted now.) If my bidict package ever has >1 user, and they prefer this to be an error, I'd totally change it. > * the proposed syntax doesn't address the issue covered in my previous > post. > ? Since bijections are symmetrical, they do not have an obvious > direction > ? (which is the primary key, the husband or the wife?). ?The syntax > needs to > ? allow user names to make it clear which is being accessed: > > ? ? ?marriages.h2w['john'] = 'amy' > ? ? ?marriages.w2h['amy'] = 'john' > > ? Contrast this with: > > ? ? ?marriages['jordan'] = 'taylor' ? ?# are you sure you got the > order correct? > ? ? ?marriages[:'taylor'] = 'jordan' ? # this is easy to get backwards The "namedbidict" class factory I wrote on your recommendation allows for the former. But it's still up to the user to choose names which indicate the direction of the mapping, whether she uses namedbidict or not: marriages.husbands['john'] = 'amy' # namedbidict, direction unclear h2w['john'] = 'amy' # regular bidict, but not unclear b/c name is 'h2w' (you can use >>> marriages.inv is marriages.husbands False to tell that husbands is the forward mapping, but that sucks -- better to have called it h2w or some such in the first place.) Thanks for the thoughtful reply. Josh From manuel.graune at koeln.de Tue Dec 1 16:36:23 2009 From: manuel.graune at koeln.de (Manuel Graune) Date: Tue, 01 Dec 2009 22:36:23 +0100 Subject: Questions about list-creation References: Message-ID: Thanks to all of you. You have been most helpful. Regards, Manuel Graune -- A hundred men did the rational thing. The sum of those rational choices was called panic. Neal Stephenson -- System of the world http://www.graune.org/GnuPG_pubkey.asc Key fingerprint = 1E44 9CBD DEE4 9E07 5E0A 5828 5476 7E92 2DB4 3C99 From tjreedy at udel.edu Tue Dec 1 16:42:44 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 01 Dec 2009 16:42:44 -0500 Subject: Inspect module - getargspec raise TypeError for built-in functions In-Reply-To: References: <97FB089C6E1F404CB0132AC3BB3E5C2701947E15@exchange.qualisystems.local> Message-ID: Christian Heimes wrote: > Nadav Chernin wrote: >> When I use getargspec(func) for user-defined function, all is working >> OK, but using it for built-in functions raise TypeError: I added an issue to document this better http://bugs.python.org/issue7422 > That's just fine and to be expected. It's not possible to inspect a C > function. Only functions implemented in Python have the necessary metadata. So should this request to also inspect C functions be closed? http://bugs.python.org/issue1748064 Terry Jan Reedy From tjreedy at udel.edu Tue Dec 1 16:50:33 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 01 Dec 2009 16:50:33 -0500 Subject: problem with lambda / closures In-Reply-To: References: Message-ID: Jussi Piitulainen wrote: > Terry Reedy writes: > >> definitions. Lambda expressions create functions just like def >> statements and are not closures and do not create closure unless >> nested within another function definition. Thinking otherwise is > > Seems quite closed in the top level environment to me: > > Python 2.3.4 (#1, Jul 16 2009, 07:03:37) > >>> k = 'outer' > >>> f = lambda : k > >>> def test(): > ... k = 'inner' > ... return f() > ... > >>> test() > 'outer' > >>> k = 'thing' > >>> test() > 'thing' I used closure in the same sense as the OP, who would have expected the last result to be 'outer', not 'thing'. Runtime lookup in the lexically defined global namespace is normal function behavior, not special closure behavior as most people mean is. Terry Jan Reedy From tjreedy at udel.edu Tue Dec 1 16:55:50 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 01 Dec 2009 16:55:50 -0500 Subject: Moving from Python 2 to Python 3: A 4 page "cheat sheet" In-Reply-To: <291d64cb-cc5c-4109-822c-84d58ed7b18b@k17g2000yqh.googlegroups.com> References: <291d64cb-cc5c-4109-822c-84d58ed7b18b@k17g2000yqh.googlegroups.com> Message-ID: Mark Summerfield wrote: > I've produced a 4 page document that provides a very concise summary > of Python 2<->3 differences plus the most commonly used new Python 3 > features. It is aimed at existing Python 2 programmers who want to > start writing Python 3 programs and want to use Python 3 idioms rather > than those from Python 2 where the idioms differ. > > It uses Python 3.1 syntax since that looks like being the standard for > a few years in view of the language moratorium. > > The document is U.S. Letter size but will also print fine on A4 > printers. > > It is available as a free PDF download (no registration or anything) > from InformIT's website. Here's the direct link: > http://ptgmedia.pearsoncmg.com/imprint_downloads/informit/promotions/python/python2python3.pdf > > And of course, if you want more on Python 3, there's always the > documentation---or my book:-) > "Programming in Python 3 (Second Edition)" ISBN-10: 0321680561. What might be even *more* helpful, with contributions from others perhaps, would be an indication of which changes are handled automatically by 2to3.py and which must be done by hand. tjr From dahl.joachim at gmail.com Tue Dec 1 16:56:34 2009 From: dahl.joachim at gmail.com (Joachim Dahl) Date: Tue, 1 Dec 2009 13:56:34 -0800 (PST) Subject: PyArg_ParseTupleAndKeywords in Python3.1 References: <0a0b822c-8d57-4816-8563-5fd8ff39f7f1@p8g2000yqb.googlegroups.com> <83f08b89-6b61-4005-9fbd-c9a01da36654@d9g2000prh.googlegroups.com> Message-ID: <408e4acd-3182-4d08-bcb4-d4ff1632d9c2@l13g2000yqb.googlegroups.com> thanks - the patch fixed my problem. Joachim On Dec 1, 5:51?am, casevh wrote: > On Nov 30, 2:18?pm, Joachim Dahl wrote: > > > > > > > I think that "C" encoding is what I need, however I run into an odd > > problem. > > If I use the following C code > > > static PyObject* foo(PyObject *self, PyObject *args, PyObject *kwrds) > > { > > ? char a, b; > > ? char *kwlist[] = {"a", "b", NULL}; > > ? if (!PyArg_ParseTupleAndKeywords(args, kwrds, "|CC", kwlist, &a, > > &b)) > > ? ? return NULL; > > ? ... > > > then the following works: > > > >>> foo('a') > > >>> foo('a','b') > > >>> foo(a='a',b='b') > > > but the following fails:>>> foo(b='b') > > > RuntimeError: impossible: 'CC' > > > Is this error-message expected? > > Nope. It appears to be a bug in Python. The format code 'C' is missing > in the switch statement in skipitem() in getargs.c. I added "case > 'C': /* int */" after "case 'c': /* char */" and then example worked > for me. > > I'll open a bug report. > > casevh > > > > > > > On Nov 30, 10:19?pm, casevh wrote: > > > > On Nov 30, 1:04?pm, Joachim Dahl wrote: > > > > > Obviously the name of the C function and the char variable cannot both > > > > be foo, > > > > so the C code should be: > > > > > static PyObject* foo(PyObject *self, PyObject *args, PyObject *kwrds) > > > > { > > > > ? char foochar; > > > > ? char *kwlist[] = {"foochar", NULL}; > > > > ? if (!PyArg_ParseTupleAndKeywords(args, kwrds, "c", kwlist, > > > > &foochar)) > > > > ? ? return NULL; > > > > ? ... > > > > > The question remains the same: why can't I pass a single character > > > > argument to this function under Python3.1? > > > > > Thanks. > > > > Joachim > > > > > On Nov 30, 9:52?pm, Joachim Dahl wrote: > > > > > > I am updating an extension module from Python2.6 to Python3. > > > > > > I used to pass character codes to the extension module, for example, I > > > > > would write: > > > > > > >>> foo('X') > > > > > > with the corresponding C extension routine defined as follows: > > > > > static PyObject* foo(PyObject *self, PyObject *args, PyObject *kwrds) > > > > > { > > > > > ? char foo; > > > > > ? char *kwlist[] = {"foo", NULL}; > > > > > ? if (!PyArg_ParseTupleAndKeywords(args, kwrds, "c", kwlist, &foo)) > > > > > ? ? return NULL; > > > > > ? ... > > > > > > In Python3.0 this also works, but in Python3.1 I get the following > > > > > error: > > > > > TypeError: argument 1 must be a byte string of length 1, not str > > > > > > and I seem to be supposed to write>>> foo(b'X') > > > > > > instead. From the Python C API, I have not been able to explain this > > > > > new behavior. > > > > > What is the correct way to pass a single character argument to > > > > > Python3.1 > > > > > extension modules?- Hide quoted text - > > > > > - Show quoted text - > > > > Python 3.1 uses "c" (lowercase c) to parse a single character from a > > > byte-string and uses "C" (uppercase c) to parse a single character > > > from a Unicode string. I don't think there is an easy way to accept a > > > character from both. > > > > HTH, > > > > casevh From manuel.graune at koeln.de Tue Dec 1 17:02:43 2009 From: manuel.graune at koeln.de (Manuel Graune) Date: Tue, 01 Dec 2009 23:02:43 +0100 Subject: Tracing variable scope (local vs. global) Message-ID: Hello, consider the following piece of code: a=1 b=2 def foo(c): b=3 return a + b + c In this case, when calling "foo", "a" will take the global value, "b" will take the local value and "c" will take the value assigned when calling the function. Since I consider this behaviour a possible source of bugs due to personal sloppiness (e. g. forgetting to put "a=4" inside the function-body): Is there any way to automatically check that all variables in a function are either local or passed in as arguments? Regards, Manuel Graune -- A hundred men did the rational thing. The sum of those rational choices was called panic. Neal Stephenson -- System of the world http://www.graune.org/GnuPG_pubkey.asc Key fingerprint = 1E44 9CBD DEE4 9E07 5E0A 5828 5476 7E92 2DB4 3C99 From tjreedy at udel.edu Tue Dec 1 17:06:18 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 01 Dec 2009 17:06:18 -0500 Subject: Can't print Chinese to HTTP In-Reply-To: References: <4b13c039$0$7478$9b622d9e@news.freenet.de> <8810fcc1-3e2d-42ce-839c-d03774e02ea1@l13g2000yqb.googlegroups.com> <4b153863@dnews.tpgi.com.au> Message-ID: Gnarlodious wrote: > On Dec 1, 8:36 am, Lie Ryan wrote: > >> #!/usr/bin/python >> import sys >> print = lambda s: sys.stdout.buffer.write(s.encode('utf-8')) This is almost exactly the same as def print(s): return sys.stdout.buffer.write(s.encode('utf-8')) except that the latter gives better error tracebacks. >> print("Content-type:text/plain;charset=utf-8\n\n") >> print('?\n') > > HA! IT WORKS! Thank you thank you thank you. I don't understand the > lambda functionality but will figure it out. Nothing to do with lambda, really. See above. tjr From davea at ieee.org Tue Dec 1 17:11:41 2009 From: davea at ieee.org (Dave Angel) Date: Tue, 01 Dec 2009 17:11:41 -0500 Subject: Python reflection and loading/calling external module classes In-Reply-To: References: Message-ID: <4B15949D.2020705@ieee.org> cmckenzie wrote: > Hi! I've been putting off playing with Python for sometime now and I > recently came up with a worthwhile project for my first hack. One > technical challenge I'm trying to work out is dynamically loading > modules from a directory (glob'd for a specific filename format) then > importing them for calling later. > > Basically my modules follow this structure: > > class sample(): > > Your message was cut-off before you finished, but the answer is probably the built-in function __import_(). DaveA From marko.loparic at gmail.com Tue Dec 1 17:16:59 2009 From: marko.loparic at gmail.com (markolopa) Date: Tue, 1 Dec 2009 14:16:59 -0800 (PST) Subject: Creating a local variable scope. References: <4b12f20c@dnews.tpgi.com.au> <97a101a2-1362-46f4-9308-b72e5c4ac392@s20g2000yqd.googlegroups.com> Message-ID: <45c694fc-b2fa-4e1e-9421-6476fdba8c7a@m26g2000yqb.googlegroups.com> Hi Dave, Since you feel like discussing my weird idea of Python reform :-) lets go... On 30 Nov, 11:29, Dave Angel wrote: > Somehow you seem to think there's some syntax for "creating" avariable. ?In fact, what's happening is you're binding/rebinding a name > to an object. ?And if you forbid doing this inside the loop, for names > that exist outside the loop, then most of the useful work the loop does > becomes impossible. ?Remember, in Python, there's no declaration of avariable(except the global statement, which does it sort-of). You are right, I have not used precise terms. Let's use examples then. >?So you'd > be disallowing the following: > > ? ? counter = 5 > ? ? for item in itemlist: > ? ? ? ? ? ?if item > 19: > ? ? ? ? ? ? ? ? counter = counter + 5 In this example, I would allow the expected behaviour. Since "counter" was bound in the outer loop, the new binding got in the inner loop would persist after the end of the "if" and the "for" block. Other examples: if True: a = 5 print a would produce an error while a = 3 if True: a = 5 print a would print 5 (and not 3). But now I realise that one of my bugs wouldn't be solved, so I believe you have managed to convince me that my idea does not make much sense...:-) > The only way I can think you possibly want this is if you're just > referring to "loop variables", such as "item" in the above example. ?The > problem is that on many loops, for example a "while" loop, there's no > such thing. This would already be great. I believe that most bugs I've had related to this issue are due to accidental reuse of loop variables. But treating the loop variables as a special case is perhaps not very elegant. Greetings, Marko From marko.loparic at gmail.com Tue Dec 1 17:32:25 2009 From: marko.loparic at gmail.com (markolopa) Date: Tue, 1 Dec 2009 14:32:25 -0800 (PST) Subject: Creating a local variable scope. References: <4b12f20c@dnews.tpgi.com.au> <97a101a2-1362-46f4-9308-b72e5c4ac392@s20g2000yqd.googlegroups.com> Message-ID: <9f5d0933-4aae-45a9-8111-84a399c493c9@b15g2000yqd.googlegroups.com> Hi Roger, > > That is what I do regularly...8-> > > Well really dude, you need to stop doing that. It's not a language > problem, it's a memory problem (human not RAM!). You guessed quite correctly!...:-) I can't recognise my code sometimes after a single week. That's why I spend a lot of time cleaning it to be easy to get back. Fortunately it seems to be recognised as a good practice... > You need to be aware of > what you're putting into your namespace. This is one of the reasons > people try to avoid using global variables, if you forget you've used a variable name and use it again somewhere you get an undefined state and > hours of debugging / data loss / subtle corruptions you won't spot until > ?the backups have all been cycled etc. Sure, zero global variables in my programs. > I'm surprised you have a recurring problem with this really. My memory > is terrible and I reuse variable names all over the place without any > trouble. Maybe try keeping the length of your functions down so that > they fit on a single screen and create and use a strong naming > convention i.e. > > Long, descriptive variable names all_in_lower_case > Function names all in CamelCase > Global names are in ALL CAPS yes, pep8 I guess. > Loop variable names all prefixed with 'each_' Interesting. A radical idea (and not very elegant for my taste I would say) but it could certainly make me avoid such bugs... Cheers! Marko From lie.1296 at gmail.com Tue Dec 1 17:34:41 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Wed, 02 Dec 2009 09:34:41 +1100 Subject: Tracing variable scope (local vs. global) In-Reply-To: References: Message-ID: <4b159a6d$1@dnews.tpgi.com.au> On 12/2/2009 9:02 AM, Manuel Graune wrote: > > Hello, > > consider the following piece of code: > > a=1 > b=2 > > def foo(c): > b=3 > return a + b + c > > In this case, when calling "foo", "a" will take the global value, > "b" will take the local value and "c" will take the value assigned > when calling the function. > > Since I consider this behaviour a possible source of bugs due to > personal sloppiness (e. g. forgetting to put "a=4" inside the > function-body): > > Is there any way to automatically check that all variables in a > function are either local or passed in as arguments? If you really mean what you're saying, you won't be able to use builtin functions. Anyway... the answer to your problem is a strong naming convention and to not store variables in the global namespace; put everything in a class and use a main() function so your initialization code doesn't clutter up the global namespace. As such, there shouldn't be a lowercased name in the global namespace (class use CamelCase and constants UPPERCASED); and all lowercased names are local (or builtins, use pylint to check for the case of shadowing builtins). From deets at nospam.web.de Tue Dec 1 17:36:39 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 01 Dec 2009 23:36:39 +0100 Subject: Tracing variable scope (local vs. global) In-Reply-To: References: Message-ID: <7nlk3nF3mphcpU1@mid.uni-berlin.de> Manuel Graune schrieb: > Hello, > > consider the following piece of code: > > a=1 > b=2 > > def foo(c): > b=3 > return a + b + c > > In this case, when calling "foo", "a" will take the global value, > "b" will take the local value and "c" will take the value assigned > when calling the function. > > Since I consider this behaviour a possible source of bugs due to > personal sloppiness (e. g. forgetting to put "a=4" inside the > function-body): > > Is there any way to automatically check that all variables in a > function are either local or passed in as arguments? No. And as long as you don't have the habit of using global variables to a non-reasonable extent, and follow some simple conventions such as spelling them in all uppercase and with more meaningful names such as the ones above - it's not an actual problem. Diez From ben+python at benfinney.id.au Tue Dec 1 17:53:20 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 02 Dec 2009 09:53:20 +1100 Subject: Report spammers to their service provider for great justice (was: can you say it please) References: <13ad18f4-d302-466a-ba62-3d3eecea7176@k19g2000yqc.googlegroups.com> <009eabd0$0$26893$c3e8da3@news.astraweb.com> Message-ID: <871vjenw67.fsf_-_@benfinney.id.au> Steven D'Aprano writes: > On Tue, 01 Dec 2009 00:31:51 -0800, Processor-Dev1l wrote: > > > does it mean ... > > Please don't respond to religious nutters or spammers, you only > encourage them. Instead, report them to the provider they used to send their message, as an abuse of service. Look in the message header; in the overwhelming majority of cases they will have used Google, so you'll find a ?Complaints-To? field with an email address as its value. Forward the entire message to that address and explain the message is an abuse of service. Yes, this actually does reach real people who can do something about it (though you won't get a response); it's the reason we don't see *even more* of this crap. -- \ ?I was sleeping the other night, alone, thanks to the | `\ exterminator.? ?Emo Philips | _o__) | Ben Finney From phlip2005 at gmail.com Tue Dec 1 17:55:27 2009 From: phlip2005 at gmail.com (Phlip) Date: Tue, 1 Dec 2009 14:55:27 -0800 (PST) Subject: combinatorics via __future__ generators References: Message-ID: <3b45b550-11dc-41a6-8c49-02f6cfaad6d5@j24g2000yqa.googlegroups.com> Awesome thanks - but: > from itertools import imap,product Do we have a version for Python2.5? I have to support an older server here; can't install a newer python on it... From allen.fowler at yahoo.com Tue Dec 1 17:57:27 2009 From: allen.fowler at yahoo.com (allen.fowler) Date: Tue, 1 Dec 2009 14:57:27 -0800 (PST) Subject: How to set object parameters nicely? Message-ID: <83ced7d2-8d75-4e41-a60b-7c0c73515129@m38g2000yqd.googlegroups.com> Hello, I've got a bunch of code that looks something like: class MyOb(object): def __init__(self, p1=None, p2=None, p3=None, ...): self.p1 = p1 self.p2 = p2 self.p3 = p3 self.pN = ... ob1 = MyOb(p1="Tom", p3="New York") ob2 = MyOb(p1="Joe", p2="joe at host", p3="New Jersey") ... and so on. This is fine for only a few parameters, but it's very ugly and a lot of duplicate typing once I've got 10+ parameters and 5 kinds of objects. Is there a better way to do this? Thanks, :) From oviney at gmail.com Tue Dec 1 18:09:26 2009 From: oviney at gmail.com (Ouray Viney) Date: Tue, 1 Dec 2009 15:09:26 -0800 (PST) Subject: Reading a file that is changing and getting the new lines Message-ID: Hi: Problem: ========= I want to read a ASCII text file that can have data appended to it. I have hacked some code together that handles the basics, but it falls short. My code doesn't read in the new lines that could have been added to the end of the file. Not python's fault, more that I don't know how to do it in python. Example scenario: As the python script is running a user/application adds new entries to the end of the test case file, example, adds the following to the file. test4 test5 test6 The python code below, won't pick these changes up. Analysis: ======== I understand why my code doesn't handle the addition of new data. This is simply because the os.open reads all the lines in the beginning and since the data is added after that, the for loop doesn't iterate through it since it doesn't know about it. Please note, my code is not pretty and isn't at all advanced. Code: ====== import os,string,sys,time # define locals tcListFile="testcase_list.txt" fh=open(tcListFile,"r") tcList=fh.readlines() fh.close() for tc in tcList: print tc.strip() print "sleeping for 2 seconds" time.sleep(2) # close the file handle fh.close() text file: ====== test1 test2 test3 Question: ========= What is the best way to handle this type of scenario using python? From deets at nospam.web.de Tue Dec 1 18:13:35 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 02 Dec 2009 00:13:35 +0100 Subject: How to set object parameters nicely? In-Reply-To: <83ced7d2-8d75-4e41-a60b-7c0c73515129@m38g2000yqd.googlegroups.com> References: <83ced7d2-8d75-4e41-a60b-7c0c73515129@m38g2000yqd.googlegroups.com> Message-ID: <7nlm8vF3mic4kU1@mid.uni-berlin.de> allen.fowler schrieb: > Hello, > > I've got a bunch of code that looks something like: > > class MyOb(object): > def __init__(self, p1=None, p2=None, p3=None, ...): > self.p1 = p1 > self.p2 = p2 > self.p3 = p3 > self.pN = ... > > > ob1 = MyOb(p1="Tom", p3="New York") > ob2 = MyOb(p1="Joe", p2="joe at host", p3="New Jersey") > > ... and so on. > > This is fine for only a few parameters, but it's very ugly and a lot > of duplicate typing once I've got 10+ parameters and 5 kinds of > objects. > > Is there a better way to do this? There are some tricks. Like this def __init__(self, p1=None, ...): d = locals() del d["self"] self.__dict__.update(d) However, it looks like a code-smell for me if you have 10+ paramters. Diez From python at mrabarnett.plus.com Tue Dec 1 18:13:55 2009 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 01 Dec 2009 23:13:55 +0000 Subject: How to set object parameters nicely? In-Reply-To: <83ced7d2-8d75-4e41-a60b-7c0c73515129@m38g2000yqd.googlegroups.com> References: <83ced7d2-8d75-4e41-a60b-7c0c73515129@m38g2000yqd.googlegroups.com> Message-ID: <4B15A333.4000009@mrabarnett.plus.com> allen.fowler wrote: > Hello, > > I've got a bunch of code that looks something like: > > class MyOb(object): > def __init__(self, p1=None, p2=None, p3=None, ...): > self.p1 = p1 > self.p2 = p2 > self.p3 = p3 > self.pN = ... > > > ob1 = MyOb(p1="Tom", p3="New York") > ob2 = MyOb(p1="Joe", p2="joe at host", p3="New Jersey") > > ... and so on. > > This is fine for only a few parameters, but it's very ugly and a lot > of duplicate typing once I've got 10+ parameters and 5 kinds of > objects. > > Is there a better way to do this? > class MyOb(object): def __init__(self, **kwargs): self.__dict__.update(kwargs) ob1 = MyOb(p1="Tom", p3="New York") ob2 = MyOb(p1="Joe", p2="joe at host", p3="New Jersey") From allen.fowler at yahoo.com Tue Dec 1 18:26:32 2009 From: allen.fowler at yahoo.com (allen.fowler) Date: Tue, 1 Dec 2009 15:26:32 -0800 (PST) Subject: How to set object parameters nicely? References: <83ced7d2-8d75-4e41-a60b-7c0c73515129@m38g2000yqd.googlegroups.com> Message-ID: > > Is there a better way to do this? > > class MyOb(object): > ? ? ?def __init__(self, **kwargs): > ? ? ? ? ?self.__dict__.update(kwargs) > > ob1 = MyOb(p1="Tom", p3="New York") > ob2 = MyOb(p1="Joe", p2="joe at host", p3="New Jersey") I've tried this, but have found two issues: 1) I can't set default values. 2) I can't set required values. In both of the above cases, if the object is created without the "exact" dict() I expect, all the assumption my methods make about what is available in "self" fall apart. Perhaps, as Diez mentioned, my approach is wrong. What would be the right thing to do in this situation? -- AF From deets at nospam.web.de Tue Dec 1 18:36:04 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 02 Dec 2009 00:36:04 +0100 Subject: How to set object parameters nicely? In-Reply-To: References: <83ced7d2-8d75-4e41-a60b-7c0c73515129@m38g2000yqd.googlegroups.com> Message-ID: <7nlnj4F3mq0bdU1@mid.uni-berlin.de> allen.fowler schrieb: >>> Is there a better way to do this? >> class MyOb(object): >> def __init__(self, **kwargs): >> self.__dict__.update(kwargs) >> >> ob1 = MyOb(p1="Tom", p3="New York") >> ob2 = MyOb(p1="Joe", p2="joe at host", p3="New Jersey") > > I've tried this, but have found two issues: > > 1) I can't set default values. > 2) I can't set required values. > > In both of the above cases, if the object is created without the > "exact" dict() I expect, all the assumption my methods make about what > is available in "self" fall apart. > > Perhaps, as Diez mentioned, my approach is wrong. What would be the > right thing to do in this situation? There is no general answer to this. It depends on your actual problem. Diez From john at castleamber.com Tue Dec 1 18:52:05 2009 From: john at castleamber.com (John Bokma) Date: Tue, 01 Dec 2009 17:52:05 -0600 Subject: Moving from Python 2 to Python 3: A 4 page "cheat sheet" References: <291d64cb-cc5c-4109-822c-84d58ed7b18b@k17g2000yqh.googlegroups.com> Message-ID: <87ljhm8d7e.fsf@castleamber.com> Mark Summerfield writes: > It is available as a free PDF download (no registration or anything) > from InformIT's website. Here's the direct link: > http://ptgmedia.pearsoncmg.com/imprint_downloads/informit/promotions/python/python2python3.pdf Thanks! > And of course, if you want more on Python 3, there's always the > documentation---or my book:-) > "Programming in Python 3 (Second Edition)" ISBN-10: 0321680561. Meh, second edition already? Haven't read the entire first edition yet. Which is IMO a good book (I also gave it to my brother as a present). Only negative point (to me) so far is that in the beginning (p8-9) the book mentions placing Python programs in C:\py3eg which gives me the unpleasant feeling that someone is coding on Windows XP with Administrator rights... Anyway, will add the 2nd edition to my wish list and donate the current one to the library in Xalapa (USBI) if they want it :-) John From kirby.urner at gmail.com Tue Dec 1 19:16:20 2009 From: kirby.urner at gmail.com (kirby urner) Date: Tue, 1 Dec 2009 16:16:20 -0800 Subject: [Edu-sig] teaching python using turtle module In-Reply-To: References: <4B13F47E.3080706@aon.at> <4B1463F8.2000902@aon.at> Message-ID: Gregor FYI: You'll find me linking to one Gregor in Vienna in this blog post, just beneath an archival photo of work by Alexander Graham Bell.[1] http://worldgame.blogspot.com/2009/12/meeting-with-sam.html ... providing more context and spin for this rhombic triancontahedron thread, all that much strong thanks to you. Kirby [1] Eber, Dorothy Harley. Genius At Work. about AGB is one of my fave syllabus entries, obscure and fun. On Mon, Nov 30, 2009 at 4:52 PM, kirby urner wrote: > On Mon, Nov 30, 2009 at 4:31 PM, Gregor Lingl wrote: > > << fascinating code >> > >> >> Hoping, you will find this a bit interesting, >> best regards >> >> Gregor >> > > Really enlightening, both mathematically and from a coding point of > view. ?I hadn't used turtle.py enough yet to know about the built-in > "context turtle" if you want to just say "forward" and forgo > specifying a target. ?That's a nice Logo-ish touch. > > Your take on the T is most excellent. > > With your permission, I'd be happy to add both versions with > attribution to my online version of tmod.py for the benefit of future > students, and/or I could simply link to this post in the edu-sig > archives (why not both?). > > Kirby > > > -- >>>> from mars import math > http://www.wikieducator.org/Digital_Math > -- >>> from mars import math http://www.wikieducator.org/Digital_Math From atlas245 at gmail.com Tue Dec 1 19:36:42 2009 From: atlas245 at gmail.com (bla bla) Date: Tue, 1 Dec 2009 16:36:42 -0800 (PST) Subject: DOM related question and problem References: <26412730.post@talk.nabble.com> <4b064b7c$0$7628$9b4e6d93@newsspool1.arcor-online.net> Message-ID: <30c5d6ef-2a0b-4487-934c-944f4e41143b@s31g2000yqs.googlegroups.com> Nice post on extracting data, simple and too the point :), I use python for simple html extracting data, but for larger projects like the web, files, or documents i tried extract data which worked great, they build quick custom screen scrapers, extracting data, and data parsing programs From juneng603 at gmail.com Tue Dec 1 19:54:47 2009 From: juneng603 at gmail.com (junyoung) Date: Tue, 1 Dec 2009 16:54:47 -0800 (PST) Subject: how to debug extended module? References: <7nk54jF3m6bppU1@mid.uni-berlin.de> Message-ID: <88d05d38-1879-4cdf-92b5-2edb6192b10e@g26g2000yqe.googlegroups.com> On 12?1?, ??6?14?, "Diez B. Roggisch" wrote: > junyoung schrieb: > > > Hi, I am a newbie who want to implement a extend module to use native > > python language with my own shared library. > > If it's a C shared library, don't bother extending it. Use ctypes to > wrap it. Much easier, and no need for a compiler. > > > > > to test wrapper library(extend module, name is 'test.so'), I created > > some test-cases. > > > There are some errors what I couldn't figure our reasons. > > > ex) > > SystemError: error return without exception set > > .... > > ... > > This indicates that you violated the exception protocol. > > http://docs.python.org/c-api/exceptions.html > > > so, I ran the ddd with python and then I set test.py as a argument of > > it. > > > ex) > > ddd python > > > in ddd > > run with arguments : test.py > > > but in this situation, I couldn't step in my own shared library > > (compiled as the debug mode). > > > Is there any clear way to debug my extend module(that it, debug shared > > library)?? > > I do it like this: > > # gdb python > gdb $ set args test.py > gdb $ run > > You can only debug a binary program (test.py isn't one, python is). But > trough the args, you get yours script running. > > It *might* help to have a python debug build, I personally never needed > that. > > Diez here is my results. anyway, check this out. (gdb) set args connect.py set args connect.py (gdb) run run Starting program: /usr/bin/python connect.py (no debugging symbols found) (no debugging symbols found) (no debugging symbols found) [Thread debugging using libthread_db enabled] (no debugging symbols found) (no debugging symbols found) (no debugging symbols found) (no debugging symbols found) [New Thread 0x7f619747e6e0 (LWP 23683)] (no debugging symbols found) (no debugging symbols found) (no debugging symbols found) (no debugging symbols found) [New Thread 0x415a9950 (LWP 23686)] [Thread 0x415a9950 (LWP 23686) exited] [New Thread 0x415a9950 (LWP 23687)] [Thread 0x415a9950 (LWP 23687) exited] Traceback (most recent call last): File "connect.py", line 25, in main() File "connect.py", line 18, in main connection_test() File "connect.py", line 15, in connection_test cnxn.close() SystemError: error return without exception set Program exited with code 01. (gdb) as you see, I can't load symbol table information from gdb. now python is defaulted installed as release. my os is ubuntu the python is installed in /usr/bin the python version is 2.5.1 do i need to re-install python as debug mode? From deets at nospam.web.de Tue Dec 1 19:55:30 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 02 Dec 2009 01:55:30 +0100 Subject: DOM related question and problem In-Reply-To: <30c5d6ef-2a0b-4487-934c-944f4e41143b@s31g2000yqs.googlegroups.com> References: <26412730.post@talk.nabble.com> <4b064b7c$0$7628$9b4e6d93@newsspool1.arcor-online.net> <30c5d6ef-2a0b-4487-934c-944f4e41143b@s31g2000yqs.googlegroups.com> Message-ID: <7nls83F3lnd6iU1@mid.uni-berlin.de> bla bla schrieb: > Nice post on extracting data, simple and too the point :), I use > python for simple html extracting data, but for larger projects like > the web, files, or documents i tried extract data which worked great, they > build quick custom screen scrapers, extracting data, and data parsing > programs You don't happen to be affiliated with that commercial venture? Which seems to be shady, to say the least. No real address, dns registered by a rather shady provider... better steer clear from this, and use lxml. Diez From aahz at pythoncraft.com Tue Dec 1 20:17:12 2009 From: aahz at pythoncraft.com (Aahz) Date: 1 Dec 2009 17:17:12 -0800 Subject: python bijection References: <85100df7-a8b0-47e9-a854-ba8a8a2f3b98@r31g2000vbi.googlegroups.com> Message-ID: In article <85100df7-a8b0-47e9-a854-ba8a8a2f3b98 at r31g2000vbi.googlegroups.com>, Joshua Bronson wrote: > >I noticed the phonebook example in your ActiveState recipe and thought >you might consider changing it to something like husbands to wives, >since the names-to-phone-numbers relation is many-to-many. What makes you think husbands to wives is one-to-one? ;-) (Even assuming monogamy, you have husbands-to-husbands and wives-to-wives.) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ The best way to get information on Usenet is not to ask a question, but to post the wrong information. From rzantow at gmail.com Tue Dec 1 20:22:46 2009 From: rzantow at gmail.com (rzed) Date: Wed, 02 Dec 2009 01:22:46 +0000 Subject: Raw strings as input from File? References: Message-ID: utabintarbo wrote in news:adc6c455-5616-471a-8b39-d7fdad2179e4 at m33g2000vbi.googlegroups.c om: > I have a log file with full Windows paths on a line. eg: > K:\A\B\C\10xx\somerandomfilename.ext->/a1/b1/c1/10xx > \somerandomfilename.ext ; t9999xx; 11/23/2009 15:00:16 ; > 1259006416 > > As I try to pull in the line and process it, python changes the > "\10" to a "\x08". This is before I can do anything with it. Is > there a way to specify that incoming lines (say, when using > .readlines() ) should be treated as raw strings? > > TIA Despite all the ragging you're getting, it is a pretty flakey thing that Python does in this context: (from a python shell) >>> x = '\1' >>> x '\x01' >>> x = '\10' >>> x '\x08' If you are pasting your string as a literal, then maybe it does the same. It still seems weird to me. I can accept that '\1' means x01, but \10 seems to be expanded to \010 and then translated from octal to get to x08. That's just strange. I'm sure it's documented somewhere, but it's not easy to search for. Oh, and this: >>> '\7' '\x07' >>> '\70' '8' ... is realy odd. -- rzed From vincent at vincentdavis.net Tue Dec 1 20:31:44 2009 From: vincent at vincentdavis.net (Vincent Davis) Date: Tue, 1 Dec 2009 18:31:44 -0700 Subject: Delaunay triangulation Message-ID: <77e831100912011731n53269c60r2a582d77a43a4eda@mail.gmail.com> Anyone know of a python implementation of Delaunay triangulation? *Vincent Davis 720-301-3003 * vincent at vincentdavis.net my blog | LinkedIn -------------- next part -------------- An HTML attachment was scrubbed... URL: From half.italian at gmail.com Tue Dec 1 20:31:57 2009 From: half.italian at gmail.com (Sean DiZazzo) Date: Tue, 1 Dec 2009 17:31:57 -0800 (PST) Subject: Reading a file that is changing and getting the new lines References: Message-ID: On Dec 1, 3:09?pm, Ouray Viney wrote: > Problem: > ========= > I want to read a ASCII text file that can have data appended to it. > > Example scenario: ?As the python script is running a user/application > adds new entries to the end of the test case file, example, adds the > following to the file. > > Question: > ========= > What is the best way to handle this type of scenario using python? There was a thread regarding 'imitating "tail -f"' recently that you might find useful. The best approach IMO is this one: http://www.dabeaz.com/generators/follow.py ~Sean From patrickstinson.lists at gmail.com Tue Dec 1 20:47:35 2009 From: patrickstinson.lists at gmail.com (Patrick Stinson) Date: Tue, 1 Dec 2009 18:47:35 -0700 Subject: xmlrpc idea for getting around the GIL In-Reply-To: References: <6214d7a20911221338l30296032y32d2d1215de57b6d@mail.gmail.com> <83303a84-a8ca-486a-8173-ef0892779f39@x16g2000vbk.googlegroups.com> <4b0b07a1$0$22159$9b622d9e@news.freenet.de> Message-ID: <6214d7a20912011747m262991a3vcfc1b7d055950a2e@mail.gmail.com> yes, using an rpc mechanism would insert a "blocking" call into a thread in which I am "not allowed to make a blocking call," but actual turn around times would be far better than forcing all threads to wait on the Gil. As it stands, blocking on a single thread lock *almost* works, and while we can claim this or that theoretical deficiency, the proof is in the pudding and the pudding almost works. In fact, it does work and has made us money, we just need one more once of performance at low latencies and I can put this way. Most machines that are running an audio sequencing host app are not running other apps, and we can generally assume that the host app is the only one using up the majority of resources on the local machine. So, as it turns out, we can assume quite a predictable and stable operating environment for our code. We don't need extension modules, and all we need to do is run some fairly basic scripts that make callbacks and use some sip-wrapped types. Py_CallObject is our only entry point into python execution from within the critical thread. SIDE NOTE: There are a lot of use cases that the educated python community is not familiar with that are really spectacularly interesting, and I think some of the myths surrounding python are incorrect. - Python is not suitable for real-time work. Not true. We have been running python callback code using PyObject_CallObject from within our audio thread for some time without a problem, and it's *extremely* fast. - Especially in a production environment. Not true. We sell the industry leading sampler engine, and it has been paying my salary for three years. It's high performance - every cycle counts. Our sampled instruments is loaded as a plugin from third-party applications and has been used to make movies you have seen. Our customers love it and have never complained about problems with the scripting engine. Audio work is interesting, because you can think and think and think about what will work and what wont, and at the end of the day all that matters is that the audio is smooth and the code doesn't crash. We need just a liiiitle push to get our code to work at low latencies, and the only thing that is standing in our way is that all threads 9usually around 20 have to block on the Gil, and this causes small gaps in the sound at low latencies (around 5ms, or 64 sample period). ...almost perfect. On Sun, Nov 29, 2009 at 8:57 AM, Aahz wrote: > In article <4b0b07a1$0$22159$9b622d9e at news.freenet.de>, > =?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?= ? wrote: >> >>In any case, I don't think you'll need a multi-process solution; a >>single-process multi-threading approach will do fine. Just create >>*another* thread, that runs at a low priority and is allowed to block. >>Run the Python interpreter in that thread (create multiple of these if >>you need them). ?Then, use some queuing producer-consumer communication >>between the high-priority thread and the low priority thread. Have the >>high priority threads put requests into the queue, and the low priority >>thread take them from the queue, dispatching them to Python. Make sure >>you use non-blocking synchronization on the queue, or else priority >>inheritance if you can get permission to do so. > > This is close to what I would recommend, but I would suggest that the > low-priority thread make calls out to an external Python process; that > way, you can have a Python worker pool of processes. ?Based on what I've > seen posted over the years, I generally recommend against instantiating > multiple interpreter instances (although I've seen some success stories, > I've seen more people butting their heads against the brick wall). > -- > Aahz (aahz at pythoncraft.com) ? ? ? ? ? <*> ? ? ? ? http://www.pythoncraft.com/ > > The best way to get information on Usenet is not to ask a question, but > to post the wrong information. > -- > http://mail.python.org/mailman/listinfo/python-list > From kevintylr at gmail.com Tue Dec 1 21:03:03 2009 From: kevintylr at gmail.com (Ethos) Date: Tue, 1 Dec 2009 18:03:03 -0800 (PST) Subject: NumPy installation won't import correctly References: <661c84c0-4f7a-4a77-9418-193aa9cacadf@13g2000prl.googlegroups.com> <7nkd87F3mdj8mU1@mid.uni-berlin.de> Message-ID: <4d3d4246-3073-4ed4-a570-dbb94b46d4e4@r24g2000yqd.googlegroups.com> On Dec 1, 3:33?am, "Diez B. Roggisch" wrote: > Ethos wrote: > > I installed NumPy for python 2.6 on my leopard macbook, using the > > nifty mac installer they now provide. I have the 2.6 official python > > distro installed on my computer, in addition to the 2.5 that is native > > on the mac. When I went to test out the installation, with 2.6, it > > gave me this: > > >>>> import numpy > > Traceback (most recent call last): > > ? File "", line 1, in > > ? File "/Library/Frameworks/Python.framework/Versions/2.6/lib/ > > python2.6/site-packages/numpy/__init__.py", line 132, in > > ? ? import add_newdocs > > ? File "/Library/Frameworks/Python.framework/Versions/2.6/lib/ > > python2.6/site-packages/numpy/add_newdocs.py", line 9, in > > ? ? from lib import add_newdoc > > ? File "/Library/Frameworks/Python.framework/Versions/2.6/lib/ > > python2.6/site-packages/numpy/lib/__init__.py", line 4, in > > ? ? from type_check import * > > ? File "/Library/Frameworks/Python.framework/Versions/2.6/lib/ > > python2.6/site-packages/numpy/lib/type_check.py", line 8, in > > ? ? import numpy.core.numeric as _nx > > ? File "/Library/Frameworks/Python.framework/Versions/2.6/lib/ > > python2.6/site-packages/numpy/core/__init__.py", line 5, in > > ? ? import multiarray > > ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/2.6/ > > lib/python2.6/site-packages/numpy/core/multiarray.so, 2): no suitable > > image found. ?Did find: > > /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site- > > packages/numpy/core/multiarray.so: unknown required load command > > 0x80000022 > > > The file that it claims it can't find a suitable image for does in > > fact exist in that directory. I'm stumped. > > > Funny thing is, when I imported it using python2.5, it worked just > > fine. numpy.test(1,10) ran without a hitch. > > Looks like a binary format issue to me. What does > > file /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/numpy/core/multiarray.so > > give you, and how does it compare to > > file /Library/Frameworks/Python.framework/Versions/2.6/bin/python > > Maybe you need to strip the binaries to your native arch, using lipo. > > Diez I reinstalled numpy, from sourceforge, even though I had already installed the latest version. Same business. 2.5 imports fine, 2.6 doesn't. Here's the output of the commands you gave me. d166-54-tercero-infill-a-1:~ kevin$ file /Library/Frameworks/ Python.framework/Versions/2.6/lib/python2.6/site-packages/numpy/core/ multiarray.so /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site- packages/numpy/core/multiarray.so: Mach-O universal binary with 2 architectures /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site- packages/numpy/core/multiarray.so (for architecture ppc7400): Mach-O bundle ppc /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site- packages/numpy/core/multiarray.so (for architecture i386): Mach-O bundle i386 d166-54-tercero-infill-a-1:~ kevin$ file /Library/Frameworks/ Python.framework/Versions/2.6/bin/python /Library/Frameworks/Python.framework/Versions/2.6/bin/python: Mach-O universal binary with 2 architectures /Library/Frameworks/Python.framework/Versions/2.6/bin/python (for architecture ppc): Mach-O executable ppc /Library/Frameworks/Python.framework/Versions/2.6/bin/python (for architecture i386): Mach-O executable i386 I don't know if this helps. Thanks for the help everyone. Kevin From clp2 at rebertia.com Tue Dec 1 21:03:31 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 1 Dec 2009 18:03:31 -0800 Subject: python bijection In-Reply-To: References: <85100df7-a8b0-47e9-a854-ba8a8a2f3b98@r31g2000vbi.googlegroups.com> Message-ID: <50697b2c0912011803j255977cdpd20ee70a90c2681c@mail.gmail.com> On Tue, Dec 1, 2009 at 5:17 PM, Aahz wrote: > In article <85100df7-a8b0-47e9-a854-ba8a8a2f3b98 at r31g2000vbi.googlegroups.com>, > Joshua Bronson ? wrote: >> >>I noticed the phonebook example in your ActiveState recipe and thought >>you might consider changing it to something like husbands to wives, >>since the names-to-phone-numbers relation is many-to-many. > > What makes you think husbands to wives is one-to-one? ?;-) ?(Even > assuming monogamy, you have husbands-to-husbands and wives-to-wives.) Reminds me of this quite funny blog post: "Gay marriage: the database engineering perspective" http://qntm.org/?gay Cheers, Chris -- http://blog.rebertia.com From cournape at gmail.com Tue Dec 1 21:37:47 2009 From: cournape at gmail.com (David Cournapeau) Date: Wed, 2 Dec 2009 11:37:47 +0900 Subject: NumPy installation won't import correctly In-Reply-To: <4d3d4246-3073-4ed4-a570-dbb94b46d4e4@r24g2000yqd.googlegroups.com> References: <661c84c0-4f7a-4a77-9418-193aa9cacadf@13g2000prl.googlegroups.com> <7nkd87F3mdj8mU1@mid.uni-berlin.de> <4d3d4246-3073-4ed4-a570-dbb94b46d4e4@r24g2000yqd.googlegroups.com> Message-ID: <5b8d13220912011837n4405e9d2y6b2a6c6807b26525@mail.gmail.com> On Wed, Dec 2, 2009 at 11:03 AM, Ethos wrote: > > I reinstalled numpy, from sourceforge, even though I had already > installed the latest version. Same business. 2.5 imports fine, 2.6 > doesn't. > > Here's the output of the commands you gave me. Which exact version of mac os x are you using ? (the output of sw_vers -productVersion would be fine). David From kevintylr at gmail.com Tue Dec 1 22:04:05 2009 From: kevintylr at gmail.com (Ethos) Date: Tue, 1 Dec 2009 19:04:05 -0800 (PST) Subject: NumPy installation won't import correctly References: <661c84c0-4f7a-4a77-9418-193aa9cacadf@13g2000prl.googlegroups.com> <7nkd87F3mdj8mU1@mid.uni-berlin.de> <4d3d4246-3073-4ed4-a570-dbb94b46d4e4@r24g2000yqd.googlegroups.com> Message-ID: On Dec 1, 6:37?pm, David Cournapeau wrote: > On Wed, Dec 2, 2009 at 11:03 AM, Ethos wrote: > > > I reinstalled numpy, from sourceforge, even though I had already > > installed the latest version. Same business. 2.5 imports fine, 2.6 > > doesn't. > > > Here's the output of the commands you gave me. > > Which exact version of mac os x are you using ? (the output of sw_vers > -productVersion > ?would be fine). > > David ProductName: Mac OS X ProductVersion: 10.5.8 BuildVersion: 9L30 Kevin From wuwei23 at gmail.com Tue Dec 1 22:25:48 2009 From: wuwei23 at gmail.com (alex23) Date: Tue, 1 Dec 2009 19:25:48 -0800 (PST) Subject: xmlrpc idea for getting around the GIL References: <6214d7a20911221338l30296032y32d2d1215de57b6d@mail.gmail.com> <83303a84-a8ca-486a-8173-ef0892779f39@x16g2000vbk.googlegroups.com> <4b0b07a1$0$22159$9b622d9e@news.freenet.de> Message-ID: Patrick Stinson wrote: > Not true. We sell the industry leading sampler engine, and it has been > paying my salary for three years. It's high performance - every cycle > counts. Our sampled instruments is loaded as a plugin from third-party > applications and has been used to make movies you have seen. Our > customers love it and have never complained about problems with the > scripting engine. As an occasional bedroom producer I have to ask if you are talking about EastWest's Play? When was Python support added? I'm surprised I missed this at the time... From davea at ieee.org Tue Dec 1 22:28:00 2009 From: davea at ieee.org (Dave Angel) Date: Tue, 01 Dec 2009 22:28:00 -0500 Subject: Reading a file that is changing and getting the new lines In-Reply-To: References: Message-ID: <4B15DEC0.4050102@ieee.org> Ouray Viney wrote: > Hi: > > Problem: > ========= > I want to read a ASCII text file that can have data appended to it. I > have hacked some code together that handles the basics, but it falls > short. My code doesn't read in the new lines that could have been > added to the end of the file. Not python's fault, more that I don't > know how to do it in python. > > Example scenario: As the python script is running a user/application > adds new entries to the end of the test case file, example, adds the > following to the file. > > test4 > test5 > test6 > > I need clarification. Is this an independent process, that appends data onto the same file, after the python script has opened it, but while it's still running? Can you give me an example point in your source code that your script might be running when the other application does its append? > The python code below, won't pick these changes up. > > Analysis: > ======== > I understand why my code doesn't handle the addition of new data. > This is simply because the os.open reads all the lines in the > os.open() doesn't read the lines, the readlines() call does. Once you've got the data in a list, of course changing the file has no impact on your code. And by the way, you didn't call os.open(), you called open(). They are not interchangeable. > beginning and since the data is added after that, the for loop doesn't > iterate through it since it doesn't know about it. Please note, my > code is not pretty and isn't at all advanced. > > Code: > ====== > import os,string,sys,time > > # define locals > tcListFile="testcase_list.txt" > fh=open(tcListFile,"r") > tcList=fh.readlines() > fh.close() > > for tc in tcList: > print tc.strip() > print "sleeping for 2 seconds" > time.sleep(2) > > # close the file handle > fh.close() > > text file: > ====== > test1 > test2 > test3 > > Question: > ========= > What is the best way to handle this type of scenario using python? > You can solve your first level of problem by simply skipping the readlines() call, and eliminating the first close() call. You close it again later, let that be the only close. You want your loop to actually get a line from the file, not from a list which is frozen in time. Naturally, you'd want a better name than tcList. Next problem is likely to be one of sharing the file. You open it read-only, the other application simultaneously tries to append. Does the OS permit that? You find out. You might actually have to close the file during those sleep() calls, and then do an open/seek to get to the earlier position. You most likely will have to switch from open() to os.open(). The calls are very different. Final problem that I note is how to decide when to quit your loop. Just because you hit eof (end of file), doesn't mean the other application isn't about to append another 50 lines. So you need a different termination condition. I suspect the sharing problems aren't going to be portable between operating systems, so you might want to answer the usual "what version of Python, on what OS" question that we seem to have for most new questions. DaveA From tjreedy at udel.edu Tue Dec 1 22:33:14 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 01 Dec 2009 22:33:14 -0500 Subject: Tracing variable scope (local vs. global) In-Reply-To: References: Message-ID: Manuel Graune wrote: > Hello, > > consider the following piece of code: > > a=1 > b=2 > > def foo(c): > b=3 > return a + b + c > > In this case, when calling "foo", "a" will take the global value, > "b" will take the local value and "c" will take the value assigned > when calling the function. > > Since I consider this behaviour a possible source of bugs due to > personal sloppiness (e. g. forgetting to put "a=4" inside the > function-body): > > Is there any way to automatically check that all variables in a > function are either local or passed in as arguments? There are at least 3 code checking programs: pychecker, pylint, pyflakes. Perhaps one of them has an option to check for non-builtin globals. Would not be too difficult to add, I suspect. From ben+python at benfinney.id.au Tue Dec 1 22:56:14 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 02 Dec 2009 14:56:14 +1100 Subject: Creating a local variable scope. References: <4b12f20c@dnews.tpgi.com.au> <97a101a2-1362-46f4-9308-b72e5c4ac392@s20g2000yqd.googlegroups.com> <9f5d0933-4aae-45a9-8111-84a399c493c9@b15g2000yqd.googlegroups.com> Message-ID: <87fx7um3kx.fsf@benfinney.id.au> markolopa writes: > Hi Roger, > [?] > > Long, descriptive variable names all_in_lower_case > > Function names all in CamelCase > > Global names are in ALL CAPS > > yes, pep8 I guess. Not quite: it deviates from PEP 8 on function names, which should rather be ?lower_case_words_separated_by_underscores?. The ?UPPER_CASE_WORDS_WITH_UNDERSCORES? form is for ?constants?, i.e. names that indicate they should stay bound to the same value through the life of the program (which is the closest normal Python programs get to a ?constant? binding). The ?TitleCase? form should be used only for class names. The ?camelCase? form is not conformant with PEP 8 at all (which makes me glad, since it's hideous). -- \ ?I see little commercial potential for the Internet for at | `\ least ten years.? ?Bill Gates, 1994 | _o__) | Ben Finney From rami.chowdhury at gmail.com Tue Dec 1 23:57:12 2009 From: rami.chowdhury at gmail.com (Rami Chowdhury) Date: Tue, 1 Dec 2009 20:57:12 -0800 Subject: High-performance Python websites In-Reply-To: References: <7cdd7775-0524-4f10-a347-6e79038c821b@a39g2000pre.googlegroups.com> Message-ID: <200912012057.12139.rami.chowdhury@gmail.com> On Monday 30 November 2009 10:55:55 inhahe wrote: > On Wed, Nov 25, 2009 at 7:33 PM, ShoqulKutlu wrote: > > Hi, > > > > Managing load of high volume of visitors is a common issue for all > > kind of web technologies. I mean this is not the python issue. This > > issue is mostly about server level designs. You need to supply load > > balancing for both web servers and databases to make your web site > > able to respond to several concurrent visitors. Of course a good > > programmed website is a key performance issue but for your mention > > I would also suggest considering how many hardwares, how many > > webservers, how many database cluster and which database server > > should be used or will be used in the future.. > > I don't know a lot about this issue, but take apache + php. every > time a page is loaded a new instance of php is loaded to run the > page, AFAIK that's only the case for PHP-CGI, and Python as a CGI scripting language is used the same way. Apache is very often run with mod_php, though, which embeds the PHP interpreter; mod_python does something similar for Python. ---- Rami Chowdhury "As an online discussion grows longer, the probability of a comparison involving Nazis or Hitler approaches one." -- Godwin's Law 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) From gallium.arsenide at gmail.com Wed Dec 2 00:35:12 2009 From: gallium.arsenide at gmail.com (John Yeung) Date: Tue, 1 Dec 2009 21:35:12 -0800 (PST) Subject: combinatorics via __future__ generators References: <3b45b550-11dc-41a6-8c49-02f6cfaad6d5@j24g2000yqa.googlegroups.com> Message-ID: On Dec 1, 5:55?pm, Phlip wrote: > Awesome thanks - but: > > > from itertools import imap,product > > Do we have a version for Python2.5? I have to support an older server > here; can't install a newer python on it... If you can get by with the performance of pure Python, a solution is right in the documentation for 2.6: ### def product(*args, **kwds): # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111 pools = map(tuple, args) * kwds.get('repeat', 1) result = [[]] for pool in pools: result = [x+[y] for x in result for y in pool] for prod in result: yield tuple(prod) ### The docs for itertools are full of these definitions (for 2.6 functions) that can be used as recipes (if you don't have 2.6). John From davea at ieee.org Wed Dec 2 00:39:50 2009 From: davea at ieee.org (Dave Angel) Date: Wed, 02 Dec 2009 00:39:50 -0500 Subject: Raw strings as input from File? In-Reply-To: References: Message-ID: <4B15FDA6.1060204@ieee.org> rzed wrote: > utabintarbo wrote in > news:adc6c455-5616-471a-8b39-d7fdad2179e4 at m33g2000vbi.googlegroups.c > om: > > >> I have a log file with full Windows paths on a line. eg: >> K:\A\B\C\10xx\somerandomfilename.ext->/a1/b1/c1/10xx >> \somerandomfilename.ext ; t9999xx; 11/23/2009 15:00:16 ; >> 1259006416 >> >> As I try to pull in the line and process it, python changes the >> "\10" to a "\x08". This is before I can do anything with it. Is >> there a way to specify that incoming lines (say, when using >> .readlines() ) should be treated as raw strings? >> >> TIA >> > > Despite all the ragging you're getting, it is a pretty flakey thing > When the OP specified readline(), which does *not* behave this way, he probably deserved what you call "ragging." The backslash escaping is for string literals, which are in code, not in data files. In any case, there's a big difference between surprising (to you), and flakey. > that Python does in this context: > (from a python shell) > >>>> x = '\1' >>>> x >>>> > '\x01' > >>>> x = '\10' >>>> x >>>> > '\x08' > > If you are pasting your string as a literal, then maybe it does the > same. It still seems weird to me. I can accept that '\1' means x01, > but \10 seems to be expanded to \010 and then translated from octal > to get to x08. That's just strange. I'm sure it's documented > somewhere, but it's not easy to search for. > > Check in the help for "escape Strings". It's documented (in vers. 2.6, anyway) in a nice chart that backslash followed by 3 digits, is interpreted as octal. I don't like it much either, but it's inherited from C, which has worked that way for 30+ years. Online, see http://www.python.org/doc/2.6.4/reference/lexical_analysis.html, and look in section 2.4.1 for the chart. > Oh, and this: > >>>> '\7' >>>> > '\x07' > >>>> '\70' >>>> > '8' > ... is realy odd. > > Octal 70 is hex 38 (or decimal 56), which is the character '8'. DaveA From tomanishkb at gmail.com Wed Dec 2 01:05:40 2009 From: tomanishkb at gmail.com (M Kumar) Date: Wed, 2 Dec 2009 11:35:40 +0530 Subject: commands module for windows Message-ID: <783b47270912012205y2935f1ebo3ff7e1d091d71494@mail.gmail.com> Dear all, Is there any python module for windows which is equivalent to commands module in linux? -- thanks & regards, Maneesh KB -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Wed Dec 2 01:12:09 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 1 Dec 2009 22:12:09 -0800 Subject: commands module for windows In-Reply-To: <783b47270912012205y2935f1ebo3ff7e1d091d71494@mail.gmail.com> References: <783b47270912012205y2935f1ebo3ff7e1d091d71494@mail.gmail.com> Message-ID: <50697b2c0912012212g41175c33oeddb07ed7c98a39@mail.gmail.com> On Tue, Dec 1, 2009 at 10:05 PM, M Kumar wrote: > Is there any python module for windows which is equivalent to commands > module in linux? `subprocess` should work: http://docs.python.org/library/subprocess.html The `commands` docs even say: "The subprocess module provides more powerful facilities for spawning new processes and retrieving their results. Using the subprocess module is preferable to using the commands module." Cheers, Chris -- http://blog.rebertia.com From tomanishkb at gmail.com Wed Dec 2 01:34:25 2009 From: tomanishkb at gmail.com (M Kumar) Date: Wed, 2 Dec 2009 12:04:25 +0530 Subject: commands module for windows In-Reply-To: <50697b2c0912012212g41175c33oeddb07ed7c98a39@mail.gmail.com> References: <783b47270912012205y2935f1ebo3ff7e1d091d71494@mail.gmail.com> <50697b2c0912012212g41175c33oeddb07ed7c98a39@mail.gmail.com> Message-ID: <783b47270912012234l58b383a2pdcf0ec9cb01829d@mail.gmail.com> can I use this module to store output to a python variable? I am looking for something similar to commands.getoutput("") On Wed, Dec 2, 2009 at 11:42 AM, Chris Rebert wrote: > On Tue, Dec 1, 2009 at 10:05 PM, M Kumar wrote: > > Is there any python module for windows which is equivalent to commands > > module in linux? > > `subprocess` should work: http://docs.python.org/library/subprocess.html > > The `commands` docs even say: > "The subprocess module provides more powerful facilities for spawning > new processes and retrieving their results. > Using the subprocess module is preferable to using the commands module." > > Cheers, > Chris > -- > http://blog.rebertia.com > -- thanks & regards, Maneesh KB Sent from Delhi, DL, India -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Wed Dec 2 01:40:16 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 1 Dec 2009 22:40:16 -0800 Subject: commands module for windows In-Reply-To: <783b47270912012234l58b383a2pdcf0ec9cb01829d@mail.gmail.com> References: <783b47270912012205y2935f1ebo3ff7e1d091d71494@mail.gmail.com> <50697b2c0912012212g41175c33oeddb07ed7c98a39@mail.gmail.com> <783b47270912012234l58b383a2pdcf0ec9cb01829d@mail.gmail.com> Message-ID: <50697b2c0912012240p73f213ddm915d69fd6a6f5688@mail.gmail.com> > On Wed, Dec 2, 2009 at 11:42 AM, Chris Rebert wrote: >> On Tue, Dec 1, 2009 at 10:05 PM, M Kumar wrote: >> > Is there any python module for windows which is equivalent to commands >> > module in linux? >> >> `subprocess` should work: http://docs.python.org/library/subprocess.html >> >> The `commands` docs even say: >> "The subprocess module provides more powerful facilities for spawning >> new processes and retrieving their results. >> Using the subprocess module is preferable to using the commands module." On Tue, Dec 1, 2009 at 10:34 PM, M Kumar wrote: > can I use this module to store output to a python variable? > I am looking for something similar to > commands.getoutput("") Yes, of course it can. If it's more powerful, then it can do everything the other module can. It'd be silly for the `commands` docs to point people to `subprocess` if this wasn't the case. It will take more than a single line of code though. Read the module's docs. Regards, Chris -- http://blog.rebertia.com From tomanishkb at gmail.com Wed Dec 2 01:46:39 2009 From: tomanishkb at gmail.com (M Kumar) Date: Wed, 2 Dec 2009 12:16:39 +0530 Subject: commands module for windows In-Reply-To: <50697b2c0912012240p73f213ddm915d69fd6a6f5688@mail.gmail.com> References: <783b47270912012205y2935f1ebo3ff7e1d091d71494@mail.gmail.com> <50697b2c0912012212g41175c33oeddb07ed7c98a39@mail.gmail.com> <783b47270912012234l58b383a2pdcf0ec9cb01829d@mail.gmail.com> <50697b2c0912012240p73f213ddm915d69fd6a6f5688@mail.gmail.com> Message-ID: <783b47270912012246q4b014071va9bdf3a525bd1f9@mail.gmail.com> thank you very much Chris :) On Wed, Dec 2, 2009 at 12:10 PM, Chris Rebert wrote: > > On Wed, Dec 2, 2009 at 11:42 AM, Chris Rebert wrote: > >> On Tue, Dec 1, 2009 at 10:05 PM, M Kumar wrote: > >> > Is there any python module for windows which is equivalent to commands > >> > module in linux? > >> > >> `subprocess` should work: > http://docs.python.org/library/subprocess.html > >> > >> The `commands` docs even say: > >> "The subprocess module provides more powerful facilities for spawning > >> new processes and retrieving their results. > >> Using the subprocess module is preferable to using the commands module." > > On Tue, Dec 1, 2009 at 10:34 PM, M Kumar wrote: > > can I use this module to store output to a python variable? > > I am looking for something similar to > > commands.getoutput("") > > Yes, of course it can. If it's more powerful, then it can do > everything the other module can. > It'd be silly for the `commands` docs to point people to `subprocess` > if this wasn't the case. > It will take more than a single line of code though. Read the module's > docs. > > Regards, > Chris > -- > http://blog.rebertia.com > -- thanks & regards, Maneesh KB Sent from Delhi, DL, India -------------- next part -------------- An HTML attachment was scrubbed... URL: From subhakolkata1234 at gmail.com Wed Dec 2 01:48:49 2009 From: subhakolkata1234 at gmail.com (joy99) Date: Tue, 1 Dec 2009 22:48:49 -0800 (PST) Subject: Question on Python as career References: <614b8dde-324b-4d54-8e73-7a96e4c0b1cf@a21g2000yqc.googlegroups.com> <_DfRm.61945$rE5.35795@newsfe08.iad> Message-ID: <47a66571-96d2-4976-9812-5b90b6fc5271@u7g2000yqm.googlegroups.com> On Dec 2, 2:11?am, Phlip wrote: > joy99 wrote: > > I have developed the following toolkits: > > (i) A web based crawler; > > (ii) A Bayesian classifier; > > (iii) One NER engine; > > (iv) One XML parser; > > (v) One PoS Tagger; > > (vi) One Parser based on CRF; > > (vii) One MLE training system; > > (viii) One Spell Checker; > > (ix) One Transliteration System; > > > I have developed them either in Python2.5 and Python2.6. > > > After I complete my Post Doctoral which may be only 2-3 months away, > > with this knowledge can I join IT? > > All your items are computer science. IT is about software engineering. That > means _avoiding_ new research in preference for efficiently implementing > business solutions. You are right. But problem is that in our country hardly any people work in the cutting edge technology. Something has been brought out in the west and we try to imulate over here. At the end of the day, when you see you toiled so much for a problem but it is actuallly someone else's algorithm things are bit frustating. But well, my teachers taught me whatever they could. In Indian Institute of Science, well things are only bit better that some of personal algorithms or revisions get approved. I may continue with research but why to follow someone else's foot step althrough life? So, better to earn money do a decent job instead of doing all these. If I have enough inertia I can do it later too. Many people do it. > > > Or Do I have to learn anything new? > > Test Driven Development. I've to know this. > Active Record (ORM models) I've to know this too. > HTML & webby technologies I know it bit. HTML,XML,DHTML,SSML I know. I have slight knowledge of Joomla and SOA. > platforms & deployment issues I will check on this. > GNU, open source, and version controlling I know it bit. > Behavior Driven Development > > > Are there any India based opportunities- as I checked Python job board > > it is very less. > > Ideally, IT should get the job done using a soft language like Python, Ruby, or > Lua. IT should not waste its time using a hard language like C++. That is for > system programming - making the modules that IT reuses. > > > If I get anything after completing my Post Doc with present base of > > knowledge what profiles I may expect? > > How about videogames? They always need hard algorithms & > computer science. That is a nice thought. Thank you Sir. But I may have to be expert in Graphics and Animation, too. I am trying to find out. > > -- I was thinking if I need to know Django,any good RDBMS(I know only MS- Access) Best Regards, Subhabrata. > ? ?Phlip > ? ?http://c2.com/cgi/wiki?ZeekLand- Hide quoted text - > > - Show quoted text - From dochoncho at gmail.com Wed Dec 2 02:07:10 2009 From: dochoncho at gmail.com (Joel Madigan) Date: Wed, 2 Dec 2009 02:07:10 -0500 Subject: Recursion head scratcher Message-ID: Hi everyone! Sorry this isn't strictly a Python question but my algorithms professor contends that given the standard recursive-backtracking maze solving algorithm: width=6 height=4 maze=[[1,0,1,1,0,1], [0,0,1,0,0,0], [1,0,1,0,1,0], [0,0,0,0,1,1]] visited = [[False for x in range(width)] for y in range(height)] sx=1 sy=2 ex=4 ey=0 def findPath(x,y): if (x < 0 or x >= width or y < 0 or y >= height): return False elif maze[y][x] == 1: return False elif visited[y][x]: return False elif (x == ex and y == ey): print "(%d,%d)"%(x,y), return True else: visited[y][x] = True if findPath(x-1,y) or \ findPath(x+1,y) or \ findPath(x,y-1) or \ findPath(x,y+1): print "(%d,%d)"%(x,y), return True else: return False print findPath(sx,sy) that it is possible to make it print the path to the finish in the order the steps were taken. That is, the algorithm as written produces: (4,0) (4,1) (3,1) (3,2) (3,3) (2,3) (1,3) (1,2) True Rather than (1,2) (1,3) (2,3) (3,3) (3,2) (3,1) (4,1) (4,0) True Furthermore, he claims it's a "one line change" without using a stack or any other extra data structure. But I can't figure it out to save my life. This isn't homework, there isn't credit on the line. I think he said it just to mess with us. Can anyone point me in the right direction? It's driving me crazy. The output it gives makes perfect sense, since it just prints out each step as the stack unwinds. Normally you would print the output BEFORE recursing, but in this case you only want to print the step if it is actually part of the path. And you don't know that until after the recursion. Can anyone shed some light on this? Thanks, Joel -------------- next part -------------- An HTML attachment was scrubbed... URL: From schettino72 at gmail.com Wed Dec 2 02:45:19 2009 From: schettino72 at gmail.com (Eduardo Schettino) Date: Wed, 2 Dec 2009 15:45:19 +0800 Subject: [ANN] doit 0.5 Message-ID: doit - Automation Tool doit comes from the idea of bringing the power of build-tools to execute any kind of task. It will keep track of dependencies between "tasks" and execute them only when necessary. It was designed to be easy to use and "get out of your way". doit can be used as: * a build tool (generic and flexible) * home of your management scripts (it helps you organize and combine shell scripts and python scripts) * a functional tests runner (combine together different tools) homepage: http://python-doit.sourceforge.net/ PyPi: http://pypi.python.org/pypi/doit license: MIT contact: https://launchpad.net/~schettino72 Regards, Eduardo From tim.wintle at teamrubber.com Wed Dec 2 02:53:51 2009 From: tim.wintle at teamrubber.com (Tim Wintle) Date: Wed, 02 Dec 2009 07:53:51 +0000 Subject: Recursion head scratcher In-Reply-To: References: Message-ID: <1259740431.14504.6.camel@localhost> On Wed, 2009-12-02 at 02:07 -0500, Joel Madigan wrote: > > that it is possible to make it print the path to the finish in the > order the steps were taken. That is, the algorithm as written > produces: (4,0) (4,1) (3,1) (3,2) (3,3) (2,3) (1,3) (1,2) True > > Rather than (1,2) (1,3) (2,3) (3,3) (3,2) (3,1) (4,1) (4,0) True > > Furthermore, he claims it's a "one line change" without using a stack > or any other extra data structure The way I see immediately is a three line change (if you include modifying/removing the existing print statements). It will be one line shorter to print the other order. As a hint - think of what the python interpreter's stack looks like when it's running your code at the moment - that's the stack you're currently using (and need to use) to store the results you print. Tim From list at qtrac.plus.com Wed Dec 2 03:01:34 2009 From: list at qtrac.plus.com (Mark Summerfield) Date: Wed, 2 Dec 2009 00:01:34 -0800 (PST) Subject: Moving from Python 2 to Python 3: A 4 page "cheat sheet" References: <291d64cb-cc5c-4109-822c-84d58ed7b18b@k17g2000yqh.googlegroups.com> Message-ID: On 1 Dec, 17:50, Mark Dickinson wrote: > On Dec 1, 2:03?pm, Mark Summerfield wrote: > > > I've produced a 4 page document that provides a very concise summary > > of Python 2<->3 differences plus the most commonly used new Python 3 > > features. > > Very nice indeed! > > My only quibble is with the statement on the first page that > the 'String % operator is deprecated'. ?I'm not sure that's > true, for all values of 'deprecated'. ?There don't appear > to be any definite plans for getting rid of it just yet. > > Mark I didn't make this up:-) According to http://docs.python.org/dev/3.0/whatsnew/3.0.html "The plan is to eventually make this the only API for string formatting, and to start deprecating the % operator in Python 3.1." From list at qtrac.plus.com Wed Dec 2 03:10:45 2009 From: list at qtrac.plus.com (Mark Summerfield) Date: Wed, 2 Dec 2009 00:10:45 -0800 (PST) Subject: Moving from Python 2 to Python 3: A 4 page "cheat sheet" References: <291d64cb-cc5c-4109-822c-84d58ed7b18b@k17g2000yqh.googlegroups.com> <4b156121$1@dnews.tpgi.com.au> Message-ID: <3851f624-f2cd-40fb-a898-cfd08d5cf0fa@e7g2000vbi.googlegroups.com> On 1 Dec, 18:30, Lie Ryan wrote: > On 12/2/2009 1:03 AM, Mark Summerfield wrote: > > > > > I've produced a 4 page document that provides a very concise summary > > of Python 2<->3 differences plus the most commonly used new Python 3 > > features. It is aimed at existing Python 2 programmers who want to > > start writing Python 3 programs and want to use Python 3 idioms rather > > than those from Python 2 where the idioms differ. > > > It uses Python 3.1 syntax since that looks like being the standard for > > a few years in view of the language moratorium. > > > The document is U.S. Letter size but will also print fine on A4 > > printers. > > > It is available as a free PDF download (no registration or anything) > > from InformIT's website. Here's the direct link: > >http://ptgmedia.pearsoncmg.com/imprint_downloads/informit/promotions/... > > > And of course, if you want more on Python 3, there's always the > > documentation---or my book:-) > > "Programming in Python 3 (Second Edition)" ISBN-10: 0321680561. > > Nice. Thanks! > I suggest changing the lambda example a bit, the current example says: > Python 2 ? ? ? ? ? ? ? ? ? ? ?Python 3 > lambda (a,b): a + b ? ? ? ? ? lambda t: t[0] + t[1] > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?lambda a, b: a + b > > into something like: > > Python 2 ? ? ? ? ? ? ? ? ? ? ?Python 3 > lambda (a,b),c: a + b + c ? ? lambda t, c: t[0] + t[1] + c > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?lambda a, b, c: a + b + c > > it is unclear at first sight that it refers to tuple argument unpacking. Your proposed example is clearer in some respects, but mine is more minimal. And I think that anyone who _thinks_ about mine will get the point. (The document is short, but I never claimed it was a quick read;-) > There should also some mention that tuple argument unpacking for regular > function (def) is also gone. I probably should have, but it is hard to fit any more in... esp. since I don't want to take anything out. > Also, I'm not sure what this change is referring to: > Python 2 ? ? ? ? ? ? ? ? Python 3 > L = list(seq) ? ? ? ? ? ?L = sorted(seq) > L.sort() > > L.sort is still available in python, and sorted() have been available > since python 2. Both list.sort() and sorted() are for different purpose, > and neither will be deprecated. What's the change here? The document is about idioms as well as changes. In this case both approaches work in both versions, but it seems that there are still a lot of people who don't know about sorted(), so I put it in to show it as an idiom. From list at qtrac.plus.com Wed Dec 2 03:13:07 2009 From: list at qtrac.plus.com (Mark Summerfield) Date: Wed, 2 Dec 2009 00:13:07 -0800 (PST) Subject: Moving from Python 2 to Python 3: A 4 page "cheat sheet" References: <291d64cb-cc5c-4109-822c-84d58ed7b18b@k17g2000yqh.googlegroups.com> Message-ID: <72210605-4f70-401e-834b-af499080fd31@j35g2000vbl.googlegroups.com> On 1 Dec, 21:55, Terry Reedy wrote: > Mark Summerfield wrote: > > I've produced a 4 page document that provides a very concise summary > > of Python 2<->3 differences plus the most commonly used new Python 3 > > features. It is aimed at existing Python 2 programmers who want to > > start writing Python 3 programs and want to use Python 3 idioms rather > > than those from Python 2 where the idioms differ. > > > It uses Python 3.1 syntax since that looks like being the standard for > > a few years in view of the language moratorium. > > > The document is U.S. Letter size but will also print fine on A4 > > printers. > > > It is available as a free PDF download (no registration or anything) > > from InformIT's website. Here's the direct link: > >http://ptgmedia.pearsoncmg.com/imprint_downloads/informit/promotions/... > > > And of course, if you want more on Python 3, there's always the > > documentation---or my book:-) > > "Programming in Python 3 (Second Edition)" ISBN-10: 0321680561. > > What might be even *more* helpful, with contributions from others > perhaps, would be an indication of which changes are handled > automatically by 2to3.py and which must be done by hand. > > tjr No, that's exactly what I did not want to cover and the document says so up front. It is aimed at people who want Python 3 to come from their own brains and fingers! Also, the kind of info you're talking about is covered elsewhere, for example: http://diveintopython3.org/porting-code-to-python-3-with-2to3.html From list at qtrac.plus.com Wed Dec 2 03:17:37 2009 From: list at qtrac.plus.com (Mark Summerfield) Date: Wed, 2 Dec 2009 00:17:37 -0800 (PST) Subject: Moving from Python 2 to Python 3: A 4 page "cheat sheet" References: <291d64cb-cc5c-4109-822c-84d58ed7b18b@k17g2000yqh.googlegroups.com> <87ljhm8d7e.fsf@castleamber.com> Message-ID: <765817ea-e502-4ec9-8639-d0d0a5b6c85f@g31g2000vbr.googlegroups.com> On 1 Dec, 23:52, John Bokma wrote: > Mark Summerfield writes: > > It is available as a free PDF download (no registration or anything) > > from InformIT's website. Here's the direct link: > >http://ptgmedia.pearsoncmg.com/imprint_downloads/informit/promotions/... > > Thanks! > > > And of course, if you want more on Python 3, there's always the > > documentation---or my book:-) > > "Programming in Python 3 (Second Edition)" ISBN-10: 0321680561. > > Meh, second edition already? Haven't read the entire first edition > yet. Which is IMO a good book (I also gave it to my brother as a > present). If it is any consolation, the second edition should have a much longer life, now that we have the language moratorium. (I _really_ wanted to cover 3.1.) > Only negative point (to me) so far is that in the beginning (p8-9) the > book mentions placing Python programs in C:\py3eg which gives me the > unpleasant feeling that someone is coding on Windows XP with > Administrator rights... OK, you got me there, I only use Windows for testing purposes and my personal logon account does have Administrator rights, which I assumed was standard for personal machines? Also, the path is short. It is only a suggestion, it really doesn't matter where you unpack the examples. > Anyway, will add the 2nd edition to my wish list and donate the current > one to the library in Xalapa (USBI) ?if they want it :-) > > John From madhura22 at gmail.com Wed Dec 2 03:20:11 2009 From: madhura22 at gmail.com (madhura vadvalkar) Date: Wed, 2 Dec 2009 00:20:11 -0800 Subject: Help in wxpython Message-ID: <86b3db7d0912020020k51cf6bc8me0bc543214c582f1@mail.gmail.com> Hi I am trying to write an PAINT like application where on the mouse click a circle is drawn on canvas. I am new to python and using wxpython to create this. here is the code: import wx class SketchWindow(wx.Window): def __init__ (self, parent,ID): wx.Window.__init__(self, parent, ID) self.panel =wx.Panel(self, size= (350,350)) self.pen=wx.Pen( 'blue',4) self.pos=(0,0) self.InitBuffer() self.Bind(wx.EVT_LEFT_DOWN,self.OnLeftDown) def InitBuffer(self): size=self.GetClientSize() self.Buffer=wx.EmptyBitmap(size.width,size.height) dc=wx.BufferedDC(None,self.buffer) dc.SetBackground(wx.Brush(self.GetBackgroundColour())) dc.Clear() self.Drawcircle(dc) self.reInitBuffer=False def OnLeftDown(self,event): self.pos=event.GetPositionTuple() self.CaptureMouse() def Drawcircle(self,dc): pen=wx.Pen(colour,thickness,wx.SOLID) dc.SetPen(pen) dc.DrawCircle(self.pos.x,self.pos.y,r) class SketchFrame(wx.Frame): def __init__(self, parent): wx.Frame.__init__(self, parent, -1, "Sketch Frame",size=(800,600)) self.sketch = SketchWindow(self, -1) if __name__=='__main__': app=wx.PySimpleApp() frame=SketchFrame(None) frame.Show(True) app.MainLoop() I am getting the following error: Traceback (most recent call last): File "C:/Python26/circle.py", line 42, in frame=SketchFrame(None) File "C:/Python26/circle.py", line 38, in __init__ self.sketch = SketchWindow(self, -1) File "C:/Python26/circle.py", line 12, in __init__ self.InitBuffer() File "C:/Python26/circle.py", line 19, in InitBuffer dc=wx.BufferedDC(None,self.buffer) AttributeError: 'SketchWindow' object has no attribute 'buffer' Please tell me what I am doing wrong. Thanks -- Madhura From bruno.42.desthuilliers at websiteburo.invalid Wed Dec 2 03:48:45 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 02 Dec 2009 09:48:45 +0100 Subject: getattr problem In-Reply-To: References: <4dc0cfea0912011032s3fc0be8doa361bb390697682f@mail.gmail.com> Message-ID: <4b1629e3$0$29357$426a74cc@news.free.fr> > Victor Subervi wrote: (NB : answering to the OP - the post didn't show up on clpy) >> Hi; >> I have the following code that execute without a problem: Fine. But it fails to execute here - ImportError on the 3rd line ("options"), NameErrors on the 4th line ("addStore") and 5th line ("optionTables"). >> import sys,os >> sys.path.append(os.getcwd()) >> import options >> storesTables = [] OT, but the official naming convention in Python is all_lower_with_underscores. >> junkStores = string.join(addStore(), ', ') junkStores = ", ".join(addStore()) >> for table in optionsTables(): OT again, but a general (not python-specific) naming rule is to use nouns for variables and verbs for functions. I almost failed to spot the parens after "optionsTables". "getOptionsTables" or something like this would make your intent more obvious IM(NS)HO. >> if table not in ('particulars', junkStores): I dont know for sure what junkStores looks like at this point, but given the call to string.join, chances are this test doesn't work as expected - cf the following snippet: """ >>> foo = ("bar", "baaz, back") >>> "bar" in foo True >>> "baaz" in foo False >>> """ >> storesTables.append(table) >> for table in storesTables: You don't need two loops here - you could as well proceed as you go, ie: for table in optionsTables(): if pass_some_test(table): proceed_with(table) >> try: >> fn = getattr(options, table) >> print fn() >> except: >> pass AAAARRRGHHH ! NO ! DONT ! EVER ! DO ! THAT ! You have to either *properly* handle and exception OR let it propagate. For the record, even sys.exit is implemented as an exception. >> I need to change the obvious line to this or something similar (that >> actually works): >> >> fn = getattr(options, '%s("names")' % table) >> >> That is, I need to pass the variable "names" to each table as it is >> called. How does this relate to the above line of code ??????? It really looks like you're programming by accident (IOW : try anything until it seems to "work", but without any understanding of what your code is *really* doing....) > How do I do this? If the question is "how do I pass a variable to a function", then you probably didn't write the above code and shouldn't even touch it before you learn CS101. Else, please explain more exactly what you're trying to do - would be better with an executable, self-contained example. From bruno.42.desthuilliers at websiteburo.invalid Wed Dec 2 03:52:32 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 02 Dec 2009 09:52:32 +0100 Subject: High-performance Python websites In-Reply-To: References: <7cdd7775-0524-4f10-a347-6e79038c821b@a39g2000pre.googlegroups.com> Message-ID: <4b162ac6$0$7063$426a34cc@news.free.fr> Rami Chowdhury a ?crit : > On Monday 30 November 2009 10:55:55 inhahe wrote: >> On Wed, Nov 25, 2009 at 7:33 PM, ShoqulKutlu > wrote: >>> Hi, >>> >>> Managing load of high volume of visitors is a common issue for all >>> kind of web technologies. I mean this is not the python issue. This >>> issue is mostly about server level designs. You need to supply load >>> balancing for both web servers and databases to make your web site >>> able to respond to several concurrent visitors. Of course a good >>> programmed website is a key performance issue but for your mention >>> I would also suggest considering how many hardwares, how many >>> webservers, how many database cluster and which database server >>> should be used or will be used in the future.. >> I don't know a lot about this issue, but take apache + php. every >> time a page is loaded a new instance of php is loaded to run the >> page, > > AFAIK that's only the case for PHP-CGI, and Python as a CGI scripting > language is used the same way. Yeps. > Apache is very often run with mod_php, > though, which embeds the PHP interpreter; mod_python does something > similar for Python. Indeed. And FWIW, this has very few impact wrt/ load balancing issues. From dickinsm at gmail.com Wed Dec 2 03:53:34 2009 From: dickinsm at gmail.com (Mark Dickinson) Date: Wed, 2 Dec 2009 00:53:34 -0800 (PST) Subject: Moving from Python 2 to Python 3: A 4 page "cheat sheet" References: <291d64cb-cc5c-4109-822c-84d58ed7b18b@k17g2000yqh.googlegroups.com> Message-ID: <19194586-cd6a-4d13-ae1c-798884194672@n35g2000yqm.googlegroups.com> On Dec 2, 8:01?am, Mark Summerfield wrote: > On 1 Dec, 17:50, Mark Dickinson wrote: > > My only quibble is with the statement on the first page that > > the 'String % operator is deprecated'. ?I'm not sure that's > > true, for all values of 'deprecated'. ?There don't appear > > to be any definite plans for getting rid of it just yet. > > I didn't make this up:-) No, I didn't imagine for a second that you had! > According to http://docs.python.org/dev/3.0/whatsnew/3.0.html > "The plan is to eventually make this the only API for string > formatting, and to start deprecating the % operator in Python 3.1." I think that's a doc bug. "The plan is to ..." should read: "The plan was originally to ...". (Well, at least in the 3.1 version of the "what's new in 3.0" documentation; the 3.0 version that you linked to isn't even autogenerated any more, AFAIK, so fixes to the ReST source for that file never make it to the web site.) I'm a little confused myself about what's actually happening with % formatting, but here's a fairly recent python-dev posting from the BDFL: http://mail.python.org/pipermail/python-dev/2009-September/092399.html Mark From davea at ieee.org Wed Dec 2 03:56:14 2009 From: davea at ieee.org (Dave Angel) Date: Wed, 02 Dec 2009 03:56:14 -0500 Subject: Recursion head scratcher In-Reply-To: References: Message-ID: <4B162BAE.4070306@ieee.org> Joel Madigan wrote: > Hi everyone! > Sorry this isn't strictly a Python question but my algorithms professor > contends that given the standard recursive-backtracking maze solving > algorithm: > > width=6 > height=4 > maze=[[1,0,1,1,0,1], > [0,0,1,0,0,0], > [1,0,1,0,1,0], > [0,0,0,0,1,1]] > visited = [[False for x in range(width)] for y in range(height)] > > sx=1 > sy=2 > ex=4 > ey=0 > > def findPath(x,y): > if (x < 0 or x >= width or y < 0 or y >= height): > return False > elif maze[y][x] == 1: > return False > elif visited[y][x]: > return False > elif (x == ex and y == ey): > print "(%d,%d)"%(x,y), > return True > else: > visited[y][x] = True > > if findPath(x-1,y) or \ > findPath(x+1,y) or \ > findPath(x,y-1) or \ > findPath(x,y+1): > print "(%d,%d)"%(x,y), > return True > else: > return False > > print findPath(sx,sy) > > that it is possible to make it print the path to the finish in the order the > steps were taken. That is, the algorithm as written produces: > (4,0) (4,1) (3,1) (3,2) (3,3) (2,3) (1,3) (1,2) True > > Rather than > (1,2) (1,3) (2,3) (3,3) (3,2) (3,1) (4,1) (4,0) True > > Furthermore, he claims it's a "one line change" without using a stack or any > other extra data structure. But I can't figure it out to save my life. > This isn't homework, there isn't credit on the line. I think he said it > just to mess with us. Can anyone point me in the right direction? It's > driving me crazy. The output it gives makes perfect sense, since it just > prints out each step as the stack unwinds. Normally you would print the > output BEFORE recursing, but in this case you only want to print the step if > it is actually part of the path. And you don't know that until after the > recursion. > > Can anyone shed some light on this? > > Thanks, > Joel > > How about swapping sx,sy with ex,ey ? That's one line (one statement). And the rest of the algorithm appears to be symmetric. Basically, you're reversing time, and starting with the end point, descending till you find the start point. DaveA From davea at ieee.org Wed Dec 2 04:06:08 2009 From: davea at ieee.org (Dave Angel) Date: Wed, 02 Dec 2009 04:06:08 -0500 Subject: Help in wxpython In-Reply-To: <86b3db7d0912020020k51cf6bc8me0bc543214c582f1@mail.gmail.com> References: <86b3db7d0912020020k51cf6bc8me0bc543214c582f1@mail.gmail.com> Message-ID: <4B162E00.8090406@ieee.org> madhura vadvalkar wrote: > Hi > > I am trying to write an PAINT like application where on the mouse > click a circle is drawn on canvas. I am new to python and using > wxpython to create this. > > here is the code: > > import wx > > class SketchWindow(wx.Window): > > def __init__ (self, parent,ID): > > wx.Window.__init__(self, parent, ID) > > self.panel =wx.Panel(self, size= (350,350)) > self.pen=wx.Pen( 'blue',4) > self.pos=(0,0) > self.InitBuffer() > self.Bind(wx.EVT_LEFT_DOWN,self.OnLeftDown) > > def InitBuffer(self): > > size=self.GetClientSize() > self.Buffer=wx.EmptyBitmap(size.width,size.height) > dc=wx.BufferedDC(None,self.buffer) > You spelled the instance attribute differently. You initialized it as "Buffer" but reference it as "buffer" Lowercase would be more standard. > > I am getting the following error: > > Traceback (most recent call last): > File "C:/Python26/circle.py", line 42, in > frame=SketchFrame(None) > File "C:/Python26/circle.py", line 38, in __init__ > self.sketch = SketchWindow(self, -1) > File "C:/Python26/circle.py", line 12, in __init__ > self.InitBuffer() > File "C:/Python26/circle.py", line 19, in InitBuffer > dc=wx.BufferedDC(None,self.buffer) > AttributeError: 'SketchWindow' object has no attribute 'buffer' > > Please tell me what I am doing wrong. > > Thanks > > > From victorsubervi at gmail.com Wed Dec 2 05:33:51 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Wed, 2 Dec 2009 05:33:51 -0500 Subject: Don't Understand This Error Message-ID: <4dc0cfea0912020233r2b441b32t358dc5f2d19609d1@mail.gmail.com> I get the following error: /var/www/html/angrynates.com/cart/chooseOptions.py 8 from login import login 9 import string 10 import options 11 from particulars import optionsTables, addStore 12 options undefined SyntaxError: invalid syntax (options.py, line 140) args = ('invalid syntax', ('/var/www/html/ angrynates.com/cart/options.py', 140, 85, " colorsTables, colorsNames = colors('products', 'specificTables', specificTables):\n")) filename = '/var/www/html/angrynates.com/cart/options.py' lineno = 140 msg = 'invalid syntax' offset = 85 print_file_and_line = None text = " colorsTables, colorsNames = colors('products', 'specificTables', specificTables):\n" I don't understand the 'text = "..." part of the last line. Here's the line from the code: colorsTables, colorsNames = colors('products', 'specificTables', specificTables): No "text". I'm just calling a function and getting the results. Here's the pared-down function: def colors(callingTable, which='', specificTables=[]): code = [] names = [] meanings = [] code.append({'black': '0000FF', 'gray': '465945', 'silver': '708090', 'white': '0F4D92', 'maroon': 'B03060', 'red': 'FE2712', 'purple': '50404D', 'fuchsia': 'FF77FF', 'green': '00A550', 'lime': '32CD32', 'olive': '6B8E23', 'yellow': '9ACD32', 'navy blue': 'CC7722', 'blue': '333399', 'teal': 'E2725B', 'aqua': '7FFFD4'}) meanings.append('These are the standard Web colors.') names.append('standardWebColors') if which == 'specificTables': whichTablesToReturn = [] i = 0 while i < len(names): # We utilize the name of the table to determine where it is in the code tuple for table in specificTables: if names[i] == table: whichTablesToReturn.append(i) i += 1 returnTheseTables = [] for table in whichTablesToReturn: returnTheseTables.append(whichTablesToReturn) returnTheseNames = [] for table in whichTablesToReturn: returnTheseNames.append(whichTablesToReturn) return returnTheseTables, returnTheseNames else: return optionsDict(which) Please help me understand what this error is trying to show me. TIA, Victor -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Wed Dec 2 05:43:43 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Wed, 2 Dec 2009 02:43:43 -0800 Subject: Don't Understand This Error In-Reply-To: <4dc0cfea0912020233r2b441b32t358dc5f2d19609d1@mail.gmail.com> References: <4dc0cfea0912020233r2b441b32t358dc5f2d19609d1@mail.gmail.com> Message-ID: <50697b2c0912020243n4a4af0e9r3373d3091d618c88@mail.gmail.com> On Wed, Dec 2, 2009 at 2:33 AM, Victor Subervi wrote: > I get the following error: > > ?/var/www/html/angrynates.com/cart/chooseOptions.py > ??? 8 from login import login > ??? 9 import string > ?? 10 import options > ?? 11 from particulars import optionsTables, addStore > ?? 12 > options undefined > > SyntaxError: invalid syntax (options.py, line 140) > ????? args = ('invalid syntax', > ('/var/www/html/angrynates.com/cart/options.py', 140, 85, " colorsTables, > colorsNames = colors('products', 'specificTables', specificTables):\n")) > ????? filename = '/var/www/html/angrynates.com/cart/options.py' > ????? lineno = 140 > ????? msg = 'invalid syntax' > ????? offset = 85 > ????? print_file_and_line = None > ????? text = " colorsTables, colorsNames = colors('products', > 'specificTables', specificTables):\n" > > I don't understand the 'text = "..." part of the last line. It's the text of the specific line of code that caused the error, I think. > Here's the line from the code: > > ??? colorsTables, colorsNames = colors('products', 'specificTables', > specificTables): The syntax error is that you have an illegal colon at the end of that line. Remove that colon. > No "text". I'm just calling a function and getting the results. Here's the > pared-down function: > > def colors(callingTable, which='', specificTables=[]): The error lies in the caller of colors(). Cheers, Chris -- http://blog.rebertia.com From bruno.42.desthuilliers at websiteburo.invalid Wed Dec 2 05:55:01 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 02 Dec 2009 11:55:01 +0100 Subject: Don't Understand This Error In-Reply-To: References: <4dc0cfea0912020233r2b441b32t358dc5f2d19609d1@mail.gmail.com> Message-ID: <4b16477b$0$13108$426a34cc@news.free.fr> > On Wed, Dec 2, 2009 at 2:33 AM, Victor Subervi wrote: >> >> def colors(callingTable, which='', specificTables=[]): Warning : default arguments are eval'd only once, at function creation time. This is a well known gotcha that can lead to unexpected behaviours like: def foo(x, bar=[]) bar.append("gotcha %s" % x) print bar for i in range(5): bar(i) From wentland at cl.uni-heidelberg.de Wed Dec 2 06:20:33 2009 From: wentland at cl.uni-heidelberg.de (Wolodja Wentland) Date: Wed, 2 Dec 2009 12:20:33 +0100 Subject: Moving from Python 2 to Python 3: A 4 page "cheat sheet" In-Reply-To: <3851f624-f2cd-40fb-a898-cfd08d5cf0fa@e7g2000vbi.googlegroups.com> References: <291d64cb-cc5c-4109-822c-84d58ed7b18b@k17g2000yqh.googlegroups.com> <4b156121$1@dnews.tpgi.com.au> <3851f624-f2cd-40fb-a898-cfd08d5cf0fa@e7g2000vbi.googlegroups.com> Message-ID: <20091202112033.GA10868@kinakuta.local> On Wed, Dec 02, 2009 at 00:10 -0800, Mark Summerfield wrote: > On 1 Dec, 18:30, Lie Ryan wrote: > > Also, I'm not sure what this change is referring to: > > Python 2 ? ? ? ? ? ? ? ? Python 3 > > L = list(seq) ? ? ? ? ? ?L = sorted(seq) > > L.sort() > > > > L.sort is still available in python, and sorted() have been available > > since python 2. Both list.sort() and sorted() are for different purpose, > > and neither will be deprecated. What's the change here? > > The document is about idioms as well as changes. In this case both > approaches work in both versions, but it seems that there are still a > lot of people who don't know about sorted(), so I put it in to show it > as an idiom. It would be quite nice if you could mark all the Python 3 idioms that work in Python 2.X as well. This would allow readers that are still using Python 2.X and are used to the 'old way' to adapt their coding style accordingly. You could just add a little (2.X) after the idiom for example. And thanks for the nice cheat sheet! :-D -- .''`. Wolodja Wentland : :' : `. `'` 4096R/CAF14EFC `- 081C B7CD FF04 2BA9 94EA 36B2 8B7F 7D30 CAF1 4EFC -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 836 bytes Desc: Digital signature URL: From martin.hellwig at dcuktec.org Wed Dec 2 06:31:07 2009 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Wed, 02 Dec 2009 11:31:07 +0000 Subject: Moving from Python 2 to Python 3: A 4 page "cheat sheet" In-Reply-To: <291d64cb-cc5c-4109-822c-84d58ed7b18b@k17g2000yqh.googlegroups.com> References: <291d64cb-cc5c-4109-822c-84d58ed7b18b@k17g2000yqh.googlegroups.com> Message-ID: Mark Summerfield wrote: > It is available as a free PDF download (no registration or anything) > from InformIT's website. Here's the direct link: > http://ptgmedia.pearsoncmg.com/imprint_downloads/informit/promotions/python/python2python3.pdf Very handy! Am I wrong in assuming that you forgot to include that file() is gone in favour of open()? -- MPH http://blog.dcuktec.com 'If consumed, best digested with added seasoning to own preference.' From victorsubervi at gmail.com Wed Dec 2 07:12:33 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Wed, 2 Dec 2009 07:12:33 -0500 Subject: Don't Understand This Error In-Reply-To: <4b16477b$0$13108$426a34cc@news.free.fr> References: <4dc0cfea0912020233r2b441b32t358dc5f2d19609d1@mail.gmail.com> <4b16477b$0$13108$426a34cc@news.free.fr> Message-ID: <4dc0cfea0912020412j389511a2ie08f56e29913d9b0@mail.gmail.com> To those who caught the colon at the end of what I thought was going to be def but turned out to be something else, thank. On Wed, Dec 2, 2009 at 5:55 AM, Bruno Desthuilliers wrote: > On Wed, Dec 2, 2009 at 2:33 AM, Victor Subervi >> wrote: >> >>> >>> def colors(callingTable, which='', specificTables=[]): >>> >> > Warning : default arguments are eval'd only once, at function creation > time. This is a well known gotcha that can lead to unexpected behaviours > like: > > > def foo(x, bar=[]) > bar.append("gotcha %s" % x) > print bar > > for i in range(5): > bar(i) > Thanks for this instructive example. V -------------- next part -------------- An HTML attachment was scrubbed... URL: From roy at panix.com Wed Dec 2 08:09:58 2009 From: roy at panix.com (Roy Smith) Date: Wed, 02 Dec 2009 08:09:58 -0500 Subject: Question on Python as career References: <614b8dde-324b-4d54-8e73-7a96e4c0b1cf@a21g2000yqc.googlegroups.com> Message-ID: joy99 wrote: > Dear Group, > > I am a researcher in India's one of the premier institutes.(Indian > Institute of Science,Bangalore). > [...] > I have developed them either in Python2.5 and Python2.6. > > After I complete my Post Doctoral which may be only 2-3 months away, > with this knowledge can I join IT? > Or Do I have to learn anything new? The short answer is, you will always need to keep learning new things. Whatever set of technologies are popular today (check out http://www.tiobe.com/index.php/content/paperinfo/tpci/index.html, for example), will change over time. When I started out, I knew C and Fortran. I'm amazed that C is still the #2 language, and Fortran isn't even on the TIOBE top 20 list any more. 17 of the 20 didn't even exist when I started out. From dochoncho at gmail.com Wed Dec 2 08:28:13 2009 From: dochoncho at gmail.com (Joel Madigan) Date: Wed, 2 Dec 2009 08:28:13 -0500 Subject: Recursion head scratcher In-Reply-To: <4B162BAE.4070306@ieee.org> References: <4B162BAE.4070306@ieee.org> Message-ID: On 12/2/09, Dave Angel wrote: > Joel Madigan wrote: >> Hi everyone! >> Sorry this isn't strictly a Python question but my algorithms professor >> contends that given the standard recursive-backtracking maze solving >> algorithm: >> >> width=6 >> height=4 >> maze=[[1,0,1,1,0,1], >> [0,0,1,0,0,0], >> [1,0,1,0,1,0], >> [0,0,0,0,1,1]] >> visited = [[False for x in range(width)] for y in range(height)] >> >> sx=1 >> sy=2 >> ex=4 >> ey=0 >> >> def findPath(x,y): >> if (x < 0 or x >= width or y < 0 or y >= height): >> return False >> elif maze[y][x] == 1: >> return False >> elif visited[y][x]: >> return False >> elif (x == ex and y == ey): >> print "(%d,%d)"%(x,y), >> return True >> else: >> visited[y][x] = True >> >> if findPath(x-1,y) or \ >> findPath(x+1,y) or \ >> findPath(x,y-1) or \ >> findPath(x,y+1): >> print "(%d,%d)"%(x,y), >> return True >> else: >> return False >> >> print findPath(sx,sy) >> >> that it is possible to make it print the path to the finish in the order >> the >> steps were taken. That is, the algorithm as written produces: >> (4,0) (4,1) (3,1) (3,2) (3,3) (2,3) (1,3) (1,2) True >> >> Rather than >> (1,2) (1,3) (2,3) (3,3) (3,2) (3,1) (4,1) (4,0) True >> >> Furthermore, he claims it's a "one line change" without using a stack or >> any >> other extra data structure. But I can't figure it out to save my life. >> This isn't homework, there isn't credit on the line. I think he said it >> just to mess with us. Can anyone point me in the right direction? It's >> driving me crazy. The output it gives makes perfect sense, since it just >> prints out each step as the stack unwinds. Normally you would print the >> output BEFORE recursing, but in this case you only want to print the step >> if >> it is actually part of the path. And you don't know that until after the >> recursion. >> >> Can anyone shed some light on this? >> >> Thanks, >> Joel >> >> > How about swapping sx,sy with ex,ey ? That's one line (one statement). > And the rest of the algorithm appears to be symmetric. Basically, > you're reversing time, and starting with the end point, descending till > you find the start point. > > DaveA > > Wow... that's devilishy clever. I can see that I still have a long way to travel on my path. Thanks for your insight. From dreadpiratejeff at gmail.com Wed Dec 2 09:14:26 2009 From: dreadpiratejeff at gmail.com (J) Date: Wed, 2 Dec 2009 09:14:26 -0500 Subject: Question about file objects... Message-ID: <36dec4ff0912020614o3263f649qccf28f50860ced8d@mail.gmail.com> Something that came up in class... when you are pulling data from a file using f.next(), the file is read one line at a time. What was explained to us is that Python iterates the file based on a carriage return as the delimiter. But what if you have a file that has one line of text, but that one line has 16,000 items that are comma delimited? Is there a way to read the file, one item at a time, delimited by commas WITHOUT having to read all 16,000 items from that one line, then split them out into a list or dictionary?? Cheers Jeff -- Ogden Nash - "The trouble with a kitten is that when it grows up, it's always a cat." - http://www.brainyquote.com/quotes/authors/o/ogden_nash.html From pruebauno at latinmail.com Wed Dec 2 09:27:28 2009 From: pruebauno at latinmail.com (nn) Date: Wed, 2 Dec 2009 06:27:28 -0800 (PST) Subject: Question about file objects... References: Message-ID: <01fd9f0b-aa15-41c8-86ac-1d719d87999a@m35g2000vbi.googlegroups.com> On Dec 2, 9:14?am, J wrote: > Something that came up in class... > > when you are pulling data from a file using f.next(), the file is read > one line at a time. > > What was explained to us is that Python iterates the file based on a > carriage return as the delimiter. > But what if you have a file that has one line of text, but that one > line has 16,000 items that are comma delimited? > > Is there a way to read the file, one item at a time, delimited by > commas WITHOUT having to read all 16,000 items from that one line, > then split them out into a list or dictionary?? > > Cheers > Jeff > > -- > > Ogden Nash ?- "The trouble with a kitten is that when it grows up, > it's always a cat." -http://www.brainyquote.com/quotes/authors/o/ogden_nash.html File iteration is a convenience since it is the most common case. If everything is on one line, you will have to handle record separators manually by using the .read() method on the file object and searching for the comma. If everything fits in memory the straightforward way would be to read the whole file with .read() and use .split(",") on the returned string. That should give you a nice list of everything. From drobinow at gmail.com Wed Dec 2 09:28:06 2009 From: drobinow at gmail.com (David Robinow) Date: Wed, 2 Dec 2009 09:28:06 -0500 Subject: Delaunay triangulation In-Reply-To: <77e831100912011731n53269c60r2a582d77a43a4eda@mail.gmail.com> References: <77e831100912011731n53269c60r2a582d77a43a4eda@mail.gmail.com> Message-ID: <4eb0089f0912020628x1fd99258s20a88571051bcf75@mail.gmail.com> On Tue, Dec 1, 2009 at 8:31 PM, Vincent Davis wrote: > Anyone know of a python implementation of?Delaunay triangulation? Matplotlib has one. There's also Delny @pypi It's been several years since I needed this. I can't remember the pros/cons. From irounakjain at gmail.com Wed Dec 2 09:32:23 2009 From: irounakjain at gmail.com (Rounak) Date: Wed, 02 Dec 2009 20:02:23 +0530 Subject: can python do this? Message-ID: <1259764343.2086.0.camel@ubuntu> I am a complete newbie. I want to know if the following can be done using python or should I learn some other language: (Basically, these are applescripts that I wrote while I used Mac OS) 1.Web Page Image to Wallpaper: A script that takes the current image in a browser and sets it as a wallpaper. http://forums.obdev.at/viewtopic.php?f=24&t=3462 2.Screenshot with name, format, Dropbox upload and public URL I used to run this script,type the name for screenshot and press return. The screenshot would be uploaded to Dropbox and public url would be copied to clipboard. http://forums.obdev.at/viewtopic.php?f=24&t=3448 3.Play, pause, set rating to track in iTunes (a music player) with keyboard shortcuts without activating iTunes. I know there is no iTunes for Linux but is there a scriptable player. See hundreds of scripts for iTunes here: http://dougscripts.com/ Thanks. I am a complete newbie. I want to know if the following can be done using python or should I learn some other language: (Basically, these are applescripts that I wrote while I used Mac OS) 1.Web Page Image to Wallpaper: A script that takes the current image in a browser and sets it as a wallpaper. http://forums.obdev.at/viewtopic.php?f=24&t=3462 2.Screenshot with name, format, Dropbox upload and public URL I used to run this script,type the name for screenshot and press return. The screenshot would be uploaded to Dropbox and public url would be copied to clipboard. http://forums.obdev.at/viewtopic.php?f=24&t=3448 3.Play, pause, set rating to track in iTunes (a music player) with keyboard shortcuts without activating iTunes. I know there is no iTunes for Linux but is there a scriptable player. See hundreds of scripts for iTunes here: http://dougscripts.com/ Thanks. From andreengels at gmail.com Wed Dec 2 09:33:40 2009 From: andreengels at gmail.com (Andre Engels) Date: Wed, 2 Dec 2009 15:33:40 +0100 Subject: Question about file objects... In-Reply-To: <36dec4ff0912020614o3263f649qccf28f50860ced8d@mail.gmail.com> References: <36dec4ff0912020614o3263f649qccf28f50860ced8d@mail.gmail.com> Message-ID: <6faf39c90912020633l23e7ad08ue101b5a1876bdab3@mail.gmail.com> On Wed, Dec 2, 2009 at 3:14 PM, J wrote: > Something that came up in class... > > when you are pulling data from a file using f.next(), the file is read > one line at a time. > > What was explained to us is that Python iterates the file based on a > carriage return as the delimiter. > But what if you have a file that has one line of text, but that one > line has 16,000 items that are comma delimited? > > Is there a way to read the file, one item at a time, delimited by > commas WITHOUT having to read all 16,000 items from that one line, > then split them out into a list or dictionary?? If f is a file object, f.read(1) will get the next byte of the file. Get single-character strings that way until you arrive at a ",", then concatenate what you have received before that. -- Andr? Engels, andreengels at gmail.com From aoifed88 at hotmail.com Wed Dec 2 09:34:47 2009 From: aoifed88 at hotmail.com (aoife) Date: Wed, 2 Dec 2009 06:34:47 -0800 (PST) Subject: pbs scripts Message-ID: Hi,very new.hoping to incorporate python into my postgrad. Basically I have 2,000 files.I want to write a script that says: open each file in turn for each file: open this pbs script and run MUSCLE (a sequence alignment tool) on each file close this file move on to next file. any help would be great. Aoife From srikrishnamohan at gmail.com Wed Dec 2 09:37:57 2009 From: srikrishnamohan at gmail.com (km) Date: Wed, 2 Dec 2009 23:37:57 +0900 Subject: Delaunay triangulation In-Reply-To: <4eb0089f0912020628x1fd99258s20a88571051bcf75@mail.gmail.com> References: <77e831100912011731n53269c60r2a582d77a43a4eda@mail.gmail.com> <4eb0089f0912020628x1fd99258s20a88571051bcf75@mail.gmail.com> Message-ID: check CGAL (cgal.org) it has python bindings Krishna On Wed, Dec 2, 2009 at 11:28 PM, David Robinow wrote: > On Tue, Dec 1, 2009 at 8:31 PM, Vincent Davis > wrote: > > Anyone know of a python implementation of Delaunay triangulation? > > Matplotlib has one. > There's also Delny @pypi > > It's been several years since I needed this. I can't remember the > pros/cons. > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From sturlamolden at yahoo.no Wed Dec 2 09:42:58 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Wed, 2 Dec 2009 06:42:58 -0800 (PST) Subject: xmlrpc idea for getting around the GIL References: <6214d7a20911221338l30296032y32d2d1215de57b6d@mail.gmail.com> <83303a84-a8ca-486a-8173-ef0892779f39@x16g2000vbk.googlegroups.com> <4b0b07a1$0$22159$9b622d9e@news.freenet.de> Message-ID: On 2 Des, 02:47, Patrick Stinson wrote: > We don't need extension modules, and all we need to do is run some > fairly basic scripts that make callbacks and use some sip-wrapped > types. Sure, you use SIP but not extension modules... > - Python is not suitable for real-time work. > > Not true. We have been running python callback code using > PyObject_CallObject from within our audio thread for some time without > a problem, and it's *extremely* fast. It seems you are confusing "real-time" with "real-fast". The fact that something runs fast does not make it "real-time". Python is not suitable for real-time applications, nor are the OSes commonly used to run Python. > We > need just a liiiitle push to get our code to work at low latencies, > and the only thing that is standing in our way is that all threads > 9usually around 20 have to block on the Gil, and this causes small > gaps in the sound at low latencies (around 5ms, or 64 sample period). > > ...almost perfect. Python is not programmed with real-time applications in mind: You have no guarrantees on maximum time-lag when a thread is blocked on the GIL. "Priority requests" (i.e. pre-emptive multitasking) was removed from Antoine's "newgil" branch, but that is the kind of mechanism you would need. Even with priority requests, Python would not be suitable for real-time apps, as extension modules (e.g. C++ wrapped with SIP) can hold the GIL forever. You will also need an OS with a real-time scheduler and a real-time C library, such as QNX or VxWorks. I find thea idea of a true real-time Python very interesting, but it would take a completely reworked interpreter. From deets at nospam.web.de Wed Dec 2 09:51:45 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 02 Dec 2009 15:51:45 +0100 Subject: can python do this? References: Message-ID: <7nnd81F3ljsp0U1@mid.uni-berlin.de> Rounak wrote: > I am a complete newbie. I want to know if the following can be done > using python or should I learn some other language: > (Basically, these are applescripts that I wrote while I used Mac OS) > 1.Web Page Image to Wallpaper: > A script that takes the current image in a browser and sets it as a > wallpaper. > http://forums.obdev.at/viewtopic.php?f=24&t=3462 > > 2.Screenshot with name, format, Dropbox upload and public URL > I used to run this script,type the name for screenshot and press return. > The screenshot would be uploaded to Dropbox and public url would be > copied to clipboard. > http://forums.obdev.at/viewtopic.php?f=24&t=3448 > > 3.Play, pause, set rating to track in iTunes (a music player) with > keyboard shortcuts without activating iTunes. I know there is no iTunes > for Linux but is there a scriptable player. See hundreds of scripts > for iTunes here: http://dougscripts.com/ As python has an apple-script binding, yes, it's possible, should even be a rather smooth transition. Diez From simon at brunningonline.net Wed Dec 2 09:52:57 2009 From: simon at brunningonline.net (Simon Brunning) Date: Wed, 2 Dec 2009 14:52:57 +0000 Subject: can python do this? In-Reply-To: <1259764343.2086.0.camel@ubuntu> References: <1259764343.2086.0.camel@ubuntu> Message-ID: <8c7f10c60912020652v4ca91fb3k218629548ae81d6f@mail.gmail.com> 2009/12/2 Rounak : > I am a complete newbie. I want to know if the following can be done > using python or should I learn some other language: > (Basically, these are applescripts that I wrote while I used Mac OS) Python can do anything Applescript can do with the appscript module - see . And, naturally, very much more. I have some driving iTunes examples I'd be happy to send you off-list if you're interested. -- Cheers, Simon B. From simon at brunningonline.net Wed Dec 2 09:59:05 2009 From: simon at brunningonline.net (Simon Brunning) Date: Wed, 2 Dec 2009 14:59:05 +0000 Subject: pbs scripts In-Reply-To: References: Message-ID: <8c7f10c60912020659y1252a40l552e2409bc92a6a5@mail.gmail.com> 2009/12/2 aoife : > Hi,very new.hoping to incorporate python into my postgrad. > > Basically I have 2,000 files.I want to write a script that says: > > open each file in turn If they are in one directory, look at the glob module. If they are in a bunch of sub-directories, see os.walk(), or . For looping through the files, see . > for each file: > ? ? ? open this pbs script and run MUSCLE (a sequence alignment tool) > on each file Is MUSCLE a command-line tool? If so, see the subprocess module. > ? ? ? close this file Do you actually need to open the file, or just run a command on it? Sounds like the latter to me. > ? ? ? move on to next file. Give it a go. Any problems, I'm sure we'd be happy to help. -- Cheers, Simon B. From irounakjain at gmail.com Wed Dec 2 10:00:10 2009 From: irounakjain at gmail.com (Rounak) Date: Wed, 02 Dec 2009 20:30:10 +0530 Subject: can python do this? In-Reply-To: <8c7f10c60912020652v4ca91fb3k218629548ae81d6f@mail.gmail.com> References: <1259764343.2086.0.camel@ubuntu> <8c7f10c60912020652v4ca91fb3k218629548ae81d6f@mail.gmail.com> Message-ID: <1259766010.2422.1.camel@ubuntu> > Python can do anything Applescript can do with the appscript module - > see . And, > naturally, very much more. wait, sorry, i forgot to mention. I am now on Linux. I want to know what python can do in Linux. On Mac, I am glad to use applescript. From deets at nospam.web.de Wed Dec 2 10:17:37 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 02 Dec 2009 16:17:37 +0100 Subject: can python do this? References: <1259764343.2086.0.camel@ubuntu> <8c7f10c60912020652v4ca91fb3k218629548ae81d6f@mail.gmail.com> Message-ID: <7nneohF3jh7ppU1@mid.uni-berlin.de> Rounak wrote: > >> Python can do anything Applescript can do with the appscript module - >> see . And, >> naturally, very much more. > > wait, sorry, i forgot to mention. I am now on Linux. I want to know what > python can do in Linux. On Mac, I am glad to use applescript. This question is not so easy to answer. Because such functionality heavily depends on your actual desktop environment - KDE, Gnome, or something entirely different. However, I'd say that using python you have a good chance of exploiting the services that are actually available to you. For example, taking a screenshot: http://stackoverflow.com/questions/69645/take-a-screenshot-via-a-python-script-linux Uploading that to dropbox is simple python urllib stuff. And there seem to be ways to insert things into the clipboard as well: http://arminstraub.com/bits-and-bytes/kde-clipboard-on-the-command-line Diez From invalid at invalid.invalid Wed Dec 2 10:33:51 2009 From: invalid at invalid.invalid (Grant Edwards) Date: Wed, 2 Dec 2009 15:33:51 +0000 (UTC) Subject: can python do this? References: <1259764343.2086.0.camel@ubuntu> <8c7f10c60912020652v4ca91fb3k218629548ae81d6f@mail.gmail.com> Message-ID: On 2009-12-02, Rounak wrote: > >> Python can do anything Applescript can do with the appscript module - >> see . And, >> naturally, very much more. > > wait, sorry, i forgot to mention. I am now on Linux. I want to > know what python can do in Linux. Python can do pretty much anything except kernel modules. -- Grant Edwards grante Yow! I want you to MEMORIZE at the collected poems of visi.com EDNA ST VINCENT MILLAY ... BACKWARDS!! From irounakjain at gmail.com Wed Dec 2 10:34:35 2009 From: irounakjain at gmail.com (Rounak) Date: Wed, 02 Dec 2009 21:04:35 +0530 Subject: can python do this? In-Reply-To: <7nneohF3jh7ppU1@mid.uni-berlin.de> References: <1259764343.2086.0.camel@ubuntu> <8c7f10c60912020652v4ca91fb3k218629548ae81d6f@mail.gmail.com> <7nneohF3jh7ppU1@mid.uni-berlin.de> Message-ID: <1259768075.2832.1.camel@ubuntu> > > http://stackoverflow.com/questions/69645/take-a-screenshot-via-a-python-script-linux > the first solution in this thread requires python imaging library which I did find here: http://www.pythonware.com/products/pil/faq.htm But i would like to know if there are easier ways to install this instead of compiling it from the source. From alley at dragoncreativeworks.net Wed Dec 2 10:38:49 2009 From: alley at dragoncreativeworks.net (Allan Davis) Date: Wed, 2 Dec 2009 09:38:49 -0600 Subject: can python do this? In-Reply-To: <1259768075.2832.1.camel@ubuntu> References: <1259764343.2086.0.camel@ubuntu> <8c7f10c60912020652v4ca91fb3k218629548ae81d6f@mail.gmail.com> <7nneohF3jh7ppU1@mid.uni-berlin.de> <1259768075.2832.1.camel@ubuntu> Message-ID: <61c507640912020738l68524f37h9232766c3596eb91@mail.gmail.com> Try your distribution of linux package management tool. You will find PIL there -------------------------------------------------------------- Allan Davis Member of NetBeans Dream Team http://wiki.netbeans.org/NetBeansDreamTeam Lead Developer, nbPython http://wiki.netbeans.org/Python http://codesnakes.blogspot.com (my blog) Co-Chair, CajunJUG http://www.cajunjug.org On Wed, Dec 2, 2009 at 9:34 AM, Rounak wrote: > > > > > > http://stackoverflow.com/questions/69645/take-a-screenshot-via-a-python-script-linux > > > the first solution in this thread requires python imaging library which > I did find here: http://www.pythonware.com/products/pil/faq.htm > But i would like to know if there are easier ways to install this > instead of compiling it from the source. > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From deets at nospam.web.de Wed Dec 2 10:40:16 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 02 Dec 2009 16:40:16 +0100 Subject: can python do this? References: <1259764343.2086.0.camel@ubuntu> <8c7f10c60912020652v4ca91fb3k218629548ae81d6f@mail.gmail.com> <7nneohF3jh7ppU1@mid.uni-berlin.de> Message-ID: <7nng30F3ldiilU1@mid.uni-berlin.de> Rounak wrote: > >> >> http://stackoverflow.com/questions/69645/take-a-screenshot-via-a-python-script-linux >> > the first solution in this thread requires python imaging library which > I did find here: http://www.pythonware.com/products/pil/faq.htm > But i would like to know if there are easier ways to install this > instead of compiling it from the source. Did you bother checking your distributions package management? Diez From bruno.42.desthuilliers at websiteburo.invalid Wed Dec 2 10:43:02 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 02 Dec 2009 16:43:02 +0100 Subject: can python do this? In-Reply-To: References: <1259764343.2086.0.camel@ubuntu> <8c7f10c60912020652v4ca91fb3k218629548ae81d6f@mail.gmail.com> <7nneohF3jh7ppU1@mid.uni-berlin.de> Message-ID: <4b168afa$0$32342$426a74cc@news.free.fr> Rounak a ?crit : >> >> http://stackoverflow.com/questions/69645/take-a-screenshot-via-a-python-script-linux >> > the first solution in this thread requires python imaging library which > I did find here: http://www.pythonware.com/products/pil/faq.htm > But i would like to know if there are easier ways to install this > instead of compiling it from the source. > Depends on your linux distro - but PIL is a fairly stable and widely used lib, so I fail to imagine any modern distro not having a packaged PIL install (rpm, ebuild, whatever). From eric.frederich at gmail.com Wed Dec 2 10:53:32 2009 From: eric.frederich at gmail.com (eric.frederich) Date: Wed, 2 Dec 2009 07:53:32 -0800 (PST) Subject: Python without wrapper script Message-ID: Is there a way to set up environment variables in python itself without having a wrapper script. The wrapper script is now something like.... #!/bin/bash export LD_LIBRARY_PATH="/some/thing/lib:$LD_LIBRARY_PATH" export LD_LIBRARY_PATH="/another/thing/lib:$LD_LIBRARY_PATH" export PATH="/some/thing/bin:$PATH" export PATH="/another/thing/bin:$PATH" python ./someScript.py From irounakjain at gmail.com Wed Dec 2 10:53:56 2009 From: irounakjain at gmail.com (Rounak) Date: Wed, 02 Dec 2009 21:23:56 +0530 Subject: can python do this? In-Reply-To: <61c507640912020738l68524f37h9232766c3596eb91@mail.gmail.com> References: <1259764343.2086.0.camel@ubuntu> <8c7f10c60912020652v4ca91fb3k218629548ae81d6f@mail.gmail.com> <7nneohF3jh7ppU1@mid.uni-berlin.de> <1259768075.2832.1.camel@ubuntu> <61c507640912020738l68524f37h9232766c3596eb91@mail.gmail.com> Message-ID: <1259769236.2048.3.camel@ubuntu> Thanks Allan, I did find PIL in Synaptic Package Manager and installed it successfully. However, I cannot use it. The reason is: 1. I had installed python3 using sudo apt-get install python3 but python 2 still remains. And it seems Scite (my python editor) is looking for python 2. Terminal Output: $ python -V Python 2.6.4 $ python3 -V Python 3.1.1+ Output from Scite: >python -u "sshot.py" Traceback (most recent call last): File "sshot.py", line 1, in import ImageGrab File "/usr/lib/python2.6/dist-packages/PIL/ImageGrab.py", line 34, in import _grabscreen ImportError: No module named _grabscreen >Exit code: 1 How to make Scite use python3 where it will hopefully find the just installed PIL. From list at qtrac.plus.com Wed Dec 2 10:55:23 2009 From: list at qtrac.plus.com (Mark Summerfield) Date: Wed, 2 Dec 2009 07:55:23 -0800 (PST) Subject: Moving from Python 2 to Python 3: A 4 page "cheat sheet" References: <291d64cb-cc5c-4109-822c-84d58ed7b18b@k17g2000yqh.googlegroups.com> Message-ID: <351fcb4c-4e88-41b0-a0aa-b3d63832d1aa@e23g2000yqd.googlegroups.com> On Dec 1, 2:03?pm, Mark Summerfield wrote: > I've produced a 4 page document that provides a very concise summary > of Python 2<->3 differences plus the most commonly used new Python 3 > features. It is aimed at existing Python 2 programmers who want to > start writing Python 3 programs and want to use Python 3 idioms rather > than those from Python 2 where the idioms differ. > > It uses Python 3.1 syntax since that looks like being the standard for > a few years in view of the language moratorium. > > The document is U.S. Letter size but will also print fine on A4 > printers. > > It is available as a free PDF download (no registration or anything) > from InformIT's website. Here's the direct link:http://ptgmedia.pearsoncmg.com/imprint_downloads/informit/promotions/... > > And of course, if you want more on Python 3, there's always the > documentation---or my book:-) > "Programming in Python 3 (Second Edition)" ISBN-10: 0321680561. I only just found out that I was supposed to give a different URL: http://www.informit.com/promotions/promotion.aspx?promo=137519 This leads to a web page where you can download the document (just by clicking the "Download Now" button), but if you _choose_ you can also enter your name and email to win some sort of prize. From list at qtrac.plus.com Wed Dec 2 10:57:23 2009 From: list at qtrac.plus.com (Mark Summerfield) Date: Wed, 2 Dec 2009 07:57:23 -0800 (PST) Subject: Moving from Python 2 to Python 3: A 4 page "cheat sheet" References: <291d64cb-cc5c-4109-822c-84d58ed7b18b@k17g2000yqh.googlegroups.com> <19194586-cd6a-4d13-ae1c-798884194672@n35g2000yqm.googlegroups.com> Message-ID: <4d82209c-1a43-405e-8ba7-49b7d7985335@n35g2000yqm.googlegroups.com> On Dec 2, 8:53?am, Mark Dickinson wrote: > On Dec 2, 8:01?am, MarkSummerfield wrote: > > > On 1 Dec, 17:50, Mark Dickinson wrote: > > > My only quibble is with the statement on the first page that > > > the 'String % operator is deprecated'. ?I'm not sure that's > > > true, for all values of 'deprecated'. ?There don't appear > > > to be any definite plans for getting rid of it just yet. > > > I didn't make this up:-) > > No, I didn't imagine for a second that you had! > > > According tohttp://docs.python.org/dev/3.0/whatsnew/3.0.html > > "The plan is to eventually make this the only API for string > > formatting, and to start deprecating the % operator in Python 3.1." > > I think that's a doc bug. ?"The plan is to ..." should read: "The plan > was > originally to ...". ?(Well, at least in the 3.1 version of the > "what's new in 3.0" documentation; ?the 3.0 version that you linked to > isn't even autogenerated any more, AFAIK, so fixes to the ReST source > for that file never make it to the web site.) > > I'm a little confused myself about what's actually happening with > % formatting, but here's a fairly recent python-dev posting from > the BDFL: > > http://mail.python.org/pipermail/python-dev/2009-September/092399.html Well it seems clear to me that the BDFL wants to kill of % formatting, but wasn't able to for Python 3... So I still think it is reasonable (1) to describe it as deprecated and (2) to only teach and use str.format(). From list at qtrac.plus.com Wed Dec 2 11:03:27 2009 From: list at qtrac.plus.com (Mark Summerfield) Date: Wed, 2 Dec 2009 08:03:27 -0800 (PST) Subject: Moving from Python 2 to Python 3: A 4 page "cheat sheet" References: <291d64cb-cc5c-4109-822c-84d58ed7b18b@k17g2000yqh.googlegroups.com> <4b156121$1@dnews.tpgi.com.au> <3851f624-f2cd-40fb-a898-cfd08d5cf0fa@e7g2000vbi.googlegroups.com> Message-ID: <9eb46f34-a9aa-46ef-98d4-1dbee0e409c0@m3g2000yqf.googlegroups.com> On Dec 2, 11:20?am, Wolodja Wentland wrote: > On Wed, Dec 02, 2009 at 00:10 -0800, Mark Summerfield wrote: > > On 1 Dec, 18:30, Lie Ryan wrote: > > > Also, I'm not sure what this change is referring to: > > > Python 2 ? ? ? ? ? ? ? ? Python 3 > > > L = list(seq) ? ? ? ? ? ?L = sorted(seq) > > > L.sort() > > > > L.sort is still available in python, and sorted() have been available > > > since python 2. Both list.sort() and sorted() are for different purpose, > > > and neither will be deprecated. What's the change here? > > > The document is about idioms as well as changes. In this case both > > approaches work in both versions, but it seems that there are still a > > lot of people who don't know about sorted(), so I put it in to show it > > as an idiom. > > It would be quite nice if you could mark all the Python 3 idioms that > work in Python 2.X as well. This would allow readers that are still using > Python 2.X and are used to the 'old way' to adapt their coding style > accordingly. You could just add a little (2.X) after the idiom for > example. Yes it would be nice, but it isn't quite so simple. To take sorted() as just one example, it was introduced in 2.4 so arguably using it isn't valid/idiomatic for Python 2.x programs where you care about backwards compatibility for the Python 2.x series... But my main reason for not wanting to do this is that the document is aimed at people who want to write Python 3, not to encourage people to stick with 2:-) > > And thanks for the nice cheat sheet! :-D Thanks! > -- > ? .''`. ? ? Wolodja Wentland ? ? > ?: :' ?: ? ? > ?`. `'` ? ? 4096R/CAF14EFC > ? ?`- ? ? ? 081C B7CD FF04 2BA9 94EA ?36B2 8B7F 7D30 CAF1 4EFC > > ?signature.asc > < 1KViewDownload From dreadpiratejeff at gmail.com Wed Dec 2 11:11:27 2009 From: dreadpiratejeff at gmail.com (J) Date: Wed, 2 Dec 2009 11:11:27 -0500 Subject: Question about file objects... In-Reply-To: <01fd9f0b-aa15-41c8-86ac-1d719d87999a@m35g2000vbi.googlegroups.com> References: <01fd9f0b-aa15-41c8-86ac-1d719d87999a@m35g2000vbi.googlegroups.com> Message-ID: <36dec4ff0912020811w32be2430rd6692de96ffd2671@mail.gmail.com> On Wed, Dec 2, 2009 at 09:27, nn wrote: >> Is there a way to read the file, one item at a time, delimited by >> commas WITHOUT having to read all 16,000 items from that one line, >> then split them out into a list or dictionary?? > File iteration is a convenience since it is the most common case. If > everything is on one line, you will have to handle record separators > manually by using the .read() method on the file > object and searching for the comma. If everything fits in memory the > straightforward way would be to read the whole file with .read() and > use .split(",") on the returned string. That should give you a nice > list of everything. Agreed. The confusion came because the guy teaching said that iterating the file is delimited by a carriage return character... which to me sounds like it's an arbitrary thing that can be changed... I was already thinking that I'd have to read it in small chunks and search for the delimiter i want... and reading the whole file into a string and then splitting that would would be nice, until the file is so large that it starts taking up significant amounts of memory. Anyway, thanks both of you for the explanations... I appreciate the help! Cheers Jeff -- Charles de Gaulle - "The better I get to know men, the more I find myself loving dogs." - http://www.brainyquote.com/quotes/authors/c/charles_de_gaulle.html From eckhardt at satorlaser.com Wed Dec 2 11:12:34 2009 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Wed, 02 Dec 2009 17:12:34 +0100 Subject: Python without wrapper script References: Message-ID: eric.frederich wrote: > Is there a way to set up environment variables in python itself > without having a wrapper script. Yes, sure, you can set environment variables... > The wrapper script is now something like.... > > #!/bin/bash > > export LD_LIBRARY_PATH="/some/thing/lib:$LD_LIBRARY_PATH" > export LD_LIBRARY_PATH="/another/thing/lib:$LD_LIBRARY_PATH" > > export PATH="/some/thing/bin:$PATH" > export PATH="/another/thing/bin:$PATH" > > python ./someScript.py ...but this won't work, I'm afraid. LD_LIBRARY_PATH is for the program loader / dynamic linker under Linux. This thing is what is invoked _before_ the program is started, any later modifications to the environment are ignored. Similarly PATH, which tells the shell (e.g. bash) where to find executables. If you need that to e.g. find 'python' itself, you're out of luck. Otherwise, I believe Python itself doesn't use PATH, so you could set it inside and any shells started from Python should pick it up. Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From list at qtrac.plus.com Wed Dec 2 11:22:59 2009 From: list at qtrac.plus.com (Mark Summerfield) Date: Wed, 2 Dec 2009 08:22:59 -0800 (PST) Subject: Moving from Python 2 to Python 3: A 4 page "cheat sheet" References: <291d64cb-cc5c-4109-822c-84d58ed7b18b@k17g2000yqh.googlegroups.com> Message-ID: On Dec 2, 11:31?am, "Martin P. Hellwig" wrote: > MarkSummerfieldwrote: > > > It is available as a free PDF download (no registration or anything) > > from InformIT's website. Here's the direct link: > >http://ptgmedia.pearsoncmg.com/imprint_downloads/informit/promotions/... > > > Very handy! Am I wrong in assuming that you forgot to include that > file() is gone in favour of open()? No you are not wrong in assuming that I forgot that:-( My lame excuse is that file() was introduced for isinstance() testing and similar, and never really as a replacement for open(). Anyway, I have now added: fh = file(fname, mode) | fh = open(fname, mode) I've sent a new PDF with this change to InformIT, so hopefully it'll become available soon from http://www.informit.com/promotions/promotion.aspx?promo=13751 From list at qtrac.plus.com Wed Dec 2 11:27:42 2009 From: list at qtrac.plus.com (Mark Summerfield) Date: Wed, 2 Dec 2009 08:27:42 -0800 (PST) Subject: Moving from Python 2 to Python 3: A 4 page "cheat sheet" References: <291d64cb-cc5c-4109-822c-84d58ed7b18b@k17g2000yqh.googlegroups.com> Message-ID: <1a1376a0-a661-44d4-878a-6d1ad64da49a@s20g2000yqd.googlegroups.com> On Dec 2, 4:22?pm, Mark Summerfield wrote: > On Dec 2, 11:31?am, "Martin P. Hellwig" > wrote: > > > MarkSummerfieldwrote: > > > > It is available as a free PDF download (no registration or anything) > > > from InformIT's website. Here's the direct link: > > >http://ptgmedia.pearsoncmg.com/imprint_downloads/informit/promotions/... > > > > > Very handy! Am I wrong in assuming that you forgot to include that > > file() is gone in favour of open()? > > No you are not wrong in assuming that I forgot that:-( > > My lame excuse is that file() was introduced for isinstance() testing > and similar, and never really as a replacement for open(). > > Anyway, I have now added: > > ? ? fh = file(fname, mode) | fh = open(fname, mode) > > I've sent a new PDF with this change to InformIT, so hopefully it'll > become available soon fromhttp://www.informit.com/promotions/promotion.aspx?promo=13751 Oops wrong URL again, should have been: http://www.informit.com/promotions/promotion.aspx?promo=137519 ... time to go offline and sleep ... From jeanmichel at sequans.com Wed Dec 2 11:31:04 2009 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Wed, 02 Dec 2009 17:31:04 +0100 Subject: Python without wrapper script In-Reply-To: References: Message-ID: <4B169648.6010100@sequans.com> eric.frederich wrote: > Is there a way to set up environment variables in python itself > without having a wrapper script. > > The wrapper script is now something like.... > > #!/bin/bash > > export LD_LIBRARY_PATH="/some/thing/lib:$LD_LIBRARY_PATH" > export LD_LIBRARY_PATH="/another/thing/lib:$LD_LIBRARY_PATH" > > export PATH="/some/thing/bin:$PATH" > export PATH="/another/thing/bin:$PATH" > > python ./someScript.py > try in someScript.py os.environ['PATH'] = "/some/thing/bin:"+ os.environ['PATH'] example: import subprocess import os p = subprocess.Popen('/bin/echo $TEST', shell=True, stdout=subprocess.PIPE ) p.communicate()[0] > '\n' os.environ['TEST'] = 'hello' p = subprocess.Popen('/bin/echo $TEST', shell=True, stdout=subprocess.PIPE ) p.communicate()[0] > 'hello\n' JM From jjposner at optimum.net Wed Dec 2 11:41:32 2009 From: jjposner at optimum.net (John Posner) Date: Wed, 02 Dec 2009 11:41:32 -0500 Subject: Moving from Python 2 to Python 3: A 4 page "cheat sheet" References: <291d64cb-cc5c-4109-822c-84d58ed7b18b@k17g2000yqh.googlegroups.com> <351fcb4c-4e88-41b0-a0aa-b3d63832d1aa@e23g2000yqd.googlegroups.com> Message-ID: On Wed, 02 Dec 2009 10:55:23 -0500, Mark Summerfield wrote: > On Dec 1, 2:03 pm, Mark Summerfield wrote: >> I've produced a 4 page document that provides a very concise summary >> of Python 2<->3 differences plus the most commonly used new Python 3 >> features. It is aimed at existing Python 2 programmers who want to >> start writing Python 3 programs and want to use Python 3 idioms rather >> than those from Python 2 where the idioms differ. Mark, I add my thanks to those of the other responders. If you find space, you might consider adding another str.format() feature: Goal: place integer 456 flush-right in a field of width 8 Py2: "%%%dd" % 8 % 456 Py3: "{0:{1}d}".format(456, 8) With str.format(), you don't need to nest one formatting operation within another. A little less mind-bending, and every little bit helps! -John From sturlamolden at yahoo.no Wed Dec 2 12:20:08 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Wed, 2 Dec 2009 09:20:08 -0800 (PST) Subject: Delaunay triangulation References: <77e831100912011731n53269c60r2a582d77a43a4eda@mail.gmail.com> Message-ID: On 2 Des, 15:28, David Robinow wrote: > On Tue, Dec 1, 2009 at 8:31 PM, Vincent Davis wrote: > > Anyone know of a python implementation of?Delaunay triangulation? > > Matplotlib has one. > There's also Delny ?@pypi > > It's been several years since I needed this. I can't remember the pros/cons. There is also a skikit add-on to NumPy/SciPy. http://scikits.appspot.com/delaunay From DarthXander at hotmail.co.uk Wed Dec 2 12:50:31 2009 From: DarthXander at hotmail.co.uk (DarthXander) Date: Wed, 2 Dec 2009 09:50:31 -0800 (PST) Subject: Coding Cross Correlation Function in Python Message-ID: <3a2b623e-e5a0-4935-97a4-cad384745525@c3g2000yqd.googlegroups.com> I have two data sets which I wish to perform the discrete correlation function on and then plot the results for many values of t to see what if any time lag exists between the data. Thus far my code is; import csv import pylab from pylab import * from numpy import * from numpy import array HSBC=csv.reader(open("HSBC data.csv")) Barclays=csv.reader(open("Barclays data.csv")) x=[] a=[] y=[] b=[] g=[] h=[] d=[] for Date, Close in HSBC: x.append(Date) a.append(float(Close)) for Date, Close in Barclays: y.append(Date) b.append(float(Close)) for index in range(len(a)): g.append(a[index]-mean(a)) for index in range(len(b)): h.append(b[index]-mean(b)) r=std(a) s=std(b) So I have all the necessary components for the DCF. However I'm not faced with the challenge of performing the DCF for t in the range of potentially 0-700 or so. Currently I could do it individually for each value of tau ie; t1=[] for index in range(len(g)-1): j=(g[index]*h[index+1])/(r*s) t1.append(j) d.append(mean(t1)) However to do this 700 times seems ridiculous. How would I get python to perform this for me for t in a range of roughly 0-700? Thanks Alex From as at sci.fi Wed Dec 2 12:55:16 2009 From: as at sci.fi (Anssi Saari) Date: Wed, 02 Dec 2009 19:55:16 +0200 Subject: can python do this? References: Message-ID: Rounak writes: > I am a complete newbie. I want to know if the following can be done > using python or should I learn some other language: > (Basically, these are applescripts that I wrote while I used Mac OS) > 1.Web Page Image to Wallpaper: > A script that takes the current image in a browser and sets it as a > wallpaper. > http://forums.obdev.at/viewtopic.php?f=24&t=3462 I don't know if any Linux web browsers are particularly scriptable. Firefox at least is pretty much limited to opening URLs and some other windows. OTOH, you can do that specific thing by just right clicking on the image in question and selecting set as desktop background... > 2.Screenshot with name, format, Dropbox upload and public URL > I used to run this script,type the name for screenshot and press return. > The screenshot would be uploaded to Dropbox and public url would be > copied to clipboard. > http://forums.obdev.at/viewtopic.php?f=24&t=3448 I think this should be easily doable with Python, at least the screenshot and clipboard parts. You can write your own Python code or use it as glue for utils like xwd, convert, xsel, xclip, xmessage... No idea if there's any way to talk to Dropbox from Python again since I know nothing about it. > 3.Play, pause, set rating to track in iTunes (a music player) with > keyboard shortcuts without activating iTunes. I know there is no iTunes > for Linux but is there a scriptable player. See hundreds of scripts > for iTunes here: http://dougscripts.com/ Don't really know again, I've found iTunes handy for managing podcasts, but that use doesn't need scripting. In Linux, at least Amarok is scriptable via Javascript. mplayer is generally scriptable in its slave mode, but it's more a video player than music. mpd is a music server which even has a Python client to control it (Sonata). But really, global hot key mapping is more of a windowing system thing than a scripting thing. I'm sure you can map your keys to do anything you want, in whatever environment you use in Linux. From dickinsm at gmail.com Wed Dec 2 13:32:56 2009 From: dickinsm at gmail.com (Mark Dickinson) Date: Wed, 2 Dec 2009 10:32:56 -0800 (PST) Subject: Moving from Python 2 to Python 3: A 4 page "cheat sheet" References: <291d64cb-cc5c-4109-822c-84d58ed7b18b@k17g2000yqh.googlegroups.com> <351fcb4c-4e88-41b0-a0aa-b3d63832d1aa@e23g2000yqd.googlegroups.com> Message-ID: <92dc5777-0fce-4463-aea4-350823e73ad3@c3g2000yqd.googlegroups.com> On Dec 2, 4:41?pm, "John Posner" wrote: > ? Goal: place integer 456 flush-right in a field of width 8 > > ? ?Py2: "%%%dd" % 8 % 456 > ? ?Py3: "{0:{1}d}".format(456, 8) > > With str.format(), you don't need to nest one formatting operation within ? > another. A little less mind-bending, and every little bit helps! Or even "{:{}d}".format(456, 8), in 3.1 and 2.7 (when it appears). But you can do this with % formatting, too. In either 2.x or 3.x: >>> "%*d" % (8, 456) ' 456' -- Mark From carsten.haese at gmail.com Wed Dec 2 13:34:11 2009 From: carsten.haese at gmail.com (Carsten Haese) Date: Wed, 02 Dec 2009 13:34:11 -0500 Subject: Moving from Python 2 to Python 3: A 4 page "cheat sheet" In-Reply-To: References: <291d64cb-cc5c-4109-822c-84d58ed7b18b@k17g2000yqh.googlegroups.com> <351fcb4c-4e88-41b0-a0aa-b3d63832d1aa@e23g2000yqd.googlegroups.com> Message-ID: John Posner wrote: > Goal: place integer 456 flush-right in a field of width 8 > > Py2: "%%%dd" % 8 % 456 > Py3: "{0:{1}d}".format(456, 8) > > With str.format(), you don't need to nest one formatting operation > within another. With string interpolation, you don't need to do that, either. >>> '%*d' % (8,456) ' 456' -- Carsten Haese http://informixdb.sourceforge.net From sturlamolden at yahoo.no Wed Dec 2 14:12:11 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Wed, 2 Dec 2009 11:12:11 -0800 (PST) Subject: Coding Cross Correlation Function in Python References: <3a2b623e-e5a0-4935-97a4-cad384745525@c3g2000yqd.googlegroups.com> Message-ID: <88e29640-ba16-4b60-83e8-12aa5fae8616@p8g2000yqb.googlegroups.com> On 2 Des, 18:50, DarthXander wrote: > However to do this 700 times seems ridiculous. How would I get python > to perform this for me for t in a range of roughly 0-700? For two 1D ndarrays, the cross-correlation is from numpy.fft import rfft, irfft from numpy import fliplr xcorr = lambda x,y : irfft(rfft(x)*rfft(fliplr(y))) Normalize as you wish, and preferably pad with zeros before invoking xcorr. From DarthXander at hotmail.co.uk Wed Dec 2 14:20:47 2009 From: DarthXander at hotmail.co.uk (DarthXander) Date: Wed, 2 Dec 2009 11:20:47 -0800 (PST) Subject: Coding Cross Correlation Function in Python References: <3a2b623e-e5a0-4935-97a4-cad384745525@c3g2000yqd.googlegroups.com> <88e29640-ba16-4b60-83e8-12aa5fae8616@p8g2000yqb.googlegroups.com> Message-ID: <2199ea50-726d-4e00-b1e4-9991dfb29443@k19g2000yqc.googlegroups.com> On Dec 2, 7:12?pm, sturlamolden wrote: > For two 1D ndarrays, the cross-correlation is > > from numpy.fft import rfft, irfft > from numpy import fliplr > > xcorr = lambda x,y : irfft(rfft(x)*rfft(fliplr(y))) > > Normalize as you wish, and preferably pad with zeros before invoking > xcorr. Thanks, though I'd like to do this longer hand than the built in functions! Great to approximate it though. From dhwild at talktalk.net Wed Dec 2 14:28:44 2009 From: dhwild at talktalk.net (David H Wild) Date: Wed, 02 Dec 2009 19:28:44 +0000 (GMT) Subject: Moving from Python 2 to Python 3: A 4 page "cheat sheet" References: <291d64cb-cc5c-4109-822c-84d58ed7b18b@k17g2000yqh.googlegroups.com> <351fcb4c-4e88-41b0-a0aa-b3d63832d1aa@e23g2000yqd.googlegroups.com> Message-ID: <50c37c6253dhwild@talktalk.net> In article <351fcb4c-4e88-41b0-a0aa-b3d63832d1aa at e23g2000yqd.googlegroups.com>, Mark Summerfield wrote: > I only just found out that I was supposed to give a different URL: > http://www.informit.com/promotions/promotion.aspx?promo=137519 > This leads to a web page where you can download the document (just by > clicking the "Download Now" button), but if you _choose_ you can also > enter your name and email to win some sort of prize. There is a typographical fault on page 4 of this pdf file. The letter "P" is missing from the word "Python" at the head of the comparison columns. -- David Wild using RISC OS on broadband www.davidhwild.me.uk From astley.lejasper at gmail.com Wed Dec 2 14:33:27 2009 From: astley.lejasper at gmail.com (Astley Le Jasper) Date: Wed, 2 Dec 2009 11:33:27 -0800 (PST) Subject: Noob thread lock question Message-ID: <5f776ec1-9b8c-45f7-b4e5-ff140638d6bf@33g2000vbe.googlegroups.com> I have a number of threads that write to a database. I have created a thread lock, but my question is this: - If one thread hits a lock, do a) all the other threads stop, or b) just the ones that come to the same lock? - I presume that the answer is b. In which case do the threads stop only if they come to the same instance of a lock. For example, you could have a lock instance for one database and another instance for another database (first_db_thread_lock = threading.RLock() .... second_db_thread_lock = threading.RLock()). I appreciate this is a bit of a noob question, but I didn't want to assume anything. ALJ From deets at nospam.web.de Wed Dec 2 14:43:46 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 02 Dec 2009 20:43:46 +0100 Subject: Noob thread lock question In-Reply-To: <5f776ec1-9b8c-45f7-b4e5-ff140638d6bf@33g2000vbe.googlegroups.com> References: <5f776ec1-9b8c-45f7-b4e5-ff140638d6bf@33g2000vbe.googlegroups.com> Message-ID: <7nnubjF3jl6o1U1@mid.uni-berlin.de> Astley Le Jasper schrieb: > I have a number of threads that write to a database. I have created a > thread lock, but my question is this: > > - If one thread hits a lock, do a) all the other threads stop, or b) > just the ones that come to the same lock? Only the ones coming the the same lock. > - I presume that the answer is b. In which case do the threads stop > only if they come to the same instance of a lock. For example, you > could have a lock instance for one database and another instance for > another database (first_db_thread_lock = threading.RLock() .... > second_db_thread_lock = threading.RLock()). There is nothing like "not an instance of a lock". So it's essentially the same question as the first, and thus the answer is also: yes, only for the *same* lock, which is an instance. Diez From john at castleamber.com Wed Dec 2 14:50:10 2009 From: john at castleamber.com (John Bokma) Date: Wed, 02 Dec 2009 13:50:10 -0600 Subject: Moving from Python 2 to Python 3: A 4 page "cheat sheet" References: <291d64cb-cc5c-4109-822c-84d58ed7b18b@k17g2000yqh.googlegroups.com> <87ljhm8d7e.fsf@castleamber.com> <765817ea-e502-4ec9-8639-d0d0a5b6c85f@g31g2000vbr.googlegroups.com> Message-ID: <874oo96tql.fsf@castleamber.com> Mark Summerfield writes: > On 1 Dec, 23:52, John Bokma wrote: >> Mark Summerfield writes: >> > It is available as a free PDF download (no registration or anything) >> > from InformIT's website. Here's the direct link: >> >http://ptgmedia.pearsoncmg.com/imprint_downloads/informit/promotions/... >> >> Thanks! >> >> > And of course, if you want more on Python 3, there's always the >> > documentation---or my book:-) >> > "Programming in Python 3 (Second Edition)" ISBN-10: 0321680561. >> >> Meh, second edition already? Haven't read the entire first edition >> yet. Which is IMO a good book (I also gave it to my brother as a >> present). > > If it is any consolation, the second edition should have a much longer > life, now that we have the language moratorium. (I _really_ wanted to > cover 3.1.) Nah, I wasn't really complaining. Moreover, I am glad I didn't finish the first edition, so I have less of a problem starting in the 2nd edition from the beginning. From what I've read in the 1st edition it's an excellent book. >> Only negative point (to me) so far is that in the beginning (p8-9) the >> book mentions placing Python programs in C:\py3eg which gives me the >> unpleasant feeling that someone is coding on Windows XP with >> Administrator rights... > > OK, you got me there, I knew it ;-) Should've emailed you months ago and maybe it would have changed in the 2nd edition :-( > I only use Windows for testing purposes and my > personal logon account does have Administrator rights, which I assumed > was standard for personal machines? I use XP Professional and the first thing I do after installation is creating a limited user account for my day to day work. As far as I know this can also be done in XP Home, but I've no experience with home. > Also, the path is short. It is > only a suggestion, it really doesn't matter where you unpack the > examples. My issue with it is that it somewhat promotes working with Administrator rights, which is as dangerous as working with root rights on other OSes if the machine is not connected to the Internet. If it's connected to the Internet it's way more dangerous, sadly. Anyway, thanks for writing IMO a very good book, and I *am* happy with a second edition. -- John Bokma Read my blog: http://johnbokma.com/ Hire me (Perl/Python): http://castleamber.com/ From allen.fowler at yahoo.com Wed Dec 2 15:13:23 2009 From: allen.fowler at yahoo.com (allen.fowler) Date: Wed, 2 Dec 2009 12:13:23 -0800 (PST) Subject: How to set object parameters nicely? References: <83ced7d2-8d75-4e41-a60b-7c0c73515129@m38g2000yqd.googlegroups.com> <7nlnj4F3mq0bdU1@mid.uni-berlin.de> Message-ID: > >>> Is there a better way to do this? > >> class MyOb(object): > >> ? ? ?def __init__(self, **kwargs): > >> ? ? ? ? ?self.__dict__.update(kwargs) > > >> ob1 = MyOb(p1="Tom", p3="New York") > >> ob2 = MyOb(p1="Joe", p2="joe at host", p3="New Jersey") > > > I've tried this, but have found two issues: > > > 1) I can't set default values. > > 2) I can't set required values. > > > In both of the above cases, if theobjectis created without the > > "exact" dict() I expect, all the assumption my methods make about what > > is available in "self" fall apart. > > > Perhaps, as Diez mentioned, my approach is wrong. ? What would be the > > right thing to do in this situation? > > There is no general answer to this. It depends on your actual problem. > > Diez What are some of the patterns that tend to be used? -- AF From list at qtrac.plus.com Wed Dec 2 15:15:01 2009 From: list at qtrac.plus.com (Mark Summerfield) Date: Wed, 2 Dec 2009 12:15:01 -0800 (PST) Subject: Moving from Python 2 to Python 3: A 4 page "cheat sheet" References: <291d64cb-cc5c-4109-822c-84d58ed7b18b@k17g2000yqh.googlegroups.com> <351fcb4c-4e88-41b0-a0aa-b3d63832d1aa@e23g2000yqd.googlegroups.com> <50c37c6253dhwild@talktalk.net> Message-ID: <9d290ad6-e0b8-4bfa-92c8-8209c7e933ec@a21g2000yqc.googlegroups.com> On 2 Dec, 19:28, David H Wild wrote: > In article > <351fcb4c-4e88-41b0-a0aa-b3d63832d... at e23g2000yqd.googlegroups.com>, > ? ?Mark Summerfield wrote: > > > I only just found out that I was supposed to give a different URL: > >http://www.informit.com/promotions/promotion.aspx?promo=137519 > > This leads to a web page where you can download the document (just by > > clicking the "Download Now" button), but if you _choose_ you can also > > enter your name and email to win some sort of prize. > > There is a typographical fault on page 4 of this pdf file. The letter "P" > is missing from the word "Python" at the head of the comparison columns. I can't see that problem---I've tried the PDF with evince, gv, acroread, and okular, and no missing "P" on page 4. I don't have a machine with RISC OS on it so I can't test on that environment! > -- > David Wild using RISC OS on broadbandwww.davidhwild.me.uk From victorsubervi at gmail.com Wed Dec 2 15:18:11 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Wed, 2 Dec 2009 16:18:11 -0400 Subject: Insane Problem Message-ID: <4dc0cfea0912021218g797f782esa2c174923b6ac492@mail.gmail.com> Hi; I have spent 2-3 hours trying to track this bug. Here's the code snippet: form = cgi.FieldStorage() fn = getattr(options, 'products') ourOptionsNames = [] optionsNames, doNotUse = fn('names') for name in optionsNames: test = table + '-' + name print test check = form.getfirst(test, '') print check if check != '': ourOptionsNames.append(name) Now, when it looks through with test=='products', it doesn't report that any of the values from the form are checked. However, when I explicitly write out something like: print form.getfirst('products-sizes', '') which I checked on the form from the referring page, it does in fact print out! My test prints show that 'products-sizes' is being passed to "check" and should therefore be appended to "ourOptionsNames". But it isn't! What am I missing here?? TIA, Victor -------------- next part -------------- An HTML attachment was scrubbed... URL: From radix at twistedmatrix.com Wed Dec 2 15:21:25 2009 From: radix at twistedmatrix.com (Christopher Armstrong) Date: Wed, 2 Dec 2009 15:21:25 -0500 Subject: ANN: Twisted 9.0.0 Message-ID: <60ed19d40912021221u3096f047g3e6e86f43b4a0d2b@mail.gmail.com> = Twisted 9.0.0 = I'm happy to announce Twisted 9, the first (and last) release of Twisted in 2009. The previous release was Twisted 8.2 in December of 2008. Given that, a lot has changed! This release supports Python 2.3 through Python 2.6, though it is the last one that will support Python 2.3. The next release will support only Python 2.4 and above. Twisted: the framework of the future! You can download the new release at our web site, http://twistedmatrix.com/ There were around 285 tickets resolved in this release. The full list of changes is available here: http://twistedmatrix.com/trac/browser/tags/releases/twisted-9.0.0/NEWS?format=raw It's quite a huge list of changes spanning almost all of the Twisted projects, so here are some of the more exciting changes: In the core: - The Windows IOCP reactor now supports SSL. - The memcache protocol implementation got some nice new features. In Twisted Web: - There's a new HTTP client API and protocol implementation, starting at twisted.web.client.Agent. It's still pretty low-level, but much more flexible than the old API. - There were many improvements to the WSGI support. In Twisted Conch: - PyASN1 is now used to parse SSH keys (which means you now need to install it to use Conch). - SFTP servers (especially on Windows) now behave a lot better. In Twisted Mail: - The IMAP server and client protocol implementations had many fixes. For example, SASL PLAIN credentials now work. In Twisted Words: - XMPP clients now support the ANONYMOUS SASL authentication type. - The IRC protocol implementations had many fixes. And a lot more. = What is Twisted? = >From the web site: Twisted is an event-driven networking engine written in Python and licensed under the MIT license. See the FAQ for commonly asked questions about Twisted. http://twistedmatrix.com/trac/wiki/FrequentlyAskedQuestions If you want to get started with Twisted, the first thing you should do is read the Twisted Core Documentation. http://twistedmatrix.com/projects/core/documentation/howto/index.html Twisted projects variously support TCP, UDP, SSL/TLS, multicast, Unix sockets, a large number of protocols (including HTTP, NNTP, IMAP, SSH, IRC, FTP, and others), and much more. Enjoy! -- Christopher Armstrong http://radix.twistedmatrix.com/ http://planet-if.com/ From hansmu at xs4all.nl Wed Dec 2 15:46:27 2009 From: hansmu at xs4all.nl (Hans Mulder) Date: Wed, 02 Dec 2009 21:46:27 +0100 Subject: Python without wrapper script In-Reply-To: References: Message-ID: <4b16d293$0$22935$e4fe514c@news.xs4all.nl> Ulrich Eckhardt wrote: > eric.frederich wrote: >> Is there a way to set up environment variables in python itself >> without having a wrapper script. > > Yes, sure, you can set environment variables... > >> The wrapper script is now something like.... >> >> #!/bin/bash >> >> export LD_LIBRARY_PATH="/some/thing/lib:$LD_LIBRARY_PATH" >> export LD_LIBRARY_PATH="/another/thing/lib:$LD_LIBRARY_PATH" >> >> export PATH="/some/thing/bin:$PATH" >> export PATH="/another/thing/bin:$PATH" >> >> python ./someScript.py > > ...but this won't work, I'm afraid. > > LD_LIBRARY_PATH is for the program loader / dynamic linker under Linux. This > thing is what is invoked _before_ the program is started, any later > modifications to the environment are ignored. In cases like yours I have sometimes written Python scripts that acted as their own wrapper: #!/usr/bin/env python import os, sys if 'LD_LIBRARY_PATH' in os.environ: lib_path = os.environ['LD_LIBRARY_PATH'] if '/some/thing/lib' in lib_path and '/another/thing/lib' in lib_path: pass else: os.environ['LD_LIBRARY_PATH'] += ':/some/thing/lib:/another/thing/lib' os.execve(sys.argv[0], sys.argv, os.environ) else: os.environ['LD_LIBRARY_PATH'] = '/some/thing/lib:/another/thing/lib' os.execve(sys.argv[0], sys.argv, os.environ) os.environ['PATH'] = '/some/thing/bin:/another/thing/bin:' + os.environ['PATH'] # At this point, you can import a module that depends # on LD_LIBRARY_PATH including /some/thing/lib # # Alternatively (and more clearly), you can replace the 'pass' above # by that import statement This code restarts Python if it has to modify os.environ['LD_LIBRARY_PATH']. If you try to single-step this code under pdb, you'll get as far as the os.execve() call. That call starts Python afresh, without a debugger. In other words, if you need to use pdb, you'll have to set the environment variables in the shell. > Similarly PATH, which tells the shell (e.g. bash) where to find executables. > If you need that to e.g. find 'python' itself, you're out of luck. > Otherwise, I believe Python itself doesn't use PATH, so you could set it > inside and any shells started from Python should pick it up. You don't have to restart Python if you modify to os.environ['PATH'], so that bit is easy. Hope this helps, -- HansM From python at mrabarnett.plus.com Wed Dec 2 15:59:07 2009 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 02 Dec 2009 20:59:07 +0000 Subject: Moving from Python 2 to Python 3: A 4 page "cheat sheet" In-Reply-To: <9d290ad6-e0b8-4bfa-92c8-8209c7e933ec@a21g2000yqc.googlegroups.com> References: <291d64cb-cc5c-4109-822c-84d58ed7b18b@k17g2000yqh.googlegroups.com> <351fcb4c-4e88-41b0-a0aa-b3d63832d1aa@e23g2000yqd.googlegroups.com> <50c37c6253dhwild@talktalk.net> <9d290ad6-e0b8-4bfa-92c8-8209c7e933ec@a21g2000yqc.googlegroups.com> Message-ID: <4B16D51B.70004@mrabarnett.plus.com> Mark Summerfield wrote: > On 2 Dec, 19:28, David H Wild wrote: >> In article >> <351fcb4c-4e88-41b0-a0aa-b3d63832d... at e23g2000yqd.googlegroups.com>, >> Mark Summerfield wrote: >> >>> I only just found out that I was supposed to give a different URL: >>> http://www.informit.com/promotions/promotion.aspx?promo=137519 >>> This leads to a web page where you can download the document (just by >>> clicking the "Download Now" button), but if you _choose_ you can also >>> enter your name and email to win some sort of prize. >> There is a typographical fault on page 4 of this pdf file. The letter "P" >> is missing from the word "Python" at the head of the comparison columns. > Which is page 4? The page numbers are missing! (But the column titles look OK.) :-) > I can't see that problem---I've tried the PDF with evince, gv, > acroread, and okular, and no missing "P" on page 4. I don't have a > machine with RISC OS on it so I can't test on that environment! > From nagle at animats.com Wed Dec 2 16:05:48 2009 From: nagle at animats.com (John Nagle) Date: Wed, 02 Dec 2009 13:05:48 -0800 Subject: Noob thread lock question In-Reply-To: <7nnubjF3jl6o1U1@mid.uni-berlin.de> References: <5f776ec1-9b8c-45f7-b4e5-ff140638d6bf@33g2000vbe.googlegroups.com> <7nnubjF3jl6o1U1@mid.uni-berlin.de> Message-ID: <4b16d3ea$0$1636$742ec2ed@news.sonic.net> Diez B. Roggisch wrote: > Astley Le Jasper schrieb: >> I have a number of threads that write to a database. I have created a >> thread lock, but my question is this: >> >> - If one thread hits a lock, do a) all the other threads stop, or b) >> just the ones that come to the same lock? > > Only the ones coming the the same lock. > >> - I presume that the answer is b. In which case do the threads stop >> only if they come to the same instance of a lock. For example, you >> could have a lock instance for one database and another instance for >> another database (first_db_thread_lock = threading.RLock() .... >> second_db_thread_lock = threading.RLock()). > > > There is nothing like "not an instance of a lock". So it's essentially > the same question as the first, and thus the answer is also: yes, only > for the *same* lock, which is an instance. > > Diez Note that if you're using MySQLdb, there are some restrictions on threading. Only one thread at a time can use each connection to the database. But you can create multiple connections to the same database at the same time from a single program, and run them concurrently. John Nagle From python at mrabarnett.plus.com Wed Dec 2 16:08:09 2009 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 02 Dec 2009 21:08:09 +0000 Subject: Insane Problem In-Reply-To: <4dc0cfea0912021218g797f782esa2c174923b6ac492@mail.gmail.com> References: <4dc0cfea0912021218g797f782esa2c174923b6ac492@mail.gmail.com> Message-ID: <4B16D739.5080408@mrabarnett.plus.com> Victor Subervi wrote: > Hi; > I have spent 2-3 hours trying to track this bug. Here's the code snippet: > > form = cgi.FieldStorage() > fn = getattr(options, 'products') > ourOptionsNames = [] > optionsNames, doNotUse = fn('names') > for name in optionsNames: > test = table + '-' + name > print test > check = form.getfirst(test, '') > print check > if check != '': > ourOptionsNames.append(name) > > Now, when it looks through with test=='products', it doesn't report that > any of the values from the form are checked. However, when I explicitly > write out something like: > print form.getfirst('products-sizes', '') > which I checked on the form from the referring page, it does in fact > print out! My test prints show that 'products-sizes' is being passed to > "check" and should therefore be appended to "ourOptionsNames". But it > isn't! What am I missing here?? > What do the print statements actually print? Please copy and paste their output. From dhwild at talktalk.net Wed Dec 2 16:28:56 2009 From: dhwild at talktalk.net (David H Wild) Date: Wed, 02 Dec 2009 21:28:56 +0000 (GMT) Subject: Moving from Python 2 to Python 3: A 4 page "cheat sheet" References: <291d64cb-cc5c-4109-822c-84d58ed7b18b@k17g2000yqh.googlegroups.com> <351fcb4c-4e88-41b0-a0aa-b3d63832d1aa@e23g2000yqd.googlegroups.com> <50c37c6253dhwild@talktalk.net> <9d290ad6-e0b8-4bfa-92c8-8209c7e933ec@a21g2000yqc.googlegroups.com> Message-ID: <50c3876378dhwild@talktalk.net> In article <9d290ad6-e0b8-4bfa-92c8-8209c7e933ec at a21g2000yqc.googlegroups.com>, Mark Summerfield wrote: > > There is a typographical fault on page 4 of this pdf file. The letter > > "P" is missing from the word "Python" at the head of the comparison > > columns. > I can't see that problem---I've tried the PDF with evince, gv, > acroread, and okular, and no missing "P" on page 4. I don't have a > machine with RISC OS on it so I can't test on that environment! Using a different pdf reader, on the same machine, the letters are there. It's an odd thing, because it's only that one page that has the problem. Thanks, anyway. -- David Wild using RISC OS on broadband www.davidhwild.me.uk From jjposner at optimum.net Wed Dec 2 17:49:43 2009 From: jjposner at optimum.net (John Posner) Date: Wed, 02 Dec 2009 17:49:43 -0500 Subject: Moving from Python 2 to Python 3: A 4 page "cheat sheet" References: <291d64cb-cc5c-4109-822c-84d58ed7b18b@k17g2000yqh.googlegroups.com> <351fcb4c-4e88-41b0-a0aa-b3d63832d1aa@e23g2000yqd.googlegroups.com> Message-ID: On Wed, 02 Dec 2009 13:34:11 -0500, Carsten Haese wrote: > > With string interpolation, you don't need to do that, either. >>>> '%*d' % (8,456) > ' 456' > Thanks, Carsten and Mark D. -- I'd forgotten about the use of "*" in minimum-field-width specs and precision specs (doh). How about this: "pi={1:.{0}f} e={2:.{0}f}".format(5, math.pi, math.e) (result: 'pi=3.14159 e=2.71828') Can the Python2 %-formating facility handle this without repeating the "5" argument? Even if it can, I stand by my original suggestion: include an example to show that the arguments to str.format() can be used on both the left and the right of a ":" in a replacement field. -John From brad.aytes at gmail.com Wed Dec 2 18:05:15 2009 From: brad.aytes at gmail.com (baytes) Date: Wed, 2 Dec 2009 15:05:15 -0800 (PST) Subject: Cron Job Output Message-ID: I have cron checking services every 5-10 minutes, and if a service goes up or down it writes to a file, Im trying to write a script that will check that file for updates and print the results. this will tie into a module for phenny where the bot will be able to print the contents of the updated file to the channel. Im extremely new to python and any point in the right direction or tutorials on the subject would be greatly appreicated. From jabronson at gmail.com Wed Dec 2 18:21:33 2009 From: jabronson at gmail.com (Joshua Bronson) Date: Wed, 2 Dec 2009 15:21:33 -0800 (PST) Subject: python bijection References: <85100df7-a8b0-47e9-a854-ba8a8a2f3b98@r31g2000vbi.googlegroups.com> Message-ID: <9a6902a1-327e-435e-8c9a-b69028994758@u20g2000vbq.googlegroups.com> On Dec 1, 8:17?pm, aahz at pythoncraft.com (Aahz) wrote: > In article <85100df7-a8b0-47e9-a854-ba8a8a2f3b98 at r31g2000vbi.googlegroups.com>, > Joshua Bronson ? wrote: > >I noticed the phonebook example in your ActiveState recipe and thought > >you might consider changing it to something like husbands to wives, > >since the names-to-phone-numbers relation is many-to-many. > > What makes you think husbands to wives is one-to-one? ?;-) ?(Even > assuming monogamy, you have husbands-to-husbands and wives-to-wives.) Hah! I knew this was coming and even put "assuming monogamy" in the source! http://bitbucket.org/jab/bidict/src/712da6e2dd26/bidict.py#cl-65 ;P As for husbands-to-husbands and wives-to-wives, those are just separate one-to-one mappings! Doesn't mean husbands-to-wives ain't one- to-one! At any rate, apologies to the community for my heteronormative example. It was merely pedagogical and reflects nothing about my personal views! If you have any further concerns, please send them to my lawyer, /dev/null. From pavlovevidence at gmail.com Wed Dec 2 18:36:40 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 2 Dec 2009 15:36:40 -0800 (PST) Subject: How to set object parameters nicely? References: <83ced7d2-8d75-4e41-a60b-7c0c73515129@m38g2000yqd.googlegroups.com> <7nlnj4F3mq0bdU1@mid.uni-berlin.de> Message-ID: <559162e6-1c91-4a4a-a90c-b303c93bd976@u7g2000yqm.googlegroups.com> On Dec 2, 12:13?pm, "allen.fowler" wrote: > > >>> Is there a better way to do this? > > >> class MyOb(object): > > >> ? ? ?def __init__(self, **kwargs): > > >> ? ? ? ? ?self.__dict__.update(kwargs) > > > >> ob1 = MyOb(p1="Tom", p3="New York") > > >> ob2 = MyOb(p1="Joe", p2="joe at host", p3="New Jersey") > > > > I've tried this, but have found two issues: > > > > 1) I can't set default values. > > > 2) I can't set required values. > > > > In both of the above cases, if theobjectis created without the > > > "exact" dict() I expect, all the assumption my methods make about what > > > is available in "self" fall apart. > > > > Perhaps, as Diez mentioned, my approach is wrong. ? What would be the > > > right thing to do in this situation? > > > There is no general answer to this. It depends on your actual problem. > > What are some of the patterns that tend to be used? For the record, I don't really agree that a lot of parameters is code smell. It's maybe a red flag that you are doing too much in one function and/or class, but nothing inherently shady. One thing to ask yourself: are there a lot of combinations of parameters that don't make sense? For example, do you have a lot of cases where, say, if one parameter is set to x, then parameters a, b, c, and d do nothing? That would indicate that you should break your function/class up into smaller, more targeted parts. However, if all your parameters are orthogonal, that is, if all or most combinations make sense, then there's no reason ten or twenty parameters isn't perfectly reasonable. Whenever I have ten parameters in an __init__, I ususally just write out the assignments, although more often than not the object's attributes don't correspond to the parameters one-to-one, so I'd have to write them out anyway. Carl Banks From jabronson at gmail.com Wed Dec 2 18:52:11 2009 From: jabronson at gmail.com (Joshua Bronson) Date: Wed, 2 Dec 2009 15:52:11 -0800 (PST) Subject: python bijection References: <85100df7-a8b0-47e9-a854-ba8a8a2f3b98@r31g2000vbi.googlegroups.com> Message-ID: <65a176a1-fa29-48d9-a30f-60f464719235@p32g2000vbi.googlegroups.com> On Dec 1, 9:03?pm, Chris Rebert wrote: > Reminds me of this quite funny blog post: > "Gay marriage: the database engineering perspective" > http://qntm.org/?gay amazing From tjreedy at udel.edu Wed Dec 2 18:56:21 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 02 Dec 2009 18:56:21 -0500 Subject: Question about file objects... In-Reply-To: <36dec4ff0912020811w32be2430rd6692de96ffd2671@mail.gmail.com> References: <01fd9f0b-aa15-41c8-86ac-1d719d87999a@m35g2000vbi.googlegroups.com> <36dec4ff0912020811w32be2430rd6692de96ffd2671@mail.gmail.com> Message-ID: J wrote: > On Wed, Dec 2, 2009 at 09:27, nn wrote: >>> Is there a way to read the file, one item at a time, delimited by >>> commas WITHOUT having to read all 16,000 items from that one line, >>> then split them out into a list or dictionary?? > >> File iteration is a convenience since it is the most common case. If >> everything is on one line, you will have to handle record separators >> manually by using the .read() method on the file >> object and searching for the comma. If everything fits in memory the >> straightforward way would be to read the whole file with .read() and >> use .split(",") on the returned string. That should give you a nice >> list of everything. > > Agreed. The confusion came because the guy teaching said that > iterating the file is delimited by a carriage return character... If he said exactly that, he is not exactly correct. File iteration looks for line ending character(s), which depends on the system or universal newline setting. > which to me sounds like it's an arbitrary thing that can be changed... > > I was already thinking that I'd have to read it in small chunks and > search for the delimiter i want... and reading the whole file into a > string and then splitting that would would be nice, until the file is > so large that it starts taking up significant amounts of memory. > > Anyway, thanks both of you for the explanations... I appreciate the help! I would not be surprised if a generic file chunk generator were posted somewhere. It would be a good entry for the Python Cookbook, if not there already. tjr From lodmod.dod at gmail.com Wed Dec 2 19:07:19 2009 From: lodmod.dod at gmail.com (LoD MoD) Date: Wed, 2 Dec 2009 16:07:19 -0800 Subject: Cron Job Output In-Reply-To: References: Message-ID: You might try something like this http://code.activestate.com/recipes/157035/ On Wed, Dec 2, 2009 at 3:05 PM, baytes wrote: > I have cron checking services every 5-10 minutes, and if a service > goes up or down it writes to a file, Im trying to write a script that > will check that file for updates and print the results. this will tie > into a module for phenny where the bot will be able to print the > contents of the updated file to the channel. > > Im extremely new to python and any point in the right direction or > tutorials on the subject would be greatly appreicated. > -- > http://mail.python.org/mailman/listinfo/python-list > From tjreedy at udel.edu Wed Dec 2 19:12:52 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 02 Dec 2009 19:12:52 -0500 Subject: Moving from Python 2 to Python 3: A 4 page "cheat sheet" In-Reply-To: <4d82209c-1a43-405e-8ba7-49b7d7985335@n35g2000yqm.googlegroups.com> References: <291d64cb-cc5c-4109-822c-84d58ed7b18b@k17g2000yqh.googlegroups.com> <19194586-cd6a-4d13-ae1c-798884194672@n35g2000yqm.googlegroups.com> <4d82209c-1a43-405e-8ba7-49b7d7985335@n35g2000yqm.googlegroups.com> Message-ID: Mark Summerfield wrote: > Well it seems clear to me that the BDFL wants to kill of % formatting, > but wasn't able to for Python 3... Definitely. I thought of adding autonumbering of fields (in 3.1) in response to his inquiry about the barriers to moving to .format. That solved 'simplicity of defaults'. The other, 'Autoconversion of installed base' still awaits. > So I still think it is reasonable > (1) to describe it as deprecated and (2) to only teach and use > str.format(). At the moment (3.1) there are, unfortunately, library packages that require % for formatting (logging, I believe, for one). There has been discussion on adding a new option for 3.2, but I do not know what will happen. Depends on whether you want to be absolutely complete. I strictly use .format when I can, which so far is always. Terry Jan Reedy From tjreedy at udel.edu Wed Dec 2 19:18:47 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 02 Dec 2009 19:18:47 -0500 Subject: ANN: Twisted 9.0.0 In-Reply-To: <60ed19d40912021221u3096f047g3e6e86f43b4a0d2b@mail.gmail.com> References: <60ed19d40912021221u3096f047g3e6e86f43b4a0d2b@mail.gmail.com> Message-ID: Christopher Armstrong wrote: > = Twisted 9.0.0 = > > I'm happy to announce Twisted 9, the first (and last) release of > Twisted in 2009. The previous release was Twisted 8.2 in December of > 2008. Given that, a lot has changed! > > This release supports Python 2.3 through Python 2.6, though it is the > last one that will support Python 2.3. The next release will support > only Python 2.4 and above. Twisted: the framework of the future! Not unless it supports 3.1+. Is that in the cards (tickets)? From aahz at pythoncraft.com Wed Dec 2 19:37:49 2009 From: aahz at pythoncraft.com (Aahz) Date: 2 Dec 2009 16:37:49 -0800 Subject: python bijection References: <85100df7-a8b0-47e9-a854-ba8a8a2f3b98@r31g2000vbi.googlegroups.com> <9a6902a1-327e-435e-8c9a-b69028994758@u20g2000vbq.googlegroups.com> Message-ID: In article <9a6902a1-327e-435e-8c9a-b69028994758 at u20g2000vbq.googlegroups.com>, Joshua Bronson wrote: > >At any rate, apologies to the community for my heteronormative >example. It was merely pedagogical and reflects nothing about my >personal views! If you have any further concerns, please send them to >my lawyer, /dev/null. Apology accepted. ;-) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ The best way to get information on Usenet is not to ask a question, but to post the wrong information. From allen.fowler at yahoo.com Wed Dec 2 19:54:26 2009 From: allen.fowler at yahoo.com (allen.fowler) Date: Wed, 2 Dec 2009 16:54:26 -0800 (PST) Subject: How to set object parameters nicely? References: <83ced7d2-8d75-4e41-a60b-7c0c73515129@m38g2000yqd.googlegroups.com> <7nlnj4F3mq0bdU1@mid.uni-berlin.de> <559162e6-1c91-4a4a-a90c-b303c93bd976@u7g2000yqm.googlegroups.com> Message-ID: On Dec 2, 6:36?pm, Carl Banks wrote: > For the record, I don't really agree that a lot of parameters is code > smell. ?It's maybe a red flag that you are doing too much in one > function and/or class, but nothing inherently shady. > > One thing to ask yourself: are there a lot of combinations of > parameters that don't make sense? ?For example, do you have a lot of > cases where, say, if one parameter is set to x, then parameters a, b, > c, and d do nothing? ?That would indicate that you should break your > function/class up into smaller, more targeted parts. > > However, if all your parameters are orthogonal, that is, if all or > most combinations make sense, then there's no reason ten or twenty > parameters isn't perfectly reasonable. > > Whenever I have ten parameters in an __init__, I ususally just write > out the assignments, although more often than not the object's > attributes don't correspond to the parameters one-to-one, so I'd have > to write them out anyway. > Thank you for the thoughtful insight. In this case, and I am trying to create a number of ORM-like objects. (Though, there is no database involved.) So, instances of these classes are acting as records that are shuttled around in the system, and the object's properties are acting as values. The parameters are (mostly) orthogonal, but do need defaults, and some must be required. From solipsis at pitrou.net Wed Dec 2 20:17:47 2009 From: solipsis at pitrou.net (Antoine Pitrou) Date: Thu, 3 Dec 2009 01:17:47 +0000 (UTC) Subject: Moving from Python 2 to Python 3: A 4 page "cheat sheet" References: <291d64cb-cc5c-4109-822c-84d58ed7b18b@k17g2000yqh.googlegroups.com> Message-ID: Le Tue, 01 Dec 2009 06:03:36 -0800, Mark Summerfield a ?crit?: > I've produced a 4 page document that provides a very concise summary of > Python 2<->3 differences plus the most commonly used new Python 3 > features. It is aimed at existing Python 2 programmers who want to start > writing Python 3 programs and want to use Python 3 idioms rather than > those from Python 2 where the idioms differ. [...] > > It is available as a free PDF download (no registration or anything) > from InformIT's website. Here's the direct link: This is great! Just one thing: ? Copyright ? Qtrac Ltd. 2009. All rights reserved ? Might I suggest that you release it under a free license instead? (such as the CC by, CC by-sa, or the Free Art License) Regards Antoine. From metal29a at gmail.com Wed Dec 2 20:28:41 2009 From: metal29a at gmail.com (metal) Date: Wed, 2 Dec 2009 17:28:41 -0800 (PST) Subject: How to implement Varient/Tagged Unions/Pattern Matching in Python? Message-ID: <358b227c-d836-4243-b79a-57258590a7a7@a10g2000pre.googlegroups.com> I want to get pattern matching like OCaml in python(ref:http:// en.wikipedia.org/wiki/Tagged_union) I consider the syntax: def decl(): def Plus(expr, expr): pass def Minus(expr, expr): pass def Times(expr, expr): pass def Divide(expr, expr): pass def Value(str): pass @enum def expr(Plus, Minus, Times, Divide, Value): pass declare_types(locals()) def f(e): def _Plus(l, r): return '(%s+%s)' % (l, r) def _Minus(l, r): return '(%s-%s)' % (l, r) def _Times(l, r): return '(%s*%s)' % (l, r) def _Divide(l, r): return '(%s/%s)' % (l, r) def _Value(x): return x try: match(e, locals()) # visitor pattern except NoMatchedError: pass >>> print f(Times(Value("n"), Plus(Value("x", Value("y")))) (n*(x+y)) But it's hard to do with nested matching. Any suggestions would be appreciated BTW, Please don't ask "Why do you want to do like this" From exarkun at twistedmatrix.com Wed Dec 2 21:30:15 2009 From: exarkun at twistedmatrix.com (exarkun at twistedmatrix.com) Date: Thu, 03 Dec 2009 02:30:15 -0000 Subject: ANN: Twisted 9.0.0 In-Reply-To: References: <60ed19d40912021221u3096f047g3e6e86f43b4a0d2b@mail.gmail.com> Message-ID: <20091203023015.2549.1864307365.divmod.xquotient.85@localhost.localdomain> On 12:18 am, tjreedy at udel.edu wrote: >Christopher Armstrong wrote: >>= Twisted 9.0.0 = >> >>I'm happy to announce Twisted 9, the first (and last) release of >>Twisted in 2009. The previous release was Twisted 8.2 in December of >>2008. Given that, a lot has changed! >> >>This release supports Python 2.3 through Python 2.6, though it is the >>last one that will support Python 2.3. The next release will support >>only Python 2.4 and above. Twisted: the framework of the future! > >Not unless it supports 3.1+. Is that in the cards (tickets)? Somewhat. A description of the plan on stackoverflow: http://bit.ly/6hWqYU A message with some ticket links from a thread on the twisted-python mailing list: http://bit.ly/8csFSa Jean-Paul From exarkun at twistedmatrix.com Wed Dec 2 21:30:15 2009 From: exarkun at twistedmatrix.com (exarkun at twistedmatrix.com) Date: Thu, 03 Dec 2009 02:30:15 -0000 Subject: ANN: Twisted 9.0.0 In-Reply-To: References: <60ed19d40912021221u3096f047g3e6e86f43b4a0d2b@mail.gmail.com> Message-ID: <20091203023015.2549.1864307365.divmod.xquotient.85@localhost.localdomain> On 12:18 am, tjreedy at udel.edu wrote: >Christopher Armstrong wrote: >>= Twisted 9.0.0 = >> >>I'm happy to announce Twisted 9, the first (and last) release of >>Twisted in 2009. The previous release was Twisted 8.2 in December of >>2008. Given that, a lot has changed! >> >>This release supports Python 2.3 through Python 2.6, though it is the >>last one that will support Python 2.3. The next release will support >>only Python 2.4 and above. Twisted: the framework of the future! > >Not unless it supports 3.1+. Is that in the cards (tickets)? Somewhat. A description of the plan on stackoverflow: http://bit.ly/6hWqYU A message with some ticket links from a thread on the twisted-python mailing list: http://bit.ly/8csFSa Jean-Paul From wgheath at gmail.com Wed Dec 2 21:47:17 2009 From: wgheath at gmail.com (William Heath) Date: Wed, 2 Dec 2009 18:47:17 -0800 Subject: prolog with python Message-ID: Hi All, I have the following prolog program that I would really like to be able to run in python in some elegant way: q00(X01, R):- write('Are you over 80?'), read(INPUT), write(''), q11(INPUT, R). q11(X11, R):- X11=y, write(' You are passed the hardest year'), !. q00(X01, R):- write('You are not over 80'), Most of the implementations I have seen use assert's and don't appear to handle backtracking or negation. I somehow need to provide input to the rules as well as you can see above. Anyone know how to do this well using a python library? I would love a 100% python solution if I could find one. Anyway, thanks! -Tim -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Wed Dec 2 21:56:06 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Wed, 2 Dec 2009 18:56:06 -0800 Subject: prolog with python In-Reply-To: References: Message-ID: <50697b2c0912021856t6a7929m9bc7d324d25b38ee@mail.gmail.com> On Wed, Dec 2, 2009 at 6:47 PM, William Heath wrote: > Hi All, > > I have the following prolog program that I would really like to be able to > run in python in some elegant way: >From googling: http://pyke.sourceforge.net/ http://code.activestate.com/recipes/303057/ Cheers, Chris -- http://blog.rebertia.com From tim at commsecure.com.au Wed Dec 2 21:57:27 2009 From: tim at commsecure.com.au (Tim Allen) Date: Thu, 3 Dec 2009 13:57:27 +1100 Subject: [Twisted-Python] ANN: Twisted 9.0.0 In-Reply-To: <20091203023015.2549.1864307365.divmod.xquotient.85@localhost.localdomain> References: <60ed19d40912021221u3096f047g3e6e86f43b4a0d2b@mail.gmail.com> <20091203023015.2549.1864307365.divmod.xquotient.85@localhost.localdomain> Message-ID: <20091203135727.7ba71817@ws35.commsecure.com.au> exarkun at twistedmatrix.com wrote: > A message with some ticket links from a thread on the twisted-python > mailing list: http://bit.ly/8csFSa Some of those tickets seem out of date; a better plan would be to query for tickets with the "py3k" keyword: http://twistedmatrix.com/trac/search?q=py3k&noquickjump=1&ticket=on I believe #2484 is the master ticket: http://twistedmatrix.com/trac/ticket/2484 -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 189 bytes Desc: not available URL: From markgrahamnz at gmail.com Wed Dec 2 22:24:07 2009 From: markgrahamnz at gmail.com (Mark G) Date: Wed, 2 Dec 2009 19:24:07 -0800 (PST) Subject: Beginner Q. interrogate html object OR file search? Message-ID: Hi all, I am new to python and don't yet know the libraries well. What would be the best way to approach this problem: I have a html file parsing script - the file sits on my harddrive. I want to extract the date modified from the meta-data. Should I read through lines of the file doing a string.find to look for the character patterns of the meta- tag, or should I use a DOM type library to retrieve the html element I want? Which is best practice? which occupies least code? Regards, Mark From hackingkk at gmail.com Wed Dec 2 23:05:56 2009 From: hackingkk at gmail.com (Krishnakant) Date: Thu, 03 Dec 2009 09:35:56 +0530 Subject: Help in wxpython In-Reply-To: <86b3db7d0912020020k51cf6bc8me0bc543214c582f1@mail.gmail.com> References: <86b3db7d0912020020k51cf6bc8me0bc543214c582f1@mail.gmail.com> Message-ID: <1259813156.4532.12.camel@krishna-laptop> On Wed, 2009-12-02 at 00:20 -0800, madhura vadvalkar wrote: > Hi > > I am trying to write an PAINT like application where on the mouse > click a circle is drawn on canvas. I am new to python and using > wxpython to create this. > > here is the code: > > import wx > > class SketchWindow(wx.Window): > > def __init__ (self, parent,ID): > > wx.Window.__init__(self, parent, ID) > > self.panel =wx.Panel(self, size= (350,350)) > self.pen=wx.Pen( 'blue',4) > self.pos=(0,0) > self.InitBuffer() > self.Bind(wx.EVT_LEFT_DOWN,self.OnLeftDown) > > def InitBuffer(self): > > size=self.GetClientSize() > self.Buffer=wx.EmptyBitmap(size.width,size.height) > dc=wx.BufferedDC(None,self.buffer) > dc.SetBackground(wx.Brush(self.GetBackgroundColour())) > dc.Clear() > self.Drawcircle(dc) > self.reInitBuffer=False > > def OnLeftDown(self,event): > self.pos=event.GetPositionTuple() > self.CaptureMouse() > > def Drawcircle(self,dc): > pen=wx.Pen(colour,thickness,wx.SOLID) > dc.SetPen(pen) > dc.DrawCircle(self.pos.x,self.pos.y,r) > > class SketchFrame(wx.Frame): > def __init__(self, parent): > > wx.Frame.__init__(self, parent, -1, "Sketch Frame",size=(800,600)) > self.sketch = SketchWindow(self, -1) > > if __name__=='__main__': > app=wx.PySimpleApp() > frame=SketchFrame(None) > frame.Show(True) > app.MainLoop() > > I am getting the following error: > > Traceback (most recent call last): > File "C:/Python26/circle.py", line 42, in > frame=SketchFrame(None) > File "C:/Python26/circle.py", line 38, in __init__ > self.sketch = SketchWindow(self, -1) > File "C:/Python26/circle.py", line 12, in __init__ > self.InitBuffer() > File "C:/Python26/circle.py", line 19, in InitBuffer > dc=wx.BufferedDC(None,self.buffer) > AttributeError: 'SketchWindow' object has no attribute 'buffer' > > Please tell me what I am doing wrong. > > Thanks Madhura, Sorry to be a bit off-topic, but, I would really recommend you to use pygtk instead of wx. For one thing, the developers at pygtk are very active (they have their mailing list as well ) and it comes by default with python on almost all linux distros. You can also easily install it on windows. Most important, the api for pygtk is closely similar to wx. Not to mention the quick responses you will get with pygtk related problems. Happy hacking. Krishnakant. From vincent at vincentdavis.net Wed Dec 2 23:26:34 2009 From: vincent at vincentdavis.net (Vincent Davis) Date: Wed, 2 Dec 2009 21:26:34 -0700 Subject: Delaunay triangulation In-Reply-To: References: <77e831100912011731n53269c60r2a582d77a43a4eda@mail.gmail.com> Message-ID: <77e831100912022026t51da1f50t6e388cbe1bf4af73@mail.gmail.com> Thanks for all the replies I will look at each. *Vincent Davis 720-301-3003 * vincent at vincentdavis.net my blog | LinkedIn On Wed, Dec 2, 2009 at 10:20 AM, sturlamolden wrote: > On 2 Des, 15:28, David Robinow wrote: > > On Tue, Dec 1, 2009 at 8:31 PM, Vincent Davis > wrote: > > > Anyone know of a python implementation of Delaunay triangulation? > > > > Matplotlib has one. > > There's also Delny @pypi > > > > It's been several years since I needed this. I can't remember the > pros/cons. > > There is also a skikit add-on to NumPy/SciPy. > > http://scikits.appspot.com/delaunay > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From mckenzie.c at gmail.com Wed Dec 2 23:55:06 2009 From: mckenzie.c at gmail.com (cmckenzie) Date: Wed, 2 Dec 2009 20:55:06 -0800 (PST) Subject: Declaring a class level nested class? Message-ID: <6232b87e-f6a5-497b-a01f-d545c09ad4a8@d21g2000yqn.googlegroups.com> Hi. I'm new to Python, but I've managed to make some nice progress up to this point. After some code refactoring, I ran into a class design problem and I was wondering what the experts thought. It goes something like this: class module: nestedClass def __init__(): self.nestedClass = nested() print self.nestedClass.nestedVar class nested(): nestedVar = 1 def __init__(self): print "Initialized..." I can't figure out what the correct way to construct the "nested" class so it can belong to "module". I want a class level construct of "nested" to belong to "module", but I keep getting nestedClass isn't defined. My example isn't great or 100% accurate, but I hope you get the idea. Thanks. From clp2 at rebertia.com Thu Dec 3 00:13:03 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Wed, 2 Dec 2009 21:13:03 -0800 Subject: Declaring a class level nested class? In-Reply-To: <6232b87e-f6a5-497b-a01f-d545c09ad4a8@d21g2000yqn.googlegroups.com> References: <6232b87e-f6a5-497b-a01f-d545c09ad4a8@d21g2000yqn.googlegroups.com> Message-ID: <50697b2c0912022113p14360322gef6706e7067c8d03@mail.gmail.com> On Wed, Dec 2, 2009 at 8:55 PM, cmckenzie wrote: > Hi. > > I'm new to Python, but I've managed to make some nice progress up to > this point. After some code refactoring, I ran into a class design > problem and I was wondering what the experts thought. It goes > something like this: > > class module: > ? nestedClass > > ? def __init__(): > ? ? ?self.nestedClass = nested() > ? ? ?print self.nestedClass.nestedVar > > ? class nested(): > ? ? ?nestedVar = 1 > ? ? ?def __init__(self): > ? ? ? ? print "Initialized..." > > I can't figure out what the correct way to construct the "nested" > class so it can belong to "module". > > I want a class level construct of "nested" to belong to "module", but > I keep getting nestedClass isn't defined. Here's the scoping reason why it fails (remember that the nested class is a class variable of the containing class): Why do I get errors when accessing class variables (a.k.a. static variables)? ------------------------------------------------------------------------------------- If you try something like the following:: class Foo(object): class_variable = 42 def method(self, x): return x + class_variable Foo().method(7) You'll get an error about Python being unable to find the class variable:: Traceback (most recent call last): ... NameError: global name 'class_variable' is not defined This is because class-level scope is not consulted when looking up plain names in methods. When looking up a name, the following scopes are consulted, in order: Local variables, Variables in nested functions, Global variables, and finally, Built-ins. To refer to class variables, you must be more explicit. There are several ways to go about it: * Refer to the class by name:: def method1(self, x): return x + Foo.class_variable * Refer to the class of the object dynamically. If you class is subclassed, this will allow the subclasses to override the value of the class variable. :: def method2(self, x): return x + self.__class__.class_variable * Exploit the fact that attribute lookups on an object fall back to its class. Be warned that if you have both instance and class variables with the same name, the instance variable will shadow the class variable. :: def method3(self, x): return x + self.class_variable * If your method is not truly an instance method (i.e. does not utilize ``self``), make it a class method :: @classmethod def method4(cls, x): return x + cls.class_variable However, there's pretty much no reason to nest classes anyway in Python (it's not Java!). Just make them both top-level in the file. If one class is only used internally in the module, just use the normal private naming convention of starting its name with an underscore. Also note that class names should generally use StudlyCaps, and that naming a class "module" is rather confusing. Cheers, Chris -- If the Python.org webmasters are listening, add the FAQ entry already! http://blog.rebertia.com From inhahe at gmail.com Thu Dec 3 00:14:55 2009 From: inhahe at gmail.com (inhahe) Date: Thu, 3 Dec 2009 00:14:55 -0500 Subject: Declaring a class level nested class? In-Reply-To: <6232b87e-f6a5-497b-a01f-d545c09ad4a8@d21g2000yqn.googlegroups.com> References: <6232b87e-f6a5-497b-a01f-d545c09ad4a8@d21g2000yqn.googlegroups.com> Message-ID: it seems to me like it should work just fine if you just take out the second line where it just says nestedClass On Wed, Dec 2, 2009 at 11:55 PM, cmckenzie wrote: > Hi. > > I'm new to Python, but I've managed to make some nice progress up to > this point. After some code refactoring, I ran into a class design > problem and I was wondering what the experts thought. It goes > something like this: > > class module: > ? nestedClass > > ? def __init__(): > ? ? ?self.nestedClass = nested() > ? ? ?print self.nestedClass.nestedVar > > ? class nested(): > ? ? ?nestedVar = 1 > ? ? ?def __init__(self): > ? ? ? ? print "Initialized..." > > I can't figure out what the correct way to construct the "nested" > class so it can belong to "module". > > I want a class level construct of "nested" to belong to "module", but > I keep getting nestedClass isn't defined. > > My example isn't great or 100% accurate, but I hope you get the idea. > > Thanks. > -- > http://mail.python.org/mailman/listinfo/python-list > From inhahe at gmail.com Thu Dec 3 00:19:44 2009 From: inhahe at gmail.com (inhahe) Date: Thu, 3 Dec 2009 00:19:44 -0500 Subject: Beginner Q. interrogate html object OR file search? In-Reply-To: References: Message-ID: or i guess you could go the middle-way and just use regex. people generally say don't use regex for html (regex can't do the nesting), but it's what i would do in this case. though i don't exactly understand the question, re the html file parsing script you say you have already, or how the date is 'modified from' the meta-data. On Wed, Dec 2, 2009 at 10:24 PM, Mark G wrote: > Hi all, > > I am new to python and don't yet know the libraries well. What would > be the best way to approach this problem: I have a html file parsing > script - the file sits on my harddrive. I want to extract the date > modified from the meta-data. Should I read through lines of the file > doing a string.find to look for the character patterns of the meta- > tag, or should I use a DOM type library to retrieve the html element I > want? Which is best practice? which occupies least code? > > Regards, Mark > -- > http://mail.python.org/mailman/listinfo/python-list > From subhakolkata1234 at gmail.com Thu Dec 3 00:26:33 2009 From: subhakolkata1234 at gmail.com (joy99) Date: Wed, 2 Dec 2009 21:26:33 -0800 (PST) Subject: Question on Python as career References: <614b8dde-324b-4d54-8e73-7a96e4c0b1cf@a21g2000yqc.googlegroups.com> Message-ID: <82a03f34-d790-4b51-b5bb-2ba07a4ebaeb@15g2000prz.googlegroups.com> On Dec 2, 6:09?pm, Roy Smith wrote: > joy99 wrote: > > Dear Group, > > > I am a researcher in India's one of the premier institutes.(Indian > > Institute of Science,Bangalore). > > [...] > > I have developed them either in Python2.5 and Python2.6. > > > After I complete my Post Doctoral which may be only 2-3 months away, > > with this knowledge can I join IT? > > Or Do I have to learn anything new? > > The short answer is, you will always need to keep learning new things. ? > Whatever set of technologies are popular today (check outhttp://www.tiobe.com/index.php/content/paperinfo/tpci/index.html, for > example), will change over time. > > When I started out, I knew C and Fortran. ?I'm amazed that C is still the > #2 language, and Fortran isn't even on the TIOBE top 20 list any more. ?17 > of the 20 didn't even exist when I started out. That's always there. C still rules, even Python is built in C. For good programming sense knowledge of C helps as it works still as some kind of standard. Fortran yes lost its power but Fortran is THE LANGUAGE for people who do high end simulation like Aviation Technology or Supercomputing. They do not take the languages available in the software engineering community of business development like C,C+ +,Java or even Python. I heard recently NASA is using Python. My query was for the more or less sizeable amount of knowledge for developing business solutions as these fetch in our developing countries more jobs than high end research. In our country the scope in high end research is very limited. 20-30% you need to upgrade always be it our research, management or programming. Sometimes even some very new technologies like SAP overrule the market and you have to know them altogether. Thanks for a nice answer. Wishing you all happy day ahead, Regards, Subhabrata Banerjee. From markgrahamnz at gmail.com Thu Dec 3 00:32:38 2009 From: markgrahamnz at gmail.com (Mark G) Date: Wed, 2 Dec 2009 21:32:38 -0800 (PST) Subject: Beginner Q. interrogate html object OR file search? References: Message-ID: On Dec 3, 4:19?pm, inhahe wrote: > or i guess you could go the middle-way and just use regex. > people generally say don't use regex for html (regex can't do the > nesting), but it's what i would do in this case. > though i don't exactly understand the question, re the html file > parsing script you say you have already, or how the date is 'modified > from' the meta-data. > > On Wed, Dec 2, 2009 at 10:24 PM, Mark G wrote: > > Hi all, > > > I am new to python and don't yet know the libraries well. What would > > be the best way to approach this problem: I have a html file parsing > > script - the file sits on my harddrive. I want to extract the date > > modified from the meta-data. Should I read through lines of the file > > doing a string.find to look for the character patterns of the meta- > > tag, or should I use a DOM type library to retrieve the html element I > > want? Which is best practice? which occupies least code? > > > Regards, Mark > > -- > >http://mail.python.org/mailman/listinfo/python-list > > I'm tempted to use regex too. I have done a bit of perl & bash, and that is how I would do it with those. However, I thought there would be a smarter way to do it with libraries. I have done some digging through the libraries and think I can do it with xml.dom.minidom. Here is what I want to try... # if html file already exists, inherit the created date # 'output' is the filename for the parsed file html_xml = xml.dom.minidom.parse(output) for node in html_xml.getElementsByTagName('meta'): # visit every node #debug print node.toxml() metatag_type = nodes.attributes["name"] if metatag_type.name == "DC.Date.Modified": metatag_date = nodes.attributes["content"] date_created = metatag_date.value() print date_created I haven't quite got up to hear in my debugging. I'll let you know if it works... RE: your questions. 1) I already have the script in bash - wanting to convert to Python :) I'm half way through I want to extract the value of the tag From apt.shansen at gmail.com Thu Dec 3 00:35:59 2009 From: apt.shansen at gmail.com (Stephen Hansen) Date: Wed, 2 Dec 2009 21:35:59 -0800 Subject: Beginner Q. interrogate html object OR file search? In-Reply-To: References: Message-ID: <7a9c25c20912022135t4a7276e0yfeba5fa63b9290e8@mail.gmail.com> On Wed, Dec 2, 2009 at 7:24 PM, Mark G wrote: > Hi all, > > I am new to python and don't yet know the libraries well. What would > be the best way to approach this problem: I have a html file parsing > script - the file sits on my harddrive. I want to extract the date > modified from the meta-data. Should I read through lines of the file > doing a string.find to look for the character patterns of the meta- > tag, or should I use a DOM type library to retrieve the html element I > want? Which is best practice? which occupies least code? > > You can probably do some string.find's and it might work almost always, HTML is funky and quite often coded badly by bad people. And I would never personally suggest anyone go anywhere near a DOM library, their life will never be happy again :) I'd get lxml -- even though you're not directly using xml. It has a html package in it too, its fast and astoundingly easy to use and fantastically featureful for future growth :) http://codespeak.net/lxml/lxmlhtml.html --S -------------- next part -------------- An HTML attachment was scrubbed... URL: From timr at probo.com Thu Dec 3 01:16:10 2009 From: timr at probo.com (Tim Roberts) Date: Wed, 02 Dec 2009 22:16:10 -0800 Subject: Question on Python as career References: <614b8dde-324b-4d54-8e73-7a96e4c0b1cf@a21g2000yqc.googlegroups.com> Message-ID: joy99 wrote: > >I am a researcher in India's one of the premier institutes.(Indian >Institute of Science,Bangalore). > >I have done one MA in Linguistics, did a PhD in Natural Language >Processing and doing a Post Doctoral now. >... >After I complete my Post Doctoral which may be only 2-3 months away, >with this knowledge can I join IT? Wouldn't you say you have already joined IT? It's difficult for me to believe that you have managed to get all the way through a PhD without cultivating close relationships with at least one private sector company. Unless you had planned to stay in research throughout your life, wouldn't that have been an obvious step along the way? >Are there any India based opportunities- as I checked Python job board >it is very less. There are very, very few full-time Python jobs anywhere in the world, although many people use Python as one tool in their toolbox. >If I get anything after completing my Post Doc with present base of >knowledge what profiles I may expect? >If I have to learn anything what they may be and how much time >generally a person needs to learn them and what may be the profile >expectancy? I am amazed that a PhD does not already have some clues about the answers to these questions. Your best plan is to start exploiting your network of contacts. If you don't already have a network of commercial contacts, then you have a long, hard road ahead of you. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From juneng603 at gmail.com Thu Dec 3 01:40:46 2009 From: juneng603 at gmail.com (junyoung) Date: Wed, 2 Dec 2009 22:40:46 -0800 (PST) Subject: how to debug extended module? References: <7nk54jF3m6bppU1@mid.uni-berlin.de> <88d05d38-1879-4cdf-92b5-2edb6192b10e@g26g2000yqe.googlegroups.com> Message-ID: <239d0346-cf19-41a5-ad65-7261149e0634@e4g2000prn.googlegroups.com> On 12?2?, ??9?54?, junyoung wrote: > On 12?1?, ??6?14?, "Diez B. Roggisch" wrote: > > > > > > > junyoung schrieb: > > > > Hi, I am a newbie who want to implement a extend module to use native > > > python language with my own shared library. > > > If it's a C shared library, don't bother extending it. Use ctypes to > > wrap it. Much easier, and no need for a compiler. > > > > to test wrapper library(extend module, name is 'test.so'), I created > > > some test-cases. > > > > There are some errors what I couldn't figure our reasons. > > > > ex) > > > SystemError: error return without exception set > > > .... > > > ... > > > This indicates that you violated the exception protocol. > > >http://docs.python.org/c-api/exceptions.html > > > > so, I ran the ddd with python and then I set test.py as a argument of > > > it. > > > > ex) > > > ddd python > > > > in ddd > > > run with arguments : test.py > > > > but in this situation, I couldn't step in my own shared library > > > (compiled as the debug mode). > > > > Is there any clear way to debug my extend module(that it, debug shared > > > library)?? > > > I do it like this: > > > # gdb python > > gdb $ set args test.py > > gdb $ run > > > You can only debug a binary program (test.py isn't one, python is). But > > trough the args, you get yours script running. > > > It *might* help to have a python debug build, I personally never needed > > that. > > > Diez > > here is my results. anyway, check this out. > > (gdb) set args connect.py > set args connect.py > (gdb) run > run > Starting program: /usr/bin/python connect.py > (no debugging symbols found) > (no debugging symbols found) > (no debugging symbols found) > [Thread debugging using libthread_db enabled] > (no debugging symbols found) > (no debugging symbols found) > (no debugging symbols found) > (no debugging symbols found) > [New Thread 0x7f619747e6e0 (LWP 23683)] > (no debugging symbols found) > (no debugging symbols found) > (no debugging symbols found) > (no debugging symbols found) > [New Thread 0x415a9950 (LWP 23686)] > [Thread 0x415a9950 (LWP 23686) exited] > [New Thread 0x415a9950 (LWP 23687)] > [Thread 0x415a9950 (LWP 23687) exited] > Traceback (most recent call last): > File "connect.py", line 25, in > main() > File "connect.py", line 18, in main > connection_test() > File "connect.py", line 15, in connection_test > cnxn.close() > SystemError: error return without exception set > > Program exited with code 01. > (gdb) > > as you see, I can't load symbol table information from gdb. > > now python is defaulted installed as release. > > my os is ubuntu > the python is installed in /usr/bin > the python version is 2.5.1 > > do i need to re-install python as debug mode? after compiling it(python) as debug mode, I could debug it ;( I don't still know why I have to compile it as debug mode to step in my own library. interesting.... From aioe.org at technicalbloke.com Thu Dec 3 02:24:03 2009 From: aioe.org at technicalbloke.com (r0g) Date: Thu, 03 Dec 2009 07:24:03 +0000 Subject: Beginner Q. interrogate html object OR file search? References: Message-ID: Mark G wrote: > Hi all, > > I am new to python and don't yet know the libraries well. What would > be the best way to approach this problem: I have a html file parsing > script - the file sits on my harddrive. I want to extract the date > modified from the meta-data. Should I read through lines of the file > doing a string.find to look for the character patterns of the meta- > tag, or should I use a DOM type library to retrieve the html element I > want? Which is best practice? which occupies least code? > > Regards, Mark Beautiful soup is the html parser of choice partly as it handles badly formed html well. http://www.crummy.com/software/BeautifulSoup/ If the date info occurs at a consistent offset from the start of the tag then you can use simple string slicing to snip out the date. If not then, as others suggest, regex is your friend. If you need to convert a date/time string back into a unix style timestamp chop the string into bits, put them into a tuple of length 9 and give that to time.mktime()... def time_to_timestamp( t ): return time.mktime( (int(t[0:4]), int(t[5:7]), int(t[8:10]), int(t[11:13]), int(t[14:16]), int(t[17:19]), 0, 0, 0) ) Note the last 3 values are hardcoded to 0, this is because most date/time strings I deal with do not encode sub second information, only YYYY/MM/DD h:m:s Roger. From aioe.org at technicalbloke.com Thu Dec 3 02:28:47 2009 From: aioe.org at technicalbloke.com (r0g) Date: Thu, 03 Dec 2009 07:28:47 +0000 Subject: Bored. References: <16097008-372c-4522-889d-a78319c3575c@b2g2000yqi.googlegroups.com> <3d634342-d98e-4023-949a-6819c74a1025@u7g2000yqm.googlegroups.com> Message-ID: Necronymouse wrote: > Thanks for reaction, I will prohably choose some project as you > said... > > > If you want to dip your toe in waters of open source contribution it looks like Gitso could use a little help pushing out their 0.6 release (which I just happen to quite want but don't have time to get involved in right now ;) Roger. From steven at REMOVE.THIS.cybersource.com.au Thu Dec 3 02:33:02 2009 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 03 Dec 2009 07:33:02 GMT Subject: Beginner Q. interrogate html object OR file search? References: Message-ID: On Wed, 02 Dec 2009 19:24:07 -0800, Mark G wrote: > Hi all, > > I am new to python and don't yet know the libraries well. What would be > the best way to approach this problem: I have a html file parsing script > - the file sits on my harddrive. I want to extract the date modified > from the meta-data. Should I read through lines of the file doing a > string.find to look for the character patterns of the meta- tag, That will probably be the fastest, simplest, and easiest to develop. But the downside is that it will be subject to false positives, if some tag happens to include text which by chance looks like your meta-data. So, strictly speaking, this approach is incorrect. > or > should I use a DOM type library to retrieve the html element I want? > Which is best practice? "Best practice" would imply DOM. As for which you use, you need to weigh up the risks of a false positive versus the convenience and speed of string matching versus the correctness of a DOM approach. > which occupies least code? Unless you're writing for an embedded system, or if the difference is vast (e.g. 300 lines versus 30) that's premature optimization. Personally, I'd use string matching or a regex, and feel guilty about it. -- Steven From aioe.org at technicalbloke.com Thu Dec 3 02:43:29 2009 From: aioe.org at technicalbloke.com (r0g) Date: Thu, 03 Dec 2009 07:43:29 +0000 Subject: Creating a local variable scope. References: <4b12f20c@dnews.tpgi.com.au> <97a101a2-1362-46f4-9308-b72e5c4ac392@s20g2000yqd.googlegroups.com> <9f5d0933-4aae-45a9-8111-84a399c493c9@b15g2000yqd.googlegroups.com> <87fx7um3kx.fsf@benfinney.id.au> Message-ID: Ben Finney wrote: > markolopa writes: > >> Hi Roger, >> > [?] >>> Long, descriptive variable names all_in_lower_case >>> Function names all in CamelCase >>> Global names are in ALL CAPS >> yes, pep8 I guess. > > Not quite: it deviates from PEP 8 on function names, which should rather > be ?lower_case_words_separated_by_underscores?. > > The ?UPPER_CASE_WORDS_WITH_UNDERSCORES? form is for ?constants?, i.e. > names that indicate they should stay bound to the same value through the > life of the program (which is the closest normal Python programs get to > a ?constant? binding). > > The ?TitleCase? form should be used only for class names. > > The ?camelCase? form is not conformant with PEP 8 at all (which makes me > glad, since it's hideous). > Heh, see! It's a spiky subject ;) Someday I'm going to found a substantial open source project just so I can force subsequent contributors to format their code the way I like it! *bwahahahaaa* :) Roger. From aioe.org at technicalbloke.com Thu Dec 3 02:55:19 2009 From: aioe.org at technicalbloke.com (r0g) Date: Thu, 03 Dec 2009 07:55:19 +0000 Subject: Help in wxpython References: <86b3db7d0912020020k51cf6bc8me0bc543214c582f1@mail.gmail.com> Message-ID: Krishnakant wrote: > On Wed, 2009-12-02 at 00:20 -0800, madhura vadvalkar wrote: >> Hi >> >> I am trying to write an PAINT like application where on the mouse >> File "C:/Python26/circle.py", line 19, in InitBuffer >> dc=wx.BufferedDC(None,self.buffer) >> AttributeError: 'SketchWindow' object has no attribute 'buffer' >> >> Please tell me what I am doing wrong. >> >> Thanks > Madhura, Sorry to be a bit off-topic, but, I would really recommend you > to use pygtk instead of wx. > For one thing, the developers at pygtk are very active (they have their > mailing list as well ) and it comes by default with python on almost all > linux distros. You can also easily install it on windows. > > Most important, the api for pygtk is closely similar to wx. > Not to mention the quick responses you will get with pygtk related > problems. > > Happy hacking. > Krishnakant. > I have to recommend to opposite, stick with wx. What's the point of tying yourself into GTK when wx works on Mac, PC and Linux? Roger. From subhakolkata1234 at gmail.com Thu Dec 3 02:59:57 2009 From: subhakolkata1234 at gmail.com (joy99) Date: Wed, 2 Dec 2009 23:59:57 -0800 (PST) Subject: Question on Python as career References: <614b8dde-324b-4d54-8e73-7a96e4c0b1cf@a21g2000yqc.googlegroups.com> Message-ID: On Dec 3, 11:16?am, Tim Roberts wrote: > joy99 wrote: > > >I am a researcher in India's one of the premier institutes.(Indian > >Institute of Science,Bangalore). > > >I have done one MA in Linguistics, did a PhD in Natural Language > >Processing and doing a Post Doctoral now. > >... > >After I complete my Post Doctoral which may be only 2-3 months away, > >with this knowledge can I join IT? > > Wouldn't you say you have already joined IT? > > It's difficult for me to believe that you have managed to get all the way > through a PhD without cultivating close relationships with at least one > private sector company. ?Unless you had planned to stay in research > throughout your life, wouldn't that have been an obvious step along the > way? > > >Are there any India based opportunities- as I checked Python job board > >it is very less. > > There are very, very few full-time Python jobs anywhere in the world, > although many people use Python as one tool in their toolbox. > > >If I get anything after completing my Post Doc with present base of > >knowledge what profiles I may expect? > >If I have to learn anything what they may be and how much time > >generally a person needs to learn them and what may be the profile > >expectancy? > > I am amazed that a PhD does not already have some clues about the answers > to these questions. ?Your best plan is to start exploiting your network of > contacts. ?If you don't already have a network of commercial contacts, then > you have a long, hard road ahead of you. > -- > Tim Roberts, t... at probo.com > Providenza & Boekelheide, Inc. I worked for quite sometime in IT, for few months I was a fellow to IBM,too. Our institute/lab has close collaboration with Carnegie Mellon or Massachussets Institute, but I ported to Python, and I am the only one in my lab using it others stick to Java. I got wonderful results doing work in Python. So, I was thinking if I could make a career in Python. And it is a room for expert Pythoner/programmers around the world. You are right, Python is seen more as a tool somepeople even find it good scripting language,too. Surely, I'll solve this on my own. Happy Day Ahead, Best Regs, Subhabrata Banerjee. From list at qtrac.plus.com Thu Dec 3 03:11:29 2009 From: list at qtrac.plus.com (Mark Summerfield) Date: Thu, 3 Dec 2009 00:11:29 -0800 (PST) Subject: Moving from Python 2 to Python 3: A 4 page "cheat sheet" References: <291d64cb-cc5c-4109-822c-84d58ed7b18b@k17g2000yqh.googlegroups.com> <351fcb4c-4e88-41b0-a0aa-b3d63832d1aa@e23g2000yqd.googlegroups.com> Message-ID: On 2 Dec, 22:49, "John Posner" wrote: > On Wed, 02 Dec 2009 13:34:11 -0500, Carsten Haese ? > > wrote: > > > With string interpolation, you don't need to do that, either. > >>>> '%*d' % (8,456) > > ' ? ? 456' > > Thanks, Carsten and Mark D. -- I'd forgotten about the use of "*" in ? > minimum-field-width specs and precision specs (doh). How about this: > > ? ?"pi={1:.{0}f} e={2:.{0}f}".format(5, math.pi, math.e) > > ? ?(result: 'pi=3.14159 e=2.71828') > > Can the Python2 %-formating facility handle this without repeating the "5" ? > argument? > > Even if it can, I stand by my original suggestion: include an example to ? > show that the arguments to str.format() can be used on both the left and ? > the right of a ":" in a replacement field. > > -John I can't squeeze another line into the last column of the last page (I already tried). However, a natural place to put this would be in the first section on the first page. But I want _common_ not _clever_, i.e., an example that shows a common use of * in % that I can then show using a nested replacement field. The idea is that people can look at the left hand column, recognize an idiom they use, and then be able to figure out from the right hand column how to do the same in Python 3. Anyway, I've come up with a tiny example and managed to squeeze it in, so hopefully it'll appear on InformIT's web site in a day or so. From list at qtrac.plus.com Thu Dec 3 03:13:28 2009 From: list at qtrac.plus.com (Mark Summerfield) Date: Thu, 3 Dec 2009 00:13:28 -0800 (PST) Subject: Moving from Python 2 to Python 3: A 4 page "cheat sheet" References: <291d64cb-cc5c-4109-822c-84d58ed7b18b@k17g2000yqh.googlegroups.com> <351fcb4c-4e88-41b0-a0aa-b3d63832d1aa@e23g2000yqd.googlegroups.com> <50c37c6253dhwild@talktalk.net> <9d290ad6-e0b8-4bfa-92c8-8209c7e933ec@a21g2000yqc.googlegroups.com> Message-ID: On 2 Dec, 20:59, MRAB wrote: > Mark Summerfield wrote: > > On 2 Dec, 19:28, David H Wild wrote: > >> In article > >> <351fcb4c-4e88-41b0-a0aa-b3d63832d... at e23g2000yqd.googlegroups.com>, > >> ? ?Mark Summerfield wrote: > > >>> I only just found out that I was supposed to give a different URL: > >>>http://www.informit.com/promotions/promotion.aspx?promo=137519 > >>> This leads to a web page where you can download the document (just by > >>> clicking the "Download Now" button), but if you _choose_ you can also > >>> enter your name and email to win some sort of prize. > >> There is a typographical fault on page 4 of this pdf file. The letter "P" > >> is missing from the word "Python" at the head of the comparison columns. > > Which is page 4? The page numbers are missing! (But the column titles > look OK.) :-) I didn't put page numbers or headers or footers on it---seemed redundant for such a short document. > > I can't see that problem---I've tried the PDF with evince, gv, > > acroread, and okular, and no missing "P" on page 4. I don't have a > > machine with RISC OS on it so I can't test on that environment! > > From aioe.org at technicalbloke.com Thu Dec 3 03:29:13 2009 From: aioe.org at technicalbloke.com (r0g) Date: Thu, 03 Dec 2009 08:29:13 +0000 Subject: pbs scripts References: Message-ID: aoife wrote: > Hi,very new.hoping to incorporate python into my postgrad. > > Basically I have 2,000 files.I want to write a script that says: > > open each file in turn > for each file: > open this pbs script and run MUSCLE (a sequence alignment tool) > on each file > close this file > move on to next file. > > any help would be great. > Aoife Hi Aoife, import os for each_pbs in os.listdir("/home/user/pbs_files/"): # loop thru dir if each_pbs[-4:].upper() == ".PBS": # check extension os.system("MUSCLE " + each_pbs) # call CLI prog I don't think you need to open or close the files if their names (As opposed to their contents) are just going to be parameters to this MUSCLE program. If you want it to look in subfolders replace 'os.listdir' with 'os.walk'. Hope this helps, if not please clarify :) Cheers, Roger. From list at qtrac.plus.com Thu Dec 3 03:44:19 2009 From: list at qtrac.plus.com (Mark Summerfield) Date: Thu, 3 Dec 2009 00:44:19 -0800 (PST) Subject: Moving from Python 2 to Python 3: A 4 page "cheat sheet" References: <291d64cb-cc5c-4109-822c-84d58ed7b18b@k17g2000yqh.googlegroups.com> Message-ID: <4ab8142d-d879-4edc-b4aa-3d803ae03463@r5g2000yqb.googlegroups.com> On 3 Dec, 01:17, Antoine Pitrou wrote: > Le Tue, 01 Dec 2009 06:03:36 -0800, Mark Summerfield a ?crit?: > > > I've produced a 4 page document that provides a very concise summary of > > Python 2<->3 differences plus the most commonly used new Python 3 > > features. It is aimed at existing Python 2 programmers who want to start > > writing Python 3 programs and want to use Python 3 idioms rather than > > those from Python 2 where the idioms differ. > [...] > > > It is available as a free PDF download (no registration or anything) > > from InformIT's website. Here's the direct link: > > This is great! > > Just one thing: > > ? Copyright ? Qtrac Ltd. 2009. All rights reserved ? > > Might I suggest that you release it under a free license instead? > (such as the CC by, CC by-sa, or the Free Art License) > > Regards > > Antoine. Good idea---I'll try. From patxi952 at gmail.com Thu Dec 3 03:46:29 2009 From: patxi952 at gmail.com (Patxi Bocos) Date: Thu, 3 Dec 2009 09:46:29 +0100 Subject: Call C program Message-ID: <9ef5cb30912030046j7c975ed1g27c92ec21334c857@mail.gmail.com> Hi!, I am developing a Python application and I need to call a C program which needs one parameter and it returns another one. How could I do it? Thanks :) -------------- next part -------------- An HTML attachment was scrubbed... URL: From aioe.org at technicalbloke.com Thu Dec 3 03:53:04 2009 From: aioe.org at technicalbloke.com (r0g) Date: Thu, 03 Dec 2009 08:53:04 +0000 Subject: Question about file objects... References: Message-ID: J wrote: > Something that came up in class... > > when you are pulling data from a file using f.next(), the file is read > one line at a time. > > What was explained to us is that Python iterates the file based on a > carriage return as the delimiter. > But what if you have a file that has one line of text, but that one > line has 16,000 items that are comma delimited? > > Is there a way to read the file, one item at a time, delimited by > commas WITHOUT having to read all 16,000 items from that one line, > then split them out into a list or dictionary?? > > Cheers > Jeff > Generators are good way of dealing with that sort of thing... http://dalkescientific.com/writings/NBN/generators.html Have the generator read in large chunks from file in binary mode then use string searching/splitting to dole out records one at a time, topping up the cache when needed. Roger. From aioe.org at technicalbloke.com Thu Dec 3 04:02:55 2009 From: aioe.org at technicalbloke.com (r0g) Date: Thu, 03 Dec 2009 09:02:55 +0000 Subject: Question on Python as career References: <614b8dde-324b-4d54-8e73-7a96e4c0b1cf@a21g2000yqc.googlegroups.com> Message-ID: Tim Roberts wrote: > joy99 wrote: >> I am a researcher in India's one of the premier institutes.(Indian >> Institute of Science,Bangalore). >> >> I have done one MA in Linguistics, did a PhD in Natural Language >> Processing and doing a Post Doctoral now. >> ... >> After I complete my Post Doctoral which may be only 2-3 months away, >> with this knowledge can I join IT? > > Wouldn't you say you have already joined IT? > > It's difficult for me to believe that you have managed to get all the way > through a PhD without cultivating close relationships with at least one > private sector company. Unless you had planned to stay in research > throughout your life, wouldn't that have been an obvious step along the > way? > >> Are there any India based opportunities- as I checked Python job board >> it is very less. > > There are very, very few full-time Python jobs anywhere in the world, > although many people use Python as one tool in their toolbox. > >> If I get anything after completing my Post Doc with present base of >> knowledge what profiles I may expect? >> If I have to learn anything what they may be and how much time >> generally a person needs to learn them and what may be the profile >> expectancy? > > I am amazed that a PhD does not already have some clues about the answers > to these questions. Your best plan is to start exploiting your network of > contacts. If you don't already have a network of commercial contacts, then > you have a long, hard road ahead of you. Getting involved in an open source project or two may bolster your CV and help you get your foot in the door. Employers always like a bit of real worlds experience - some even insist on it. There are thousands of open source projects using python you could contribute to, or you could found your own. You sound like a bright guy, maybe you could be the next Bram Cohen? Roger. From aioe.org at technicalbloke.com Thu Dec 3 04:17:01 2009 From: aioe.org at technicalbloke.com (r0g) Date: Thu, 03 Dec 2009 09:17:01 +0000 Subject: Reading a file that is changing and getting the new lines References: Message-ID: Ouray Viney wrote: > Hi: > > Problem: > ========= > I want to read a ASCII text file that can have data appended to it. I > have hacked some code together that handles the basics, but it falls > short. My code doesn't read in the new lines that could have been > added to the end of the file. Not python's fault, more that I don't > know how to do it in python. > > Example scenario: As the python script is running a user/application > adds new entries to the end of the test case file, example, adds the > following to the file. > > test4 > test5 > test6 > > The python code below, won't pick these changes up. > > Analysis: > ======== > I understand why my code doesn't handle the addition of new data. > This is simply because the os.open reads all the lines in the > beginning and since the data is added after that, the for loop doesn't > iterate through it since it doesn't know about it. Please note, my > code is not pretty and isn't at all advanced. > > Code: > ====== > import os,string,sys,time > > # define locals > tcListFile="testcase_list.txt" > fh=open(tcListFile,"r") > tcList=fh.readlines() > fh.close() > > for tc in tcList: > print tc.strip() > print "sleeping for 2 seconds" > time.sleep(2) > > # close the file handle > fh.close() > > text file: > ====== > test1 > test2 > test3 > > Question: > ========= > What is the best way to handle this type of scenario using python? Read your file once. Make a note of the length (X) Close the file Setup a loop with a sleep at the end. Each time round check the file size If it has increased, make a note of it (Y) and open the file, seek to X and read Y - X bytes This gives you the new data, you can then append it to the inital read or whatever. Do bar in mind though that all OS's buffer IO so the program that's generating the file might have a different view of it than your python script i.e. program A might output 300 chars to file but they may not be written to disk until the buffer receives 4096 chars. If this might be a problem to you make sure the program generating the data flushes the cache after every write (sys.stdout.flush() in python). Roger. From jspies at sun.ac.za Thu Dec 3 04:50:42 2009 From: jspies at sun.ac.za (Johann Spies) Date: Thu, 3 Dec 2009 11:50:42 +0200 Subject: peppy In-Reply-To: References: Message-ID: <20091203095042.GE5899@sun.ac.za> On Tue, Dec 01, 2009 at 07:35:52AM +0000, Nobody wrote: > On Tue, 01 Dec 2009 08:51:20 +0200, Johann Spies wrote: > > > After reading about peppy on Freshmeat I decided to try it out after > > installing it using easy_install. But: > > > > $ peppy > > > File "/usr/lib/python2.5/site-packages/peppy-0.13.2-py2.5.egg/peppy/lib/multikey.py", line 120, in > > 'C-': wx.ACCEL_CMD, > > AttributeError: 'module' object has no attribute 'ACCEL_CMD' > > wx.ACCEL_CMD exists in wxPython 2.8 but not in 2.6, so I'd guess that > peppy requires 2.8 but you have 2.6 (or if you have both, 2.6 is the > default). > > > This is on Debian squeeze. > > > > How do I solve this? > > First, ensure that wxPython 2.8 is installed. If you have both 2.6 and > 2.8, you may need to add the following at the beginning of the main > "peppy" script: > > import wxversion > wxversion.select("2.8") > > This will cause subsequent "import wx" commands to use wxPython 2.8. Thanks. That was indeed the problem that I had both 2.6 and 2.8 installed. Regards Johann -- Johann Spies Telefoon: 021-808 4599 Informasietegnologie, Universiteit van Stellenbosch "What shall we then say to these things? If God be for us, who can be against us?" Romans 8:31 From news at schwertberger.de Thu Dec 3 05:09:06 2009 From: news at schwertberger.de (Dietmar Schwertberger) Date: Thu, 03 Dec 2009 11:09:06 +0100 Subject: Help in wxpython In-Reply-To: References: <86b3db7d0912020020k51cf6bc8me0bc543214c582f1@mail.gmail.com> Message-ID: <7nph37F3mavn4U1@mid.individual.net> On Wed, 2009-12-02 at 00:20 -0800, madhura vadvalkar wrote: >> def InitBuffer(self): >> >> size=self.GetClientSize() >> self.Buffer=wx.EmptyBitmap(size.width,size.height) >> dc=wx.BufferedDC(None,self.buffer) >> dc.SetBackground(wx.Brush(self.GetBackgroundColour())) >> dc.Clear() >> self.Drawcircle(dc) >> self.reInitBuffer=False >> I am getting the following error: >> >> Traceback (most recent call last): >> File "C:/Python26/circle.py", line 42, in >> frame=SketchFrame(None) >> File "C:/Python26/circle.py", line 38, in __init__ >> self.sketch = SketchWindow(self, -1) >> File "C:/Python26/circle.py", line 12, in __init__ >> self.InitBuffer() >> File "C:/Python26/circle.py", line 19, in InitBuffer >> dc=wx.BufferedDC(None,self.buffer) >> AttributeError: 'SketchWindow' object has no attribute 'buffer' >> >> Please tell me what I am doing wrong. As the traceback suggests, self.buffer does not exist. You need to write self.Buffer. I did not have a further look or try the code. Did you have a look at the wxPython demo? The demo "Core Windows/Controls -> ScrolledWindow" is probably very similar to what you want. Krishnakant schrieb: > Madhura, Sorry to be a bit off-topic, but, I would really recommend you > to use pygtk instead of wx. > For one thing, the developers at pygtk are very active (they have their > mailing list as well ) and it comes by default with python on almost all > linux distros. You can also easily install it on windows. > > Most important, the api for pygtk is closely similar to wx. > Not to mention the quick responses you will get with pygtk related > problems. That's also true for wxPython on the related mail lists: http://www.wxpython.org/maillist.php Regards, Dietmar From wentland at cl.uni-heidelberg.de Thu Dec 3 05:40:44 2009 From: wentland at cl.uni-heidelberg.de (Wolodja Wentland) Date: Thu, 3 Dec 2009 11:40:44 +0100 Subject: Moving from Python 2 to Python 3: A 4 page "cheat sheet" In-Reply-To: <9eb46f34-a9aa-46ef-98d4-1dbee0e409c0@m3g2000yqf.googlegroups.com> References: <291d64cb-cc5c-4109-822c-84d58ed7b18b@k17g2000yqh.googlegroups.com> <4b156121$1@dnews.tpgi.com.au> <3851f624-f2cd-40fb-a898-cfd08d5cf0fa@e7g2000vbi.googlegroups.com> <9eb46f34-a9aa-46ef-98d4-1dbee0e409c0@m3g2000yqf.googlegroups.com> Message-ID: <20091203104044.GB3430@kinakuta.local> On Wed, Dec 02, 2009 at 08:03 -0800, Mark Summerfield wrote: > On Dec 2, 11:20?am, Wolodja Wentland > > It would be quite nice if you could mark all the Python 3 idioms that > > work in Python 2.X as well. This would allow readers that are still using > > Python 2.X and are used to the 'old way' to adapt their coding style > > accordingly. You could just add a little (2.X) after the idiom for > > example. > Yes it would be nice, but it isn't quite so simple. > To take sorted() as just one example, it was introduced in 2.4 so > arguably using it isn't valid/idiomatic for Python 2.x programs where > you care about backwards compatibility for the Python 2.x series... Yes, which is why you could include a 2.X and people who target, say current +/- 0.1 can choose their poison. > But my main reason for not wanting to do this is that the document is > aimed at people who want to write Python 3, not to encourage people to > stick with 2:-) I actually think that it is the other way round. People should get familiar with py3 features even if they are not yet ready to "abandon" py2 (yet). I also think that using some of the backported/supported features might spur interest in features that are 'py3 only' and therefore encourage the adoption of py3. It would also be nice to have a summary of things people can do *now* if they want to keep the changes from 2to3 to a minimum, which will be with us for some time. But that is not something *you* have to write .. :-) -- .''`. Wolodja Wentland : :' : `. `'` 4096R/CAF14EFC `- 081C B7CD FF04 2BA9 94EA 36B2 8B7F 7D30 CAF1 4EFC -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 836 bytes Desc: Digital signature URL: From astley.lejasper at gmail.com Thu Dec 3 05:42:56 2009 From: astley.lejasper at gmail.com (Astley Le Jasper) Date: Thu, 3 Dec 2009 02:42:56 -0800 (PST) Subject: Noob thread lock question References: <5f776ec1-9b8c-45f7-b4e5-ff140638d6bf@33g2000vbe.googlegroups.com> <7nnubjF3jl6o1U1@mid.uni-berlin.de> <4b16d3ea$0$1636$742ec2ed@news.sonic.net> Message-ID: <12110118-3e2b-4d5b-a9e3-853665edccb7@r24g2000yqd.googlegroups.com> Cheers for the responses. ALJ From Nadav.C at qualisystems.com Thu Dec 3 06:02:10 2009 From: Nadav.C at qualisystems.com (Nadav Chernin) Date: Thu, 3 Dec 2009 13:02:10 +0200 Subject: Help with function prototype Message-ID: <97FB089C6E1F404CB0132AC3BB3E5C2701948253@exchange.qualisystems.local> Hi, all In past I asked about module - inspect, that can't to get me prototype of C-implemented functions ( usually all built-in functions ). But, still I see that all Python Editors ( IDLE for example ) can to show prototype of built-in functions - by tooltip. When you print for example: sum(, you see what kind of parameters you must to enter. So, how IDLE know it? Thanks, Nadav -------------- next part -------------- An HTML attachment was scrubbed... URL: From victorsubervi at gmail.com Thu Dec 3 06:07:55 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Thu, 3 Dec 2009 06:07:55 -0500 Subject: Insane Problem In-Reply-To: <4B16D739.5080408@mrabarnett.plus.com> References: <4dc0cfea0912021218g797f782esa2c174923b6ac492@mail.gmail.com> <4B16D739.5080408@mrabarnett.plus.com> Message-ID: <4dc0cfea0912030307j7556eb06j469ccc4e6a29d1ee@mail.gmail.com> On Wed, Dec 2, 2009 at 4:08 PM, MRAB wrote: > Victor Subervi wrote: > >> Hi; >> I have spent 2-3 hours trying to track this bug. Here's the code snippet: >> >> form = cgi.FieldStorage() >> fn = getattr(options, 'products') >> ourOptionsNames = [] >> optionsNames, doNotUse = fn('names') >> for name in optionsNames: >> test = table + '-' + name >> print test >> check = form.getfirst(test, '') >> print check >> if check != '': >> ourOptionsNames.append(name) >> Now, when it looks through with test=='products', it doesn't report that >> any of the values from the form are checked. However, when I explicitly >> write out something like: >> print form.getfirst('products-sizes', '') >> which I checked on the form from the referring page, it does in fact print >> out! My test prints show that 'products-sizes' is being passed to "check" >> and should therefore be appended to "ourOptionsNames". But it isn't! What am >> I missing here?? >> >> What do the print statements actually print? Please copy and paste their > output. > For the part in question they print __nothing__. That's the point. V -------------- next part -------------- An HTML attachment was scrubbed... URL: From lie.1296 at gmail.com Thu Dec 3 06:16:12 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Thu, 03 Dec 2009 22:16:12 +1100 Subject: Noob thread lock question In-Reply-To: <5f776ec1-9b8c-45f7-b4e5-ff140638d6bf@33g2000vbe.googlegroups.com> References: <5f776ec1-9b8c-45f7-b4e5-ff140638d6bf@33g2000vbe.googlegroups.com> Message-ID: <4b179e6d$1@dnews.tpgi.com.au> On 12/3/2009 6:33 AM, Astley Le Jasper wrote: > I have a number of threads that write to a database. I have created a > thread lock, but my question is this: > > - If one thread hits a lock, do a) all the other threads stop, or b) > just the ones that come to the same lock? Just the ones the comes to the same lock, but... Though it should not be a problem since your threads are I/O bound, don't forget about the GIL (Global Interpeter Lock). A decent DB API should release the GIL when writing/reading. > - I presume that the answer is b. In which case do the threads stop > only if they come to the same instance of a lock. For example, you > could have a lock instance for one database and another instance for > another database (first_db_thread_lock = threading.RLock() .... > second_db_thread_lock = threading.RLock()). > > I appreciate this is a bit of a noob question, but I didn't want to > assume anything. > > ALJ From lie.1296 at gmail.com Thu Dec 3 06:16:37 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Thu, 03 Dec 2009 22:16:37 +1100 Subject: Creating a local variable scope. In-Reply-To: <87fx7um3kx.fsf@benfinney.id.au> References: <4b12f20c@dnews.tpgi.com.au> <97a101a2-1362-46f4-9308-b72e5c4ac392@s20g2000yqd.googlegroups.com> <9f5d0933-4aae-45a9-8111-84a399c493c9@b15g2000yqd.googlegroups.com> <87fx7um3kx.fsf@benfinney.id.au> Message-ID: <4b179e86$1@dnews.tpgi.com.au> On 12/2/2009 2:56 PM, Ben Finney wrote: > The ?camelCase? form is not conformant with PEP 8 at all (which makes me > glad, since it's hideous). For some reason, every time I look at a unittest code, I was thinking of Java... and not just because it's modeled after JUnitTest. From ben+python at benfinney.id.au Thu Dec 3 06:33:20 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Thu, 03 Dec 2009 22:33:20 +1100 Subject: Creating a local variable scope. References: <4b12f20c@dnews.tpgi.com.au> <97a101a2-1362-46f4-9308-b72e5c4ac392@s20g2000yqd.googlegroups.com> <9f5d0933-4aae-45a9-8111-84a399c493c9@b15g2000yqd.googlegroups.com> <87fx7um3kx.fsf@benfinney.id.au> <4b179e86$1@dnews.tpgi.com.au> Message-ID: <87eincl2bj.fsf@benfinney.id.au> Lie Ryan writes: > On 12/2/2009 2:56 PM, Ben Finney wrote: > > The ?camelCase? form is not conformant with PEP 8 at all (which makes me > > glad, since it's hideous). > > For some reason, every time I look at a unittest code, I was thinking > of Java... and not just because it's modeled after JUnitTest. Right, there are a number of standard library modules that don't conform to PEP 8; in many cases that's because the module in question was largely written before PEP 8. -- \ ?When we pray to God we must be seeking nothing ? nothing.? | `\ ?Saint Francis of Assisi | _o__) | Ben Finney From fetchinson at googlemail.com Thu Dec 3 06:54:50 2009 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Thu, 3 Dec 2009 12:54:50 +0100 Subject: Call C program In-Reply-To: <9ef5cb30912030046j7c975ed1g27c92ec21334c857@mail.gmail.com> References: <9ef5cb30912030046j7c975ed1g27c92ec21334c857@mail.gmail.com> Message-ID: > I am developing a Python application and I need to call a C program which > needs one parameter and it returns another one. You mean you need to call a C function from python? Here is an example with a C function that adds two integers: /***************************** call this source file mymod.c ***********************************/ #include /* This is the function 'add' that will be accessible from python */ static PyObject *add( PyObject * self, PyObject * args ) { const int i, j; int k; if( !PyArg_ParseTuple( args, "ii", &i, &j ) ) return NULL; k = i + j; return Py_BuildValue( "i", k ); } /* Here we tell python that the function 'add' should indeed be accessible from python */ static PyMethodDef AddMethods[] = { {"add", add, METH_VARARGS, "Add two integers."}, {NULL, NULL, 0, NULL} }; /* This tells python that we have an extension module called 'mymod' */ PyMODINIT_FUNC initmymod( void ) { ( void ) Py_InitModule( "mymod", AddMethods ); } /************************************************************************/ Once we have the above C file with the function 'add' we create a setup.py for compiling it: ########################################### from distutils.core import setup, Extension # we define that our C function should live in the python module mymod mymod = Extension( 'mymod', sources = ['mymod.c']) # this will tell setup that we want to build an extension module setup ( name = 'PackageName', version = '1.0', description = 'This is a demo package', ext_modules = [ mymod ] ) ########################################### Okay, so we have mymod.c and setup.py. You compile it with python setup.py build Now look into the 'build' directory, it will contain another directory called lib.something. In this directory there is the compiled mymod.so shared object file, which is ready to use: [fetchinson at fetch lib.linux-x86_64-2.6]$ python Python 2.6.1 (r261:67515, Mar 29 2009, 14:31:47) [GCC 4.1.2 20070925 (Red Hat 4.1.2-33)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import mymod >>> mymod.add(1,2) 3 >>> dir(mymod) ['__doc__', '__file__', '__name__', '__package__', 'add'] Have fun! Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From mal at egenix.com Thu Dec 3 07:04:48 2009 From: mal at egenix.com (M.-A. Lemburg) Date: Thu, 03 Dec 2009 13:04:48 +0100 Subject: python bijection In-Reply-To: References: <5a99def7-e182-4782-9054-f1035affa34d@x5g2000prf.googlegroups.com> <7n39ojF3jj6iuU1@mid.individual.net> <12c55890-118d-4655-b6c0-c908c9734a17@a32g2000yqm.googlegroups.com> <85100df7-a8b0-47e9-a854-ba8a8a2f3b98@r31g2000vbi.googlegroups.com> Message-ID: <4B17A960.1090700@egenix.com> Raymond Hettinger wrote: > [Joshua Bronson] >> Raymond, do you think there might be any future in including a built- >> in bidict data structure in Python? > > I don't think so. There are several forces working against it: > > * the recipe is new, so it hasn't had a chance to mature > or to gain a fan club. > > * there are many approaches to the solving the problem and > there is no reason to assume this one is the best. > > * it extends the language with arcane syntax tricks instead of > using the language as designed by Guido. That makes it harder > to learn and remember. > > * we've already got one (actually two). The two dictionary approach > uses plain python, requires no new learning, and is more flexible. > Also, sqlite3 provides another way to use multiple lookups to a > single record. The database approach is much more general > (extending to trijections, allowing multiple sort orders, > providing persistence, etc). > > * the semantics of a bijection aren't obvious: > > b['x'] = 'ex' # first record: ('x', 'ex') > b['y'] = 'why' # second record: ('y', 'why') > b[:'why'] = 'x' # do two records collapse into one? is there > an error? > > * the proposed syntax doesn't address the issue covered in my previous > post. > Since bijections are symmetrical, they do not have an obvious > direction > (which is the primary key, the husband or the wife?). The syntax > needs to > allow user names to make it clear which is being accessed: > > marriages.h2w['john'] = 'amy' > marriages.w2h['amy'] = 'john' > > Contrast this with: > > marriages['jordan'] = 'taylor' # are you sure you got the > order correct? > marriages[:'taylor'] = 'jordan' # this is easy to get backwards I think the only major CS data type missing from Python is some form of (fast) directed graph implementation ? la kjGraph: http://gadfly.sourceforge.net/kjbuckets.html With these, you can easily build all sorts of relations between objects and apply fast operations on them. In fact, it should then be possible to build a complete relational database in Python (along the lines of Gadfly). -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Dec 03 2009) >>> 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 our new mxODBC.Connect Python Database Interface 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 http://www.egenix.com/company/contact/ From subhakolkata1234 at gmail.com Thu Dec 3 07:05:20 2009 From: subhakolkata1234 at gmail.com (joy99) Date: Thu, 3 Dec 2009 04:05:20 -0800 (PST) Subject: Question on Python as career References: <614b8dde-324b-4d54-8e73-7a96e4c0b1cf@a21g2000yqc.googlegroups.com> Message-ID: On Dec 3, 2:02?pm, r0g wrote: > Tim Roberts wrote: > > joy99 wrote: > >> I am a researcher in India's one of the premier institutes.(Indian > >> Institute of Science,Bangalore). > > >> I have done one MA in Linguistics, did a PhD in Natural Language > >> Processing and doing a Post Doctoral now. > >> ... > >> After I complete my Post Doctoral which may be only 2-3 months away, > >> with this knowledge can I join IT? > > > Wouldn't you say you have already joined IT? > > > It's difficult for me to believe that you have managed to get all the way > > through a PhD without cultivating close relationships with at least one > > private sector company. ?Unless you had planned to stay in research > > throughout your life, wouldn't that have been an obvious step along the > > way? > > >> Are there any India based opportunities- as I checked Python job board > >> it is very less. > > > There are very, very few full-time Python jobs anywhere in the world, > > although many people use Python as one tool in their toolbox. > > >> If I get anything after completing my Post Doc with present base of > >> knowledge what profiles I may expect? > >> If I have to learn anything what they may be and how much time > >> generally a person needs to learn them and what may be the profile > >> expectancy? > > > I am amazed that a PhD does not already have some clues about the answers > > to these questions. ?Your best plan is to start exploiting your network of > > contacts. ?If you don't already have a network of commercial contacts, then > > you have a long, hard road ahead of you. > > Getting involved in an open source project or two may bolster your CV > and help you get your foot in the door. Employers always like a bit of > real worlds experience - some even insist on it. There are thousands of > open source projects using python you could contribute to, or you could > found your own. You sound like a bright guy, maybe you could be the next > Bram Cohen? > > Roger.- Hide quoted text - > > - Show quoted text - Thanks for another nice message. Bright? I don't know, all I try to do my work and get some results. That's upto the world to say. Happy day ahead, Best Regards, Subhabrata. From jeanmichel at sequans.com Thu Dec 3 07:52:41 2009 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Thu, 03 Dec 2009 13:52:41 +0100 Subject: Declaring a class level nested class? In-Reply-To: <6232b87e-f6a5-497b-a01f-d545c09ad4a8@d21g2000yqn.googlegroups.com> References: <6232b87e-f6a5-497b-a01f-d545c09ad4a8@d21g2000yqn.googlegroups.com> Message-ID: <4B17B499.7080204@sequans.com> cmckenzie wrote: > Hi. > > I'm new to Python, but I've managed to make some nice progress up to > this point. After some code refactoring, I ran into a class design > problem and I was wondering what the experts thought. It goes > something like this: > > class module: > nestedClass > > def __init__(): > self.nestedClass = nested() > print self.nestedClass.nestedVar > > class nested(): > nestedVar = 1 > def __init__(self): > print "Initialized..." > > I can't figure out what the correct way to construct the "nested" > class so it can belong to "module". > > I want a class level construct of "nested" to belong to "module", but > I keep getting nestedClass isn't defined. > > My example isn't great or 100% accurate, but I hope you get the idea. > > Thanks. > class module: class nested: nestedVar = 1 def __init__(self): print "Initialized..." def __init__(self): self.nestedClass = module.nested() print self.nestedClass.nestedVar Python will not look into the current class scope when trying to resolve "nested", that is why the explicit call including the scope is required. The code above runs fine with python 2.5. Jean-Michel From victorsubervi at gmail.com Thu Dec 3 08:02:59 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Thu, 3 Dec 2009 08:02:59 -0500 Subject: Insane Problem In-Reply-To: <4dc0cfea0912030307j7556eb06j469ccc4e6a29d1ee@mail.gmail.com> References: <4dc0cfea0912021218g797f782esa2c174923b6ac492@mail.gmail.com> <4B16D739.5080408@mrabarnett.plus.com> <4dc0cfea0912030307j7556eb06j469ccc4e6a29d1ee@mail.gmail.com> Message-ID: <4dc0cfea0912030502x1532319dy92e6f62868b6ef5e@mail.gmail.com> On Thu, Dec 3, 2009 at 6:07 AM, Victor Subervi wrote: > On Wed, Dec 2, 2009 at 4:08 PM, MRAB wrote: > >> Victor Subervi wrote: >> >>> Hi; >>> I have spent 2-3 hours trying to track this bug. Here's the code snippet: >>> >>> form = cgi.FieldStorage() >>> fn = getattr(options, 'products') >>> ourOptionsNames = [] >>> optionsNames, doNotUse = fn('names') >>> for name in optionsNames: >>> test = table + '-' + name >>> print test >>> check = form.getfirst(test, '') >>> print check >>> if check != '': >>> ourOptionsNames.append(name) >>> Now, when it looks through with test=='products', it doesn't report that >>> any of the values from the form are checked. However, when I explicitly >>> write out something like: >>> print form.getfirst('products-sizes', '') >>> which I checked on the form from the referring page, it does in fact >>> print out! My test prints show that 'products-sizes' is being passed to >>> "check" and should therefore be appended to "ourOptionsNames". But it isn't! >>> What am I missing here?? >>> >>> What do the print statements actually print? Please copy and paste their >> output. >> > > For the part in question they print __nothing__. That's the point. > V > I believe I mentioned in my first post that the "print test" does print the exact fields being called from the referring page. The "print check" prints nothing. Another thing that's strange is that there are two tables of fields in the referrer page; it will print the first of those tables--whichever of the two I choose--but not the latter. Perhaps this is a bug in the cgi interface? Perhaps I should migrate this to mod_python? TIA, V -------------- next part -------------- An HTML attachment was scrubbed... URL: From jeanmichel at sequans.com Thu Dec 3 08:13:19 2009 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Thu, 03 Dec 2009 14:13:19 +0100 Subject: Declaring a class level nested class? In-Reply-To: <50697b2c0912022113p14360322gef6706e7067c8d03@mail.gmail.com> References: <6232b87e-f6a5-497b-a01f-d545c09ad4a8@d21g2000yqn.googlegroups.com> <50697b2c0912022113p14360322gef6706e7067c8d03@mail.gmail.com> Message-ID: <4B17B96F.4090903@sequans.com> Chris Rebert wrote: > On Wed, Dec 2, 2009 at 8:55 PM, cmckenzie wrote: > >> Hi. >> >> I'm new to Python, but I've managed to make some nice progress up to >> this point. After some code refactoring, I ran into a class design >> problem and I was wondering what the experts thought. It goes >> something like this: >> >> class module: >> nestedClass >> >> def __init__(): >> self.nestedClass = nested() >> print self.nestedClass.nestedVar >> >> class nested(): >> nestedVar = 1 >> def __init__(self): >> print "Initialized..." >> >> I can't figure out what the correct way to construct the "nested" >> class so it can belong to "module". >> >> I want a class level construct of "nested" to belong to "module", but >> I keep getting nestedClass isn't defined. >> > > Here's the scoping reason why it fails (remember that the nested class > is a class variable of the containing class): > > [snip interesting reminder/faq] > > However, there's pretty much no reason to nest classes anyway in > Python (it's not Java!). A little bit off topic,ahere is a nested class pattern I'm using quite often : class Device """Holds the different device services.""" class OS: # UPPERCASE means it holds constants """Operating system of one device.""" VXWORKS = 'vxWorks' ECOS = 'ecos' def init(self, _os = None): self.os = _os device = Device(Device.OS.VXWORKS) Whenever I get a Device instance in my code I can match its OS without tedious imports: # no "from whatever import Device" is required if device.os is device.OS.VXWORKS: print 'you are using vxWorks' I'm using this pattern whenever I can now: 1/ it removes all magically 'inside code' defined strings or numbers, only class attributes are used. 2/ if required, it allows to write complete and detailed documentation for nested class constants 3/ you can match attributes with the nested class values without further import, everything is accessible from the instance itself JM From dksreddy at gmail.com Thu Dec 3 08:17:37 2009 From: dksreddy at gmail.com (Sandy) Date: Thu, 3 Dec 2009 05:17:37 -0800 (PST) Subject: prolog with python References: Message-ID: <6e8c880b-a9f4-4063-8e77-e77679f6b54c@m3g2000yqf.googlegroups.com> you can also look at swi-prolog and python bridge: pyswip. I am using it and its very nice though it has some issues with 64-bit os. http://code.google.com/p/pyswip/ - dksr On Dec 3, 2:56?am, Chris Rebert wrote: > On Wed, Dec 2, 2009 at 6:47 PM, William Heath wrote: > > Hi All, > > > I have the following prolog program that I would really like to be able to > > run in python in some elegant way: > >From googling: > > http://pyke.sourceforge.net/http://code.activestate.com/recipes/303057/ > > Cheers, > Chris > --http://blog.rebertia.com From patrick.just4fun at gmail.com Thu Dec 3 08:32:58 2009 From: patrick.just4fun at gmail.com (Patrick Sabin) Date: Thu, 03 Dec 2009 14:32:58 +0100 Subject: Call C program In-Reply-To: <9ef5cb30912030046j7c975ed1g27c92ec21334c857@mail.gmail.com> References: <9ef5cb30912030046j7c975ed1g27c92ec21334c857@mail.gmail.com> Message-ID: <4B17BE0A.9020800@gmail.com> Have a look at the ctypes module http://python.net/crew/theller/ctypes/tutorial.html e.g.: from ctypes import * cdll.LoadLibrary("libc.so.6") libc = CDLL("libc.so.6") print libc.rand() print libc.atoi("34") - Patrick Patxi Bocos wrote: > Hi!, > > I am developing a Python application and I need to call a C program > which needs one parameter and it returns another one. > > How could I do it? > > Thanks :) > From michaelmossey at gmail.com Thu Dec 3 08:44:37 2009 From: michaelmossey at gmail.com (Michael Mossey) Date: Thu, 3 Dec 2009 05:44:37 -0800 (PST) Subject: Organization of GUIs Message-ID: <424dcb65-735c-4779-ae0a-5c4e662b24ac@b36g2000prf.googlegroups.com> I have a question about typical organization of GUIs. I will be using PyQt. I have mostly used Python and C++ in my professional life, but I just took an 8 month detour into using a functional programming language called Haskell. Haskell is "pure" meaning that for the most part data is not mutable, or if it is mutable, access to it is controlled very carefully. This got me thinking about how mutable data can make program behavior complicated and difficult to understood/prove- correct. I am returning to Python and PyQt for my next project, but I come away inspired to do things a little differently. For example, in GUIs I've written in the past, typically there are a lot of GUI objects (windows, data repositories, etc.) that "talk" to each other. One object might send messages about a change in its state to other objects that are watching it. I am now wondering if I should write a GUI so that everything is in a true hierarchy, rather than a tangle of objects with democratic relationships---and more specifically, that messages (which may cause state to be changed in the receiver of the message) should first go up the hierarchy until they reach the right level, and then down to the ultimate receiver of the message. This way a parent object in the hierarchy has complete visibility and control of messages passing between its children, leading to the possibility of consolidating the code and documentation about the children's mutability in one place (the parent). But honestly, I have never really studied how good existing GUI programs are organized. Always flew by the seat of my pants. So I'm interested in someone has thoughts about this, maybe can point me to a good book, etc. Thanks, Mike From list at qtrac.plus.com Thu Dec 3 08:45:54 2009 From: list at qtrac.plus.com (Mark Summerfield) Date: Thu, 3 Dec 2009 05:45:54 -0800 (PST) Subject: Moving from Python 2 to Python 3: A 4 page "cheat sheet" References: <291d64cb-cc5c-4109-822c-84d58ed7b18b@k17g2000yqh.googlegroups.com> <351fcb4c-4e88-41b0-a0aa-b3d63832d1aa@e23g2000yqd.googlegroups.com> <50c37c6253dhwild@talktalk.net> <9d290ad6-e0b8-4bfa-92c8-8209c7e933ec@a21g2000yqc.googlegroups.com> <50c3876378dhwild@talktalk.net> Message-ID: <9692a312-9f61-4610-a335-ee9e97e5fece@r5g2000yqb.googlegroups.com> On 2 Dec, 21:28, David H Wild wrote: > In article > <9d290ad6-e0b8-4bfa-92c8-8209c7e93... at a21g2000yqc.googlegroups.com>, > ? ?Mark Summerfield wrote: > > > > There is a typographical fault on page 4 of this pdf file. The letter > > > "P" is missing from the word "Python" at the head of the comparison > > > columns. > > I can't see that problem---I've tried the PDF with evince, gv, > > acroread, and okular, and no missing "P" on page 4. I don't have a > > machine with RISC OS on it so I can't test on that environment! > > Using a different pdf reader, on the same machine, the letters are there. > It's an odd thing, because it's only that one page that has the problem. I've never had a problem with my PDFs before. However I use the lout typesetting system and I suspect that it has some bugs relating to external links (which normally I don't use but which I've put in this particular document). Anyway, glad you found something that could read it:-) BTW issue #2 is now up. This has the file() vs. open() line. Hopefully issue #3 will follow tomorrow or early next week with a line about %*d. > Thanks, anyway. > > -- > David Wild using RISC OS on broadbandwww.davidhwild.me.uk From shahmed at sfwmd.gov Thu Dec 3 08:51:05 2009 From: shahmed at sfwmd.gov (Ahmed, Shakir) Date: Thu, 3 Dec 2009 08:51:05 -0500 Subject: memory error In-Reply-To: <6e8c880b-a9f4-4063-8e77-e77679f6b54c@m3g2000yqf.googlegroups.com> References: <6e8c880b-a9f4-4063-8e77-e77679f6b54c@m3g2000yqf.googlegroups.com> Message-ID: <1482CDE5CD38BC4B99F6182262ADCB2925FAA4@EXCHVS02.ad.sfwmd.gov> I am getting a memory error while executing a script. Any idea is highly appreciated. Error message: " The instruction at "0x1b009032" referenced memory at "0x00000804:, The memory could not be "written" This error is appearing and I have to exit from the script. Thanks sk -------------- next part -------------- A non-text attachment was scrubbed... Name: error_py.bmp Type: image/bmp Size: 275954 bytes Desc: error_py.bmp URL: From lie.1296 at gmail.com Thu Dec 3 09:16:50 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Fri, 04 Dec 2009 01:16:50 +1100 Subject: How to set object parameters nicely? In-Reply-To: References: <83ced7d2-8d75-4e41-a60b-7c0c73515129@m38g2000yqd.googlegroups.com> Message-ID: <4b17c8c4$1@dnews.tpgi.com.au> On 12/2/2009 10:26 AM, allen.fowler wrote: > I've tried this, but have found two issues: > > 1) I can't set default values. > 2) I can't set required values. > > In both of the above cases, if the object is created without the > "exact" dict() I expect, all the assumption my methods make about what > is available in "self" fall apart. > You can inspect the dict, something like: def __init__(self, **kwargs): required = ['p1', 'p2', 'p3'] optional = {'p4': 'foo', 'p5': 'bar'} if any(par not in kwargs for par in required): raise TypeError('required parameter not set') for par in optional: if par not in kwargs: kwargs[par] = optional[par] # ... do work ... Tips: turn this parameter checker into a @decorator But generally, as Diez pointed out your class may be doing too much. Try splitting it into smaller classes. Passing too much parameter is an indication of a God Object (or demi-god) http://en.wikipedia.org/wiki/God_object "He" just knows too much. === Unpythonic warning: Java-style code would use several separate initializers that would be called in order before the object is in a ready state (but never in an invalid state [!]). The first initializer merely set all the attributes into some valid state. This is an *anti-pattern* in python. Avoid it. def __init__(self): self.p1 = '' self.p2 = 0 self.p3 = [] def init_name(self, name): self.p1 = name etc, etc... === From astley.lejasper at gmail.com Thu Dec 3 09:20:29 2009 From: astley.lejasper at gmail.com (Astley Le Jasper) Date: Thu, 3 Dec 2009 06:20:29 -0800 (PST) Subject: Noob thread lock question References: <5f776ec1-9b8c-45f7-b4e5-ff140638d6bf@33g2000vbe.googlegroups.com> <4b179e6d$1@dnews.tpgi.com.au> Message-ID: When you say don't forget about the GIL, what should I not be forgetting? I'm using sqlite and the following: <<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>> thread_lock = threading.RLock() def db_execute(sql): thread_lock.acquire() try: connection = sqlite3.connect(database_name) cursor = connection.cursor() cursor.execute(sql) connection.commit() except: log.error(formatExceptionInfo()) finally: thread_lock.release() <<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>> From inhahe at gmail.com Thu Dec 3 09:32:55 2009 From: inhahe at gmail.com (inhahe) Date: Thu, 3 Dec 2009 09:32:55 -0500 Subject: How to set object parameters nicely? In-Reply-To: <4b17c8c4$1@dnews.tpgi.com.au> References: <83ced7d2-8d75-4e41-a60b-7c0c73515129@m38g2000yqd.googlegroups.com> <4b17c8c4$1@dnews.tpgi.com.au> Message-ID: On Thu, Dec 3, 2009 at 9:16 AM, Lie Ryan wrote: > On 12/2/2009 10:26 AM, allen.fowler wrote: >> >> I've tried this, but have found two issues: >> >> 1) I can't set default values. >> 2) I can't set required values. >> >> In both of the above cases, if the object is created without the >> "exact" dict() I expect, all the assumption my methods make about what >> is available in "self" fall apart. >> > def __init__(self, required1, required2, default1='d1', default2='d2', **kwargs): ? ?for par in kwargs: ? ? ?self.setattr(par, kwargs[par]) self.required1 = required1 self.required2 = required2 self.default1 = default1 self.default2 = default2 or def __init__(self, required1, required2, default1='d1', default2='d2', **kwargs): ? ?for par in kwargs: ? ? ?self.setattr(par, kwargs[par]) self.required1 = required1 self.required2 = required2 self.default1 = default1 self.default2 = default2 From davea at ieee.org Thu Dec 3 09:33:14 2009 From: davea at ieee.org (Dave Angel) Date: Thu, 03 Dec 2009 09:33:14 -0500 Subject: Call C program In-Reply-To: <9ef5cb30912030046j7c975ed1g27c92ec21334c857@mail.gmail.com> References: <9ef5cb30912030046j7c975ed1g27c92ec21334c857@mail.gmail.com> Message-ID: <4B17CC2A.3030204@ieee.org> Patxi Bocos wrote: > Hi!, > > I am developing a Python application and I need to call a C program which > needs one parameter and it returns another one. > > How could I do it? > > Thanks :) > > You don't specify your python version, nor your OS. And you don't really say what state that C program is in. So I'll guess you're programming in Python 2.6, on Windows, and want to "call" an existing EXE file that happened to have been written in C, but which you don't want to modify. Further, I'll assume the program is written to take its input from stdin, and outputs to stdout. Use the subprocess module to run the EXE file. You can supply a stream for stdin, and can capture stdout. DaveA From inhahe at gmail.com Thu Dec 3 09:33:22 2009 From: inhahe at gmail.com (inhahe) Date: Thu, 3 Dec 2009 09:33:22 -0500 Subject: How to set object parameters nicely? In-Reply-To: References: <83ced7d2-8d75-4e41-a60b-7c0c73515129@m38g2000yqd.googlegroups.com> <4b17c8c4$1@dnews.tpgi.com.au> Message-ID: On Thu, Dec 3, 2009 at 9:32 AM, inhahe wrote: > On Thu, Dec 3, 2009 at 9:16 AM, Lie Ryan wrote: >> On 12/2/2009 10:26 AM, allen.fowler wrote: >>> >>> I've tried this, but have found two issues: >>> >>> 1) I can't set default values. >>> 2) I can't set required values. >>> >>> In both of the above cases, if the object is created without the >>> "exact" dict() I expect, all the assumption my methods make about what >>> is available in "self" fall apart. >>> >> > > def __init__(self, required1, required2, default1='d1', default2='d2', > **kwargs): > ? ?for par in kwargs: > ?? ? ?self.setattr(par, kwargs[par]) > ? self.required1 = required1 > ? self.required2 = required2 > ? self.default1 = default1 > ? self.default2 = default2 > > or > > def __init__(self, required1, required2, default1='d1', default2='d2', > **kwargs): > ? ?for par in kwargs: > ?? ? ?self.setattr(par, kwargs[par]) > ? self.required1 = required1 > ? self.required2 = required2 > ? self.default1 = default1 > ? self.default2 = default2 > (sorry, sent the same code twice. i was going to do it a different way and realized it would be too magically) From lie.1296 at gmail.com Thu Dec 3 09:38:00 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Fri, 04 Dec 2009 01:38:00 +1100 Subject: Organization of GUIs In-Reply-To: <424dcb65-735c-4779-ae0a-5c4e662b24ac@b36g2000prf.googlegroups.com> References: <424dcb65-735c-4779-ae0a-5c4e662b24ac@b36g2000prf.googlegroups.com> Message-ID: <4b17cdb8$1@dnews.tpgi.com.au> On 12/4/2009 12:44 AM, Michael Mossey wrote: > I have a question about typical organization of GUIs. I will be using > PyQt. > Model-View-Controller (MVC) pattern. Model - all the business logic lives in the model. View - your GUI Controller - Takes input Controller notifies Model if there is user input; Model notifies View if there is an update in the model; View "notifies" user if there is an update in the model; User "notifies" controller of the changes wanted. http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller From HeinTest at web.de Thu Dec 3 09:46:56 2009 From: HeinTest at web.de (=?ISO-8859-1?Q?Hans_M=FCller?=) Date: Thu, 03 Dec 2009 15:46:56 +0100 Subject: Strange MySQL / sqlite3 Problem with unicode Message-ID: <4b17cf60$0$3292$8e6e7893@newsreader.ewetel.de> I have a strange unicode problem with mySQL and sqlite. In my application I get a table as a sqlite table which is being compared to an existing mySQL Table. The sqlite drive returns all strings from the table as a unicode string which is Ok. The mysql drive returns all strings as utf-8 coded strings (no unicode!). When opening the mySQL database, use unicode is set to true, so the driver should return unicode strings. Any ideas ? This is the mySQL table definition: CREATE TABLE `USERNAMES` ( `NAME` varchar(256) COLLATE utf8_bin NOT NULL, `ID` mediumint(8) unsigned NOT NULL AUTO_INCREMENT, PRIMARY KEY (`NAME`), KEY `BYID` (`ID`) ) ENGINE=MyISAM AUTO_INCREMENT=59325 DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='Table for mapping user names to IDs' The sqlite Table was created this way: sq3Cursor.execute("create table USERNAMES(NAME text, ID integer)") When I query a value from both tables I get: sqlite: >>> SrcCursor.execute("select * from USERNAMES where ID=49011") >>> SrcCursor.fetchone() (u'J\xd6RG R\xd6\xdfMANN', 49011) >>> print u'J\xd6RG R\xd6\xdfLER/BD_FH'.encode("utf8") J?RG R??MANN This is Ok. Now mysql: >>> DstCursor.execute("select * from USERNAMES where ID=49011") 1L >>> DstCursor.fetchone() ('J\xc3\x96RG R\xc3\x96\xc3\x9fMANN', 49011) This is the same result, but returned as a utf-8 coded string, not unicode >>> 'J\xc3\x96RG R\xc3\x96\xc3\x9fMANN'.decode("utf8") u'J\xd6RG R\xd6\xdfMANN' The mySQL database has been opened this way: DstCon = MySQLdb.connect(host = DstServer, user = config["DBUser"], passwd = config["DBPasswd"], db = DstDBName, use_unicode = True, charset = "utf8") DstCursor = DstCon.cursor() Since use_unicode is set to True, I expect query results to be unicode (for string data types). From fasteliteprogrammer at gmail.com Thu Dec 3 09:52:47 2009 From: fasteliteprogrammer at gmail.com (perlsyntax) Date: Thu, 03 Dec 2009 08:52:47 -0600 Subject: Socket question Message-ID: <4B17D0BF.7070000@gmail.com> Is there away in python i can connect to a server in socket to two servers at the same time or can't it be done? From lie.1296 at gmail.com Thu Dec 3 09:56:19 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Fri, 04 Dec 2009 01:56:19 +1100 Subject: Noob thread lock question In-Reply-To: References: <5f776ec1-9b8c-45f7-b4e5-ff140638d6bf@33g2000vbe.googlegroups.com> <4b179e6d$1@dnews.tpgi.com.au> Message-ID: <4b17d204$1@dnews.tpgi.com.au> On 12/4/2009 1:20 AM, Astley Le Jasper wrote: > When you say don't forget about the GIL, what should I not be > forgetting? I'm using sqlite and the following: I mean don't forget that when the GIL is locked, all threads (except the current one, and threads waiting on I/O) will not be able to run. In your case, you don't have anything to worry about since you're I/O bound. From michaelmossey at gmail.com Thu Dec 3 09:59:09 2009 From: michaelmossey at gmail.com (Michael Mossey) Date: Thu, 3 Dec 2009 06:59:09 -0800 (PST) Subject: Organization of GUIs References: <424dcb65-735c-4779-ae0a-5c4e662b24ac@b36g2000prf.googlegroups.com> <4b17cdb8$1@dnews.tpgi.com.au> Message-ID: On Dec 3, 6:38?am, Lie Ryan wrote: > On 12/4/2009 12:44 AM, Michael Mossey wrote: > > > I have a question about typical organization of GUIs. I will be using > > PyQt. > > Model-View-Controller (MVC) pattern. > > Model - all the business logic lives in the model. > View - your GUI > Controller - Takes input > > Controller notifies Model if there is user input; Model notifies View if > there is an update in the model; View "notifies" user if there is an > update in the model; User "notifies" controller of the changes wanted. > > http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller I'm aware of Model-View-Controller, but my question is broader than that for a couple reasons: View can be fine-grained. Often the View consists of a number of GUI objects. Some people write this in a democratic arrangement---they all talk to each other. This can make analyzing system behavior complicated. Hence my proposal for a hierarchy. Also, often different parts of the Model talk to different parts of the View. The question, then, is whether both the Model and View should be structured hierarchically so that all messages pass through a "master" or "root" object before going to the other Model/View, and messages within a Model or View should only move along the hierarchy. In other words, you can easily make a complete mess of MVC. From mckenzie.c at gmail.com Thu Dec 3 09:59:43 2009 From: mckenzie.c at gmail.com (cmckenzie) Date: Thu, 3 Dec 2009 06:59:43 -0800 (PST) Subject: Declaring a class level nested class? Message-ID: Sigh, I'm using Google Groups and it seems I can't see my original post and everyone's replies. I'm really keen to reply back, so I'll just re-post my follow up for now and make sure I don't make a habit of this. (I'll get a news reader) Here goes: I agree, I'm C# and Java influenced, but I've got some messy Perl experience too. It was late when I posted my example, so I don't think I made my question clear enough. I want to be able to construct a class level class variable, so its global to the class, then reference it from a class method. I wrote a web server that uses reflection to dynamically load modules which are mapped to url paths. e.g. module "search.py" maps to "search.html", etc... It all works great, but I want my modules to be able to __init__ classes that belong to the module, then when a request comes in and is passed to the module, I can reference that initialized class. The declaration of a class level nestedClass class variable is wrong, but I was hoping someone could just say, "dummy, this is how to declare a class variable when you can't construct it just yet", or "you have to construct an empty version of nestedClass at the class level, then just re-construct it with any parameters during __init__". class module: nestedClass def __init__(): self.nestedClass = nested(10) print self.nestedClass.nestedVar def getNestedVar(self): return self.nestedClass.nestedVar class nested(): nestedVar = 1 def __init__(self, value): nestedVar = value print "Initialized..." Thanks and sorry for double posting, it won't happen again. From mckenzie.c at gmail.com Thu Dec 3 10:01:02 2009 From: mckenzie.c at gmail.com (cmckenzie) Date: Thu, 3 Dec 2009 07:01:02 -0800 (PST) Subject: Declaring a class level nested class? References: Message-ID: On Dec 3, 9:59?am, cmckenzie wrote: > Sigh, I'm using Google Groups and it seems I can't see my original > post and everyone's replies. I'm really keen to reply back, so I'll > just re-post my follow up for now and make sure I don't make a habit > of this. (I'll get a news reader) Here goes: > > I agree, I'm C# and Java influenced, but I've got some messy Perl > experience too. > > It was late when I posted my example, so I don't think I made my > question clear enough. I want to be able to construct a class level > class variable, so its global to the class, then reference it from a > class method. I wrote a web server that uses reflection to dynamically > load modules which are mapped to url paths. e.g. module "search.py" > maps to "search.html", etc... It all works great, but I want my > modules to be able to __init__ classes that belong to the module, then > when a request comes in and is passed to the module, I can reference > that initialized class. > > The declaration of a class level nestedClass class variable is wrong, > but I was hoping someone could just say, "dummy, this is how to > declare a class variable when you can't construct it just yet", or > "you have to construct an empty version of nestedClass at the class > level, then just re-construct it with any parameters during __init__". > > class module: > ? nestedClass > > ? def __init__(): > ? ? ?self.nestedClass = nested(10) > ? ? ?print self.nestedClass.nestedVar > > ? def getNestedVar(self): > ? ? ?return self.nestedClass.nestedVar > > ? class nested(): > ? ? ?nestedVar = 1 > ? ? ?def __init__(self, value): > ? ? ? ? nestedVar = value > ? ? ? ? print "Initialized..." > > Thanks and sorry for double posting, it won't happen again. Ok, it seems that my original post was present, just not searchable? Forget my confusion on this. Thanks. From lie.1296 at gmail.com Thu Dec 3 10:07:27 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Fri, 04 Dec 2009 02:07:27 +1100 Subject: Declaring a class level nested class? In-Reply-To: <6232b87e-f6a5-497b-a01f-d545c09ad4a8@d21g2000yqn.googlegroups.com> References: <6232b87e-f6a5-497b-a01f-d545c09ad4a8@d21g2000yqn.googlegroups.com> Message-ID: <4b17d4a0$1@dnews.tpgi.com.au> On 12/3/2009 3:55 PM, cmckenzie wrote: > I can't figure out what the correct way to construct the "nested" > class so it can belong to "module". > which one you want? 1. The Outside's class contains a nested class class Outside(object): class Inside(object): ... 2. The Outside's class contains an instance of the nested class class Outside(object): class inside(object): ... inside = inside() 3. The Outside's instance contains an instance of the nested class class Outside(object): class Inside(object): ... def __init__(self): self.inside = Outside.Inside() 4. From victorsubervi at gmail.com Thu Dec 3 10:12:06 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Thu, 3 Dec 2009 10:12:06 -0500 Subject: Insane Problem In-Reply-To: <4dc0cfea0912030502x1532319dy92e6f62868b6ef5e@mail.gmail.com> References: <4dc0cfea0912021218g797f782esa2c174923b6ac492@mail.gmail.com> <4B16D739.5080408@mrabarnett.plus.com> <4dc0cfea0912030307j7556eb06j469ccc4e6a29d1ee@mail.gmail.com> <4dc0cfea0912030502x1532319dy92e6f62868b6ef5e@mail.gmail.com> Message-ID: <4dc0cfea0912030712n602d003em12c994206c4191bc@mail.gmail.com> On Thu, Dec 3, 2009 at 8:02 AM, Victor Subervi wrote: > On Thu, Dec 3, 2009 at 6:07 AM, Victor Subervi wrote: > >> On Wed, Dec 2, 2009 at 4:08 PM, MRAB wrote: >> >>> Victor Subervi wrote: >>> >>>> Hi; >>>> I have spent 2-3 hours trying to track this bug. Here's the code >>>> snippet: >>>> >>>> form = cgi.FieldStorage() >>>> fn = getattr(options, 'products') >>>> ourOptionsNames = [] >>>> optionsNames, doNotUse = fn('names') >>>> for name in optionsNames: >>>> test = table + '-' + name >>>> print test >>>> check = form.getfirst(test, '') >>>> print check >>>> if check != '': >>>> ourOptionsNames.append(name) >>>> Now, when it looks through with test=='products', it doesn't report >>>> that any of the values from the form are checked. However, when I explicitly >>>> write out something like: >>>> print form.getfirst('products-sizes', '') >>>> which I checked on the form from the referring page, it does in fact >>>> print out! My test prints show that 'products-sizes' is being passed to >>>> "check" and should therefore be appended to "ourOptionsNames". But it isn't! >>>> What am I missing here?? >>>> >>>> What do the print statements actually print? Please copy and paste >>> their >>> output. >>> >> >> For the part in question they print __nothing__. That's the point. >> V >> > I believe I mentioned in my first post that the "print test" does print the > exact fields being called from the referring page. The "print check" prints > nothing. Another thing that's strange is that there are two tables of fields > in the referrer page; it will print the first of those tables--whichever of > the two I choose--but not the latter. Perhaps this is a bug in the cgi > interface? Perhaps I should migrate this to mod_python? > TIA, > V > Perhaps the following code, which is from the referrer, will help. I don't see how it makes any difference at all, since all the code is printed between the opening form and the submit button: #!/usr/bin/python import cgitb; cgitb.enable() import MySQLdb import cgi import sys,os sys.path.append(os.getcwd()) from login import login import string import options from particulars import optionsTables, addStore def chooseOptions(): print '''Content-Type: text/html\r\n
''' storesTables = [] junkStores = string.join(addStore(), ', ') for table in optionsTables(): if table not in ('particulars', junkStores): storesTables.append(table) bgcolors = ['F2F6D3', 'F2DDD3', 'D7DDD3'] myOptions = [] myMeanings = [] for table in storesTables: try: fn = getattr(options, table) opts, means = fn('names') myOptions.append(opts) myMeanings.append(means) except: pass i = 0 print "Please select which of the option groups below you would like to associate with each store. On the next page, you will have the opportunity to select which options within each option group you would like to have in your selection for each store.

" for table in storesTables: print "\n \n \n \n" % (table[0].upper() + table[1:]) print " \n \n \n \n \n" j = 0 while j < len(myOptions[0]): print " \n \n \n \n \n" % (myOptions[0][j], myMeanings[0][j], table + '-' + myOptions[0][j]) j += 1 print "
\n" % bgcolors[i] print "

%s

\n
OptionDefinitionCheck
%s%s


\n" i += 1 print '''
''' chooseOptions() TIA, V -------------- next part -------------- An HTML attachment was scrubbed... URL: From tartley at tartley.com Thu Dec 3 10:13:05 2009 From: tartley at tartley.com (Jonathan Hartley) Date: Thu, 3 Dec 2009 07:13:05 -0800 (PST) Subject: Python without wrapper script References: Message-ID: <7560513d-ae36-4152-a7be-0d661887c014@m38g2000yqd.googlegroups.com> On Dec 2, 4:12?pm, Ulrich Eckhardt wrote: > eric.frederich wrote: > > Is there a way to set up environment variables in python itself > > without having a wrapper script. > > Yes, sure, you can set environment variables... > > > The wrapper script is now something like.... > > > #!/bin/bash > > > export LD_LIBRARY_PATH="/some/thing/lib:$LD_LIBRARY_PATH" > > export LD_LIBRARY_PATH="/another/thing/lib:$LD_LIBRARY_PATH" > > > export PATH="/some/thing/bin:$PATH" > > export PATH="/another/thing/bin:$PATH" > > > python ./someScript.py > > ...but this won't work, I'm afraid. > > LD_LIBRARY_PATH is for the program loader / dynamic linker under Linux. This > thing is what is invoked _before_ the program is started, any later > modifications to the environment are ignored. > > Similarly PATH, which tells the shell (e.g. bash) where to find executables. > If you need that to e.g. find 'python' itself, you're out of luck. > Otherwise, I believe Python itself doesn't use PATH, so you could set it > inside and any shells started from Python should pick it up. > > Uli > > -- > Sator Laser GmbH > Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 I have had success in modifying LD_LIBRARY_PATH from within my Python code, to make sure that Python correctly loads DLL's from subdirectories of my project. (I believe the Python ended up calling CDll, or somesuch?) From carsten.haese at gmail.com Thu Dec 3 10:13:14 2009 From: carsten.haese at gmail.com (Carsten Haese) Date: Thu, 03 Dec 2009 10:13:14 -0500 Subject: Insane Problem In-Reply-To: <4dc0cfea0912030502x1532319dy92e6f62868b6ef5e@mail.gmail.com> References: <4dc0cfea0912021218g797f782esa2c174923b6ac492@mail.gmail.com> <4B16D739.5080408@mrabarnett.plus.com> <4dc0cfea0912030307j7556eb06j469ccc4e6a29d1ee@mail.gmail.com> <4dc0cfea0912030502x1532319dy92e6f62868b6ef5e@mail.gmail.com> Message-ID: Victor Subervi wrote: > I believe I mentioned in my first post that the "print test" does print > the exact fields being called from the referring page. Was any part of "What do the print statements actually print? Please copy and paste their output." unclear to you in any way? > Perhaps this > is a bug in the cgi interface? Unlikely. It's much more likely that whatever frankencode you stitched together from examples you found on the internet without understanding how they work is doing something unexpected, and you are unable to diagnose the problem because you don't understand how your code works. In order to help you diagnose the problem, we need to see the *exact* code you're running, we need to see the *exact* inputs going into it, and we need to see the *exact* output coming out of it. -- Carsten Haese http://informixdb.sourceforge.net From lie.1296 at gmail.com Thu Dec 3 10:15:20 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Fri, 04 Dec 2009 02:15:20 +1100 Subject: Help in wxpython In-Reply-To: References: <86b3db7d0912020020k51cf6bc8me0bc543214c582f1@mail.gmail.com> Message-ID: <4b17d679$1@dnews.tpgi.com.au> On 12/3/2009 6:55 PM, r0g wrote: > Krishnakant wrote: >> Madhura, Sorry to be a bit off-topic, but, I would really recommend you >> to use pygtk instead of wx. >> For one thing, the developers at pygtk are very active (they have their >> mailing list as well ) and it comes by default with python on almost all >> linux distros. You can also easily install it on windows. >> >> Most important, the api for pygtk is closely similar to wx. >> Not to mention the quick responses you will get with pygtk related >> problems. >> >> Happy hacking. >> Krishnakant. > > I have to recommend to opposite, stick with wx. What's the point of > tying yourself into GTK when wx works on Mac, PC and Linux? > > Roger. This again... I recommend writing your own C extension module to access GDI using ; it's ugly, it's non-cross-platform, it gets you bashed for reinventing the wheel, and it's buggy. Five thumbs up! (err... I only got four... whatever...) From tartley at tartley.com Thu Dec 3 10:16:04 2009 From: tartley at tartley.com (Jonathan Hartley) Date: Thu, 3 Dec 2009 07:16:04 -0800 (PST) Subject: Python without wrapper script References: <7560513d-ae36-4152-a7be-0d661887c014@m38g2000yqd.googlegroups.com> Message-ID: <6fb6aff0-0d90-4121-87db-98996fdd0b34@r5g2000yqb.googlegroups.com> On Dec 3, 3:13?pm, Jonathan Hartley wrote: > On Dec 2, 4:12?pm, Ulrich Eckhardt wrote: > > > > > eric.frederich wrote: > > > Is there a way to set up environment variables in python itself > > > without having a wrapper script. > > > Yes, sure, you can set environment variables... > > > > The wrapper script is now something like.... > > > > #!/bin/bash > > > > export LD_LIBRARY_PATH="/some/thing/lib:$LD_LIBRARY_PATH" > > > export LD_LIBRARY_PATH="/another/thing/lib:$LD_LIBRARY_PATH" > > > > export PATH="/some/thing/bin:$PATH" > > > export PATH="/another/thing/bin:$PATH" > > > > python ./someScript.py > > > ...but this won't work, I'm afraid. > > > LD_LIBRARY_PATH is for the program loader / dynamic linker under Linux. This > > thing is what is invoked _before_ the program is started, any later > > modifications to the environment are ignored. > > > Similarly PATH, which tells the shell (e.g. bash) where to find executables. > > If you need that to e.g. find 'python' itself, you're out of luck. > > Otherwise, I believe Python itself doesn't use PATH, so you could set it > > inside and any shells started from Python should pick it up. > > > Uli > > > -- > > Sator Laser GmbH > > Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 > > I have had success in modifying LD_LIBRARY_PATH from within my Python > code, to make sure that Python correctly loads DLL's from > subdirectories of my project. (I believe the Python ended up calling > CDll, or somesuch?) Ahar! But of course, I was modifying os.environ, not setting the actual environment. I see. From HeinTest at web.de Thu Dec 3 10:25:00 2009 From: HeinTest at web.de (=?ISO-8859-1?Q?Hans_M=FCller?=) Date: Thu, 03 Dec 2009 16:25:00 +0100 Subject: Strange unicode / no unicode phenomen with mysql Message-ID: <4b17d84c$0$3296$8e6e7893@newsreader.ewetel.de> I have a strange unicode problem with mySQL and sqlite. In my application I get a table as a sqlite table which is being compared to an existing mySQL Table. The sqlite drive returns all strings from the table as a unicode string which is Ok. The mysql drive returns all strings as utf-8 coded strings (no unicode!). When opening the mySQL database, use unicode is set to true, so the driver should return unicode strings. Any ideas ? This is the mySQL table definition: CREATE TABLE `USERNAMES` ( `NAME` varchar(256) COLLATE utf8_bin NOT NULL, `ID` mediumint(8) unsigned NOT NULL AUTO_INCREMENT, PRIMARY KEY (`NAME`), KEY `BYID` (`ID`) ) ENGINE=MyISAM AUTO_INCREMENT=59325 DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='Table for mapping user names to IDs' The sqlite Table was created this way: sq3Cursor.execute("create table USERNAMES(NAME text, ID integer)") When I query a value from both tables I get: sqlite: >>> SrcCursor.execute("select * from USERNAMES where ID=49011") >>> SrcCursor.fetchone() (u'J\xd6RG R\xd6\xdfMANN', 49011) >>> print u'J\xd6RG R\xd6\xdfMANN'.encode("utf8") J?RG R??MANN This is Ok. Now mysql: >>> DstCursor.execute("select * from USERNAMES where ID=49011") 1L >>> DstCursor.fetchone() ('J\xc3\x96RG R\xc3\x96\xc3\x9fMANN', 49011) This is the same result, but returned as a utf-8 coded string, not unicode >>> 'J\xc3\x96RG R\xc3\x96\xc3\x9fMANN'.decode("utf8") u'J\xd6RG R\xd6\xdfMANN' The mySQL database has been opened this way: DstCon = MySQLdb.connect(host = DstServer, user = config["DBUser"], passwd = config["DBPasswd"], db = DstDBName, use_unicode = True, charset = "utf8") DstCursor = DstCon.cursor() Since use_unicode is set to True, I expect query results to be unicode (for string data types). Trying another table, the result for a query is as aspected a unicode string. From exarkun at twistedmatrix.com Thu Dec 3 10:28:07 2009 From: exarkun at twistedmatrix.com (exarkun at twistedmatrix.com) Date: Thu, 03 Dec 2009 15:28:07 -0000 Subject: Socket question In-Reply-To: <4B17D0BF.7070000@gmail.com> References: <4B17D0BF.7070000@gmail.com> Message-ID: <20091203152807.2549.1165382253.divmod.xquotient.117@localhost.localdomain> On 02:52 pm, fasteliteprogrammer at gmail.com wrote: >Is there away in python i can connect to a server in socket to two >servers at the same time or can't it be done? I'm not sure what you're asking. Can you clarify? Jean-Paul From victorsubervi at gmail.com Thu Dec 3 10:28:35 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Thu, 3 Dec 2009 10:28:35 -0500 Subject: Insane Problem In-Reply-To: References: <4dc0cfea0912021218g797f782esa2c174923b6ac492@mail.gmail.com> <4B16D739.5080408@mrabarnett.plus.com> <4dc0cfea0912030307j7556eb06j469ccc4e6a29d1ee@mail.gmail.com> <4dc0cfea0912030502x1532319dy92e6f62868b6ef5e@mail.gmail.com> Message-ID: <4dc0cfea0912030728v7637edb5ue4a6f3ea25af593c@mail.gmail.com> On Thu, Dec 3, 2009 at 10:13 AM, Carsten Haese wrote: > Victor Subervi wrote: > > I believe I mentioned in my first post that the "print test" does print > > the exact fields being called from the referring page. > > Was any part of "What do the print statements actually print? Please > copy and paste their output." unclear to you in any way? > products-sizes products-colorsShadesNumbersShort products-colorsNamesNumbers products-colorsShadesNumbers The very fact that, as I stated earlier, I can get the cgi calls from the table in question to print by forcing the absence of the other, I believe, is proof positive that it's not what you think it is. Sorry for the misunderstanding. > > Perhaps this > > is a bug in the cgi interface? > > Unlikely. > > It's much more likely that whatever frankencode you stitched together > from examples you found on the internet without understanding how they > work is doing something unexpected, and you are unable to diagnose the > problem because you don't understand how your code works. > Frankencode? Please don't be rude. > > In order to help you diagnose the problem, we need to see the *exact* > code you're running, we need to see the *exact* inputs going into it, > and we need to see the *exact* output coming out of it. > Let's see your answers and see if you're right that the above output helps you arrive at the correct conclusion. TIA, V -------------- next part -------------- An HTML attachment was scrubbed... URL: From gruszczy at gmail.com Thu Dec 3 10:41:56 2009 From: gruszczy at gmail.com (=?UTF-8?Q?Filip_Gruszczy=C5=84ski?=) Date: Thu, 3 Dec 2009 16:41:56 +0100 Subject: Which is more pythonic? Message-ID: <1be78d220912030741p39e966e0s96bc82c61818c8e0@mail.gmail.com> I have just written a very small snippet of code and started thinking, which version would be more pythonic. Basically, I am adding a list of string to combo box in qt. So, the most obvious way is: for choice in self.__choices: choicesBox.addItem(choice) But I could also do: map(self.__choices, choicesBox.addItem) or [choicesBox.addItem(choice) for choice in self.__choices] I guess map version would be fastest and explicit for is the slowest version. However, the first, most obvious way seems most clear to me and I don't have to care about speed with adding elements to combo box. Still, it's two lines instead of one, so maybe it's not the best. So, which one is? -- Filip Gruszczy?ski From lie.1296 at gmail.com Thu Dec 3 10:43:18 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Fri, 04 Dec 2009 02:43:18 +1100 Subject: Declaring a class level nested class? In-Reply-To: References: Message-ID: <4b17dd0a$1@dnews.tpgi.com.au> On 12/4/2009 1:59 AM, cmckenzie wrote: > Sigh, I'm using Google Groups and it seems I can't see my original > post and everyone's replies. I'm really keen to reply back, so I'll > just re-post my follow up for now and make sure I don't make a habit > of this. (I'll get a news reader) Here goes: > > I agree, I'm C# and Java influenced, but I've got some messy Perl > experience too. > > It was late when I posted my example, so I don't think I made my > question clear enough. I want to be able to construct a class level > class variable, so its global to the class, "global to the class" that's contradictory! > then reference it from a > class method. > I wrote a web server that uses reflection to dynamically > load modules which are mapped to url paths. e.g. module "search.py" > maps to "search.html", Be careful of someone requesting an ../insecure.html > etc... It all works great, but I want my > modules to be able to __init__ classes that belong to the module, then > when a request comes in and is passed to the module, I can reference > that initialized class. When a module is "import"-ed, it's body is executed, unless you put it inside a if __name__ == '__main__': block which is only executed when the module itself is executed (instead of being imported). Basically, the module's body is like the module's __init__() That way if your directory is like this: /data - /__init__.py - /one.py /run_server.py your one.py would contains something like: class MyClass(object): ... instance = MyClass() and your run_server.py would reference the already instantiated module in the class as such: from data.one import instance # serve something using the instance > The declaration of a class level nestedClass class variable is wrong, > but I was hoping someone could just say, "dummy, this is how to > declare a class variable when you can't construct it just yet", > or > "you have to construct an empty version of nestedClass at the class > level, then just re-construct it with any parameters during __init__". That sounds like C/C++ forward declaration. Not something you'd need in a language that has dynamic name resolution. > > class module: > nestedClass > > def __init__(): > self.nestedClass = nested(10) > print self.nestedClass.nestedVar > > def getNestedVar(self): > return self.nestedClass.nestedVar > > class nested(): > nestedVar = 1 > def __init__(self, value): > nestedVar = value > print "Initialized..." > > Thanks and sorry for double posting, it won't happen again. From fasteliteprogrammer at gmail.com Thu Dec 3 10:45:19 2009 From: fasteliteprogrammer at gmail.com (perlsyntax) Date: Thu, 03 Dec 2009 09:45:19 -0600 Subject: Socket question In-Reply-To: <20091203152807.2549.1165382253.divmod.xquotient.117@localhost.localdomain> References: <4B17D0BF.7070000@gmail.com> <20091203152807.2549.1165382253.divmod.xquotient.117@localhost.localdomain> Message-ID: <4B17DD0F.5080702@gmail.com> On 12/03/2009 09:28 AM, exarkun at twistedmatrix.com wrote: > On 02:52 pm, fasteliteprogrammer at gmail.com wrote: >> Is there away in python i can connect to a server in socket to two >> servers at the same time or can't it be done? > > I'm not sure what you're asking. Can you clarify? > > Jean-Paul I just want to know could it be done makeing my own socket tool that connect to two server at the same time.And what link do i need to look at? From invalid at invalid.invalid Thu Dec 3 10:48:42 2009 From: invalid at invalid.invalid (Grant Edwards) Date: Thu, 3 Dec 2009 15:48:42 +0000 (UTC) Subject: Question on Python as career References: <614b8dde-324b-4d54-8e73-7a96e4c0b1cf@a21g2000yqc.googlegroups.com> Message-ID: On 2009-12-03, r0g wrote: >>> I have done one MA in Linguistics, did a PhD in Natural >>> Language Processing and doing a Post Doctoral now. ... >>> >>> After I complete my Post Doctoral which may be only 2-3 months >>> away, with this knowledge can I join IT? > Getting involved in an open source project or two may bolster your CV > and help you get your foot in the door. Having some real experience would help offset the liability of having a PhD. 1/2 ;) -- Grant Edwards grante Yow! Eisenhower!! Your at mimeograph machine upsets visi.com my stomach!! From invalid at invalid.invalid Thu Dec 3 10:51:34 2009 From: invalid at invalid.invalid (Grant Edwards) Date: Thu, 3 Dec 2009 15:51:34 +0000 (UTC) Subject: Call C program References: <9ef5cb30912030046j7c975ed1g27c92ec21334c857@mail.gmail.com> Message-ID: On 2009-12-03, Patrick Sabin wrote: >> I am developing a Python application and I need to call a C program >> which needs one parameter and it returns another one. > Have a look at the ctypes module > http://python.net/crew/theller/ctypes/tutorial.html Ctypes is great, except it's for calling C functions within libraries. Calling C programs is done using the subprocess module: http://docs.python.org/library/subprocess.html -- Grant Edwards grante Yow! I'm rated PG-34!! at visi.com From carsten.haese at gmail.com Thu Dec 3 10:53:11 2009 From: carsten.haese at gmail.com (Carsten Haese) Date: Thu, 03 Dec 2009 10:53:11 -0500 Subject: Insane Problem In-Reply-To: <4dc0cfea0912030728v7637edb5ue4a6f3ea25af593c@mail.gmail.com> References: <4dc0cfea0912021218g797f782esa2c174923b6ac492@mail.gmail.com> <4B16D739.5080408@mrabarnett.plus.com> <4dc0cfea0912030307j7556eb06j469ccc4e6a29d1ee@mail.gmail.com> <4dc0cfea0912030502x1532319dy92e6f62868b6ef5e@mail.gmail.com> <4dc0cfea0912030728v7637edb5ue4a6f3ea25af593c@mail.gmail.com> Message-ID: Victor Subervi wrote: > In order to help you diagnose the problem, we need to see the *exact* > code you're running, we need to see the *exact* inputs going into it, > and we need to see the *exact* output coming out of it. > > > Let's see your answers and see if you're right that the above output > helps you arrive at the correct conclusion. No, it doesn't, because you've only provided one third of what I asked for. I also asked for the code and the inputs that go into it. -- Carsten Haese http://informixdb.sourceforge.net From invalid at invalid.invalid Thu Dec 3 10:54:54 2009 From: invalid at invalid.invalid (Grant Edwards) Date: Thu, 3 Dec 2009 15:54:54 +0000 (UTC) Subject: Socket question References: <4B17D0BF.7070000@gmail.com> <20091203152807.2549.1165382253.divmod.xquotient.117@localhost.localdomain> Message-ID: On 2009-12-03, perlsyntax wrote: > On 12/03/2009 09:28 AM, exarkun at twistedmatrix.com wrote: >> On 02:52 pm, fasteliteprogrammer at gmail.com wrote: >> >>> Is there away in python i can connect to a server in socket to >>> two servers at the same time or can't it be done? >> >> I'm not sure what you're asking. Can you clarify? > I just want to know could it be done makeing my own socket > tool that connect to two server at the same time. And what > link do i need to look at? In the context of sockets a "connection" has exactly two ends. IOW, no. You can't do "it". You can create two sockets, connect each of them to a server. Unless you provide some sort of clue about what it is you're trying to do, that's as about as much of an answer as you can expect. -- Grant Edwards grante Yow! I'm gliding over a at NUCLEAR WASTE DUMP near visi.com ATLANTA, Georgia!! From fpm at u.washington.edu Thu Dec 3 11:05:32 2009 From: fpm at u.washington.edu (cassiope) Date: Thu, 3 Dec 2009 08:05:32 -0800 (PST) Subject: Socket question References: <4B17D0BF.7070000@gmail.com> <20091203152807.2549.1165382253.divmod.xquotient.117@localhost.localdomain> Message-ID: <92080b8a-ab79-46d7-8d86-52a6a5e4d8e9@u16g2000pru.googlegroups.com> On Dec 3, 7:45?am, perlsyntax wrote: > On 12/03/2009 09:28 AM, exar... at twistedmatrix.com wrote:> On 02:52 pm, fasteliteprogram... at gmail.com wrote: > >> Is there away in python i can connect to a server in socket to two > >> servers at the same time or can't it be done? > > > I'm not sure what you're asking. ?Can you clarify? > > > Jean-Paul > > I just want to know could it be done makeing my own socket tool that > connect to two server at the same time.And what link do i need to look at? Should be pretty straightforward in a multithreadded application, at least in a Unix variant - can't say for sure about windows, but probably there too. Have you checked out the 'socket' module? Interesting name... From victorsubervi at gmail.com Thu Dec 3 11:07:14 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Thu, 3 Dec 2009 11:07:14 -0500 Subject: Insane Problem In-Reply-To: References: <4dc0cfea0912021218g797f782esa2c174923b6ac492@mail.gmail.com> <4B16D739.5080408@mrabarnett.plus.com> <4dc0cfea0912030307j7556eb06j469ccc4e6a29d1ee@mail.gmail.com> <4dc0cfea0912030502x1532319dy92e6f62868b6ef5e@mail.gmail.com> <4dc0cfea0912030728v7637edb5ue4a6f3ea25af593c@mail.gmail.com> Message-ID: <4dc0cfea0912030807o78b874a0jd64f3e902825e3a2@mail.gmail.com> On Thu, Dec 3, 2009 at 10:53 AM, Carsten Haese wrote: > Victor Subervi wrote: > > In order to help you diagnose the problem, we need to see the *exact* > > code you're running, we need to see the *exact* inputs going into it, > > and we need to see the *exact* output coming out of it. > > > > > > Let's see your answers and see if you're right that the above output > > helps you arrive at the correct conclusion. > > No, it doesn't, because you've only provided one third of what I asked > for. I also asked for the code and the inputs that go into it. > I provided those earlier. To be sure I don't miss anything that may be important, here is the entire code for chooseOptions.py, the referrer. What I consider to be the important code is between the : #!/usr/bin/python import cgitb; cgitb.enable() import MySQLdb import cgi import sys,os sys.path.append(os.getcwd()) from login import login import string import options from particulars import optionsTables, addStore def chooseOptions(): print '''Content-Type: text/html\r\n
''' storesTables = [] junkStores = string.join(addStore(), ', ') for table in optionsTables(): if table not in ('particulars', junkStores): storesTables.append(table) bgcolors = ['F2F6D3', 'F2DDD3', 'D7DDD3'] myOptions = [] myMeanings = [] for table in storesTables: try: fn = getattr(options, table) opts, means = fn('names') myOptions.append(opts) myMeanings.append(means) except: pass i = 0 print "Please select which of the option groups below you would like to associate with each store. On the next page, you will have the opportunity to select which options within each option group you would like to have in your selection for each store.

" for table in storesTables: print "\n \n \n \n" % (table[0].upper() + table[1:]) print " \n \n \n \n \n" j = 0 while j < len(myOptions[0]): print " \n \n \n \n \n" % (myOptions[0][j], myMeanings[0][j], table + '-' + myOptions[0][j]) j += 1 print "
\n" % bgcolors[i] print "

%s

\n
OptionDefinitionCheck
%s%s


\n" i += 1 print '''
''' chooseOptions() Here is the pared-down code (to the "products") from options.py: def products(which='', specificTables=[]): code = [] names = [] meanings = [] code.append(['Extra-small', 'Small', 'Medium', 'Large', 'XLarge', 'XXLarge', 'XXXLarge']) meanings.append('The standard sizes.') names.append('sizes') if which == 'names': for name in colors('products', 'names'): names.append(name) for meaning in colors('products', 'meanings'): meanings.append(meaning) return names, meanings elif which == 'specificTables': whichTablesToReturn = [] colorsTables, colorsNames = colors('products', 'specificTables', specificTables) for name in colorsNames: names.append(name) for table in colorsTables: code.append(table) i = 0 while i < len(names): # We utilize the name of the table to determine where it is in the code tuple for table in specificTables: if names[i] == table: whichTablesToReturn.append(i) i += 1 returnTheseTables = [] for table in whichTablesToReturn: returnTheseTables.append(code[table]) returnTheseNames = [] for table in whichTablesToReturn: returnTheseNames.append(names[table]) i = 0 all = '' table = '' while i < len(returnTheseNames): table += "\n \n \n " % returnTheseNames[i] j = 0 for elt in code[i]: if (j + 8) % 8 == 0: table += ' \n' table += ' \n' % code[i][j] table += " " % (returnTheseNames[i], returnTheseTables[i][j]) if (j + 1) % 8 == 0: table += ' \n' j += 1 if table[-6:] != '\n': table += ' \n' table += '
%s
%s
\n' all += table + '

' i += 1 print all else: i = 0 all = '' if which != '': # I place a dummy value in here to get what I want ourCode = [] ourMeanings = [] ourNames = specificTables i = 0 for name in names: for check in ourNames: if name == check: ourCode.append(code[i]) ourMeanings.append(meanings[i]) i += 1 else: ourCode = code ourMeanings = meanings ourNames = names ourColors = [] i = 0 while i < len(ourNames): if ourNames[i] in names: table = '%s\n' % ourMeanings[i] table += "\n \n \n " % ourNames[i] j = 0 for elt in ourCode[i]: if (j + 8) % 8 == 0: table += ' \n' table += ' \n' % ourCode[i][j] table += " " % (ourNames[i], ourCode[i][j]) if (j + 1) % 8 == 0: table += ' \n' j += 1 if table[-6:] != '\n': table += ' \n' table += '
%s
%s
\n' all += table + '

' else: # This must be a color option ourColors.append(ourNames[i]) i += 1 all += colors('products', 'junk', ourColors) return all Here is the chooseOptions2.py, with : #! /usr/bin/python import cgitb; cgitb.enable() import cgi import sys,os sys.path.append(os.getcwd()) from login import login import string import options from particulars import optionsTables, addStore def optionsPrintout(table): form = cgi.FieldStorage() fn = getattr(options, table) ourOptionsNames = [] optionsNames, doNotUse = fn('names') for name in optionsNames: check = form.getfirst(table + '-' + name, '') if check != '': ourOptionsNames.append(name) try: return fn('junk', ourOptionsNames) except: pass def chooseOptions2(): print '''Content-Type: text/html\r\n
''' print '

Which options shall we associate with the items in each shop?


' storesTables = [] junkStores = string.join(addStore(), ', ') for table in optionsTables(): if table not in ('particulars', junkStores): storesTables.append(table) bgcolors = ['F2F6D3', 'F2DDD3', 'D7DDD3'] i = 0 for table in storesTables: try: fn = getattr(options, table) # This is only here to trigger the try statement print "\n \n \n \n
\n" % bgcolors[i] print '

%s

' % (table[0].upper() + table[1:]) print optionsPrintout(table) print "


\n" except: # All tables must have the products options in them by defualt print "\n \n \n \n
\n" % bgcolors[i] print '

%s

' % (table[0].upper() + table[1:]) # print optionsPrintout('products') print "


\n" i += 1 print '''

''' chooseOptions2() TIA, V -------------- next part -------------- An HTML attachment was scrubbed... URL: From darcy at druid.net Thu Dec 3 11:07:14 2009 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Thu, 3 Dec 2009 11:07:14 -0500 Subject: Socket question In-Reply-To: <4B17DD0F.5080702@gmail.com> References: <4B17D0BF.7070000@gmail.com> <20091203152807.2549.1165382253.divmod.xquotient.117@localhost.localdomain> <4B17DD0F.5080702@gmail.com> Message-ID: <20091203110714.244ca9ad.darcy@druid.net> On Thu, 03 Dec 2009 09:45:19 -0600 perlsyntax wrote: > On 12/03/2009 09:28 AM, exarkun at twistedmatrix.com wrote: > > On 02:52 pm, fasteliteprogrammer at gmail.com wrote: > >> Is there away in python i can connect to a server in socket to two > >> servers at the same time or can't it be done? > > > > I'm not sure what you're asking. Can you clarify? > > > > Jean-Paul > I just want to know could it be done makeing my own socket tool that > connect to two server at the same time.And what link do i need to look at? Repeating the question won't clarify it any more. Post some code, even pseudo code, to show what you are trying to do and be clear about what you expect it to do. Let me start you out. from socket import * def MyConnection(host, port): s = socket(AF_INET, SOCK_STREAM) s.connect((host, port)) return s s1 = MyConnection(host1, port1) s2 = MyConnection(host2, port2) There, that gives you access to two remote servers in one tool. That's what you asked for. I am sure that what you really need is something else so expand on this example so that we can see what you really want. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From bruno.42.desthuilliers at websiteburo.invalid Thu Dec 3 11:22:20 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 03 Dec 2009 17:22:20 +0100 Subject: How to set object parameters nicely? In-Reply-To: References: <83ced7d2-8d75-4e41-a60b-7c0c73515129@m38g2000yqd.googlegroups.com> <7nlnj4F3mq0bdU1@mid.uni-berlin.de> <559162e6-1c91-4a4a-a90c-b303c93bd976@u7g2000yqm.googlegroups.com> Message-ID: <4b17e5aa$0$11196$426a74cc@news.free.fr> allen.fowler a ?crit : (snip) > In this case, and I am trying to create a number of ORM-like objects. > (Though, there is no database involved.) > > So, instances of these classes are acting as records that are shuttled > around in the system, and the object's properties are acting as > values. The parameters are (mostly) orthogonal, but do need defaults, > and some must be required. You could specify the names, defaults and validations required at an upper level then automate the whole thing, ie (thinking out loud): class Field(object): def __init__(self, name,required=False, default=None,target=None,validate=None): self._name = name self._required = required self._default = default self._target = target or name self._validate = validate or lambda x: x def validate(self, value): """ _validate is supposed to raise a ValueError if not ok. it can also do any required conversion, formatting etc """ return self._validate(value) def set(self, instance, **kw): value = kw.get(self._name, None) if value is None if self.required: raise ValueError("argument %s is required" % self._name) else: value = self._default value = self.validate(value) setattr(instance, self._target, value) class Record(object): def __init__(self, **kw): if not hasattr(self, "_fields"): raise AttributeError("Record subclasses must define _fields") for field in self._fields: field.set(self, **kw) class Foo(Record): _fields = ( Field("bar", True, validate=lambda v : v > 1), Field("baaz", default=42) ) NB : totally untested code, so it will of course contains at least one major and obvious bug / typo / whatever !-) You could go further using an even more declarative API based on a fancy custom metaclass and descriptors (for Fields) etc etc - and that even might be the RightThing(tm) to do if you have more than moderatly complex needs, but for simple cases the above should work fine without going over the top with black magic. HTH From lie.1296 at gmail.com Thu Dec 3 11:29:46 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Fri, 04 Dec 2009 03:29:46 +1100 Subject: Socket question In-Reply-To: References: Message-ID: <4b17e7ea$1@dnews.tpgi.com.au> On 12/4/2009 1:52 AM, perlsyntax wrote: > Is there away in python i can connect to a server in socket to two > servers at the same time or can't it be done? use threading or non-blocking read. From carsten.haese at gmail.com Thu Dec 3 11:38:36 2009 From: carsten.haese at gmail.com (Carsten Haese) Date: Thu, 03 Dec 2009 11:38:36 -0500 Subject: Insane Problem In-Reply-To: <4dc0cfea0912030807o78b874a0jd64f3e902825e3a2@mail.gmail.com> References: <4dc0cfea0912021218g797f782esa2c174923b6ac492@mail.gmail.com> <4B16D739.5080408@mrabarnett.plus.com> <4dc0cfea0912030307j7556eb06j469ccc4e6a29d1ee@mail.gmail.com> <4dc0cfea0912030502x1532319dy92e6f62868b6ef5e@mail.gmail.com> <4dc0cfea0912030728v7637edb5ue4a6f3ea25af593c@mail.gmail.com> <4dc0cfea0912030807o78b874a0jd64f3e902825e3a2@mail.gmail.com> Message-ID: Victor Subervi wrote: > No, it doesn't, because you've only provided one third of what I asked > for. I also asked for the code and the inputs that go into it. > > > I provided those earlier. No, you didn't provide the exact code you're running. You provided a selected snippet you deemed important, but because you don't actually know what the problem is and where it is, your determination of what's important is not helpful. You actually managed to snip away the part that causes the problem. The code snipped you posted earlier showed cgi.FieldStorage being called once. The code you're posting now makes it clear that cgi.FieldStorage is actually called multiple times in a loop: > [snip...] > def optionsPrintout(table): > form = cgi.FieldStorage() > fn = getattr(options, table) > ourOptionsNames = [] > optionsNames, doNotUse = fn('names') > > [snip...] > > for table in storesTables: > [snip...] > print optionsPrintout(table) > [snip ...] The problem is that the first call to cgi.FieldStorage() consumes all POST variables that were given to the script, so any subsequent call reads an empty file and results in an empty FieldStorage object. Rewrite your code to construct the FieldStorage object once and refer to that one object in every pass of the loop. As you can see, and as I suspected, it's not a bug in the cgi module. -- Carsten Haese http://informixdb.sourceforge.net From victorsubervi at gmail.com Thu Dec 3 11:52:25 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Thu, 3 Dec 2009 12:52:25 -0400 Subject: Insane Problem In-Reply-To: References: <4dc0cfea0912021218g797f782esa2c174923b6ac492@mail.gmail.com> <4B16D739.5080408@mrabarnett.plus.com> <4dc0cfea0912030307j7556eb06j469ccc4e6a29d1ee@mail.gmail.com> <4dc0cfea0912030502x1532319dy92e6f62868b6ef5e@mail.gmail.com> <4dc0cfea0912030728v7637edb5ue4a6f3ea25af593c@mail.gmail.com> <4dc0cfea0912030807o78b874a0jd64f3e902825e3a2@mail.gmail.com> Message-ID: <4dc0cfea0912030852s3930501dy3bade4e19b571d88@mail.gmail.com> On Thu, Dec 3, 2009 at 12:38 PM, Carsten Haese wrote: > Victor Subervi wrote: > > No, it doesn't, because you've only provided one third of what I > asked > > for. I also asked for the code and the inputs that go into it. > > > > > > I provided those earlier. > > No, you didn't provide the exact code you're running. You provided a > selected snippet you deemed important, but because you don't actually > know what the problem is and where it is, your determination of what's > important is not helpful. You actually managed to snip away the part > that causes the problem. > > The code snipped you posted earlier showed cgi.FieldStorage being called > once. The code you're posting now makes it clear that cgi.FieldStorage > is actually called multiple times in a loop: > > > [snip...] > > def optionsPrintout(table): > > form = cgi.FieldStorage() > > fn = getattr(options, table) > > ourOptionsNames = [] > > optionsNames, doNotUse = fn('names') > > > > [snip...] > > > > for table in storesTables: > > [snip...] > > print optionsPrintout(table) > > [snip ...] > > The problem is that the first call to cgi.FieldStorage() consumes all > POST variables that were given to the script, so any subsequent call > reads an empty file and results in an empty FieldStorage object. Rewrite > your code to construct the FieldStorage object once and refer to that > one object in every pass of the loop. > > As you can see, and as I suspected, it's not a bug in the cgi module. > Thank you! Well, I suspected it wasn't a bug either, but I was at my wit's end and pulling straws. Thanks again! V -------------- next part -------------- An HTML attachment was scrubbed... URL: From debatem1 at gmail.com Thu Dec 3 11:54:27 2009 From: debatem1 at gmail.com (geremy condra) Date: Thu, 3 Dec 2009 11:54:27 -0500 Subject: python bijection In-Reply-To: <4B17A960.1090700@egenix.com> References: <5a99def7-e182-4782-9054-f1035affa34d@x5g2000prf.googlegroups.com> <7n39ojF3jj6iuU1@mid.individual.net> <12c55890-118d-4655-b6c0-c908c9734a17@a32g2000yqm.googlegroups.com> <85100df7-a8b0-47e9-a854-ba8a8a2f3b98@r31g2000vbi.googlegroups.com> <4B17A960.1090700@egenix.com> Message-ID: On Thu, Dec 3, 2009 at 7:04 AM, M.-A. Lemburg wrote: > Raymond Hettinger wrote: >> [Joshua Bronson] >>> Raymond, do you think there might be any future in including a built- >>> in bidict data structure in Python? >> >> I don't think so. ?There are several forces working against it: >> >> * the recipe is new, so it hasn't had a chance to mature >> ? or to gain a fan club. >> >> * there are many approaches to the solving the problem and >> ? there is no reason to assume this one is the best. >> >> * it extends the language with arcane syntax tricks instead of >> ? using the language as designed by Guido. ?That makes it harder >> ? to learn and remember. >> >> * we've already got one (actually two). ?The two dictionary approach >> ? uses plain python, requires no new learning, and is more flexible. >> ? Also, sqlite3 provides another way to use multiple lookups to a >> ? single record. ?The database approach is much more general >> ? (extending to trijections, allowing multiple sort orders, >> ? providing persistence, etc). >> >> * the semantics of a bijection aren't obvious: >> >> ? ? ?b['x'] = 'ex' ? ? ?# first record: ?('x', 'ex') >> ? ? ?b['y'] = 'why' ? ? # second record: ('y', 'why') >> ? ? ?b[:'why'] = 'x' ? ?# do two records collapse into one? is there >> an error? >> >> * the proposed syntax doesn't address the issue covered in my previous >> post. >> ? Since bijections are symmetrical, they do not have an obvious >> direction >> ? (which is the primary key, the husband or the wife?). ?The syntax >> needs to >> ? allow user names to make it clear which is being accessed: >> >> ? ? ?marriages.h2w['john'] = 'amy' >> ? ? ?marriages.w2h['amy'] = 'john' >> >> ? Contrast this with: >> >> ? ? ?marriages['jordan'] = 'taylor' ? ?# are you sure you got the >> order correct? >> ? ? ?marriages[:'taylor'] = 'jordan' ? # this is easy to get backwards > > I think the only major CS data type missing from Python is some > form of (fast) directed graph implementation ? la kjGraph: > > ? ?http://gadfly.sourceforge.net/kjbuckets.html > > With these, you can easily build all sorts of relations between > objects and apply fast operations on them. In fact, it should then > be possible to build a complete relational database in Python > (along the lines of Gadfly). If you're in the market for a Python graph library, you may want to check out Graphine- I'm obviously biased (I wrote most of it) but it has a few more bells and whistles than kjbuckets, and is pretty darned easy to use. It also supports undirected and bridge graphs. Geremy Condra From mal at egenix.com Thu Dec 3 12:57:18 2009 From: mal at egenix.com (M.-A. Lemburg) Date: Thu, 03 Dec 2009 18:57:18 +0100 Subject: python bijection In-Reply-To: References: <5a99def7-e182-4782-9054-f1035affa34d@x5g2000prf.googlegroups.com> <7n39ojF3jj6iuU1@mid.individual.net> <12c55890-118d-4655-b6c0-c908c9734a17@a32g2000yqm.googlegroups.com> <85100df7-a8b0-47e9-a854-ba8a8a2f3b98@r31g2000vbi.googlegroups.com> <4B17A960.1090700@egenix.com> Message-ID: <4B17FBFE.8070903@egenix.com> geremy condra wrote: > On Thu, Dec 3, 2009 at 7:04 AM, M.-A. Lemburg wrote: >> I think the only major CS data type missing from Python is some >> form of (fast) directed graph implementation ? la kjGraph: >> >> http://gadfly.sourceforge.net/kjbuckets.html >> >> With these, you can easily build all sorts of relations between >> objects and apply fast operations on them. In fact, it should then >> be possible to build a complete relational database in Python >> (along the lines of Gadfly). > > If you're in the market for a Python graph library, you may want > to check out Graphine- I'm obviously biased (I wrote most of it) > but it has a few more bells and whistles than kjbuckets, and is > pretty darned easy to use. It also supports undirected and > bridge graphs. Thanks for the hint :-) The lib looks nice and would probably serve as a good prototype for writing a new built-in type for Python. This would have to be written in C, though, and come under a Python compatible license. With the built-in feature moratorium currently in place, there's about 1.5-2 years time to get this done; perhaps a good GSoC project for next year :-) -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Dec 03 2009) >>> 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 our new mxODBC.Connect Python Database Interface 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 http://www.egenix.com/company/contact/ From news at schwertberger.de Thu Dec 3 13:08:39 2009 From: news at schwertberger.de (Dietmar Schwertberger) Date: Thu, 03 Dec 2009 19:08:39 +0100 Subject: Organization of GUIs In-Reply-To: References: <424dcb65-735c-4779-ae0a-5c4e662b24ac@b36g2000prf.googlegroups.com> <4b17cdb8$1@dnews.tpgi.com.au> Message-ID: <7nqd6cF3nf1n3U1@mid.individual.net> Michael Mossey schrieb: > View can be fine-grained. Often the View consists of a number of GUI > objects. Some people write this in a democratic arrangement---they all > talk to each other. This can make analyzing system behavior > complicated. Hence my proposal for a hierarchy. Yes, the democratic arrangement is only for very simple applications. > Also, often different parts of the Model talk to different parts of > the View. The question, then, is whether both the Model and View > should be structured hierarchically so that all messages pass through > a "master" or "root" object before going to the other Model/View, and > messages within a Model or View should only move along the hierarchy. > > In other words, you can easily make a complete mess of MVC. I made good experiences with this setup in a very complex application (inspired by MVC/MVP, but slightly different): - Model is completely independent of any GUI; in fact it's written to be used not only with a GUI, but also by scripts and an application server - Controller/Presenter holds the model instance and serves as message dispatcher; also it holds view-only data (e.g. cursor position, cell selections, file modified?) - Views/Controls - subscribe to the messages to update themselves - either modify data and send update message via the dispatcher - or tell Controller to modify the data, which then generates the update message With this architecture, you have the choice whether to plug the Views/Controls directly to the Controller/Presenter or organize them hierarchically. I doubt that you'll have many hierarchy levels between Presenter and Controls. Probably only one... Examples for the messages: - "Changed", model (anything may have changed) - "AttributeChanged", attname, value - "DataChanged", index, new_value - "Saved", filename - "Modified", modified - "IndexChanged", new_index - "ViewChanged", view_names (I'm using a tabbed interface and some views react to messages only when they're active.) - "ConfigRead", key, value, persistent Some messages are automatically issued by the Presenter in response to other messages. E.g. for a "Saved" message, the Presenter automatically generates a ("Modified",False) message afterwards. In my case, the model is hierarchical and so I have "Changed" messages for many different aspects / levels. The total number of message types is around 60. I could live with much less, but the finer the messages, the less performance overhead. As there are messages related to the model (e.g. Changed) as well as messages related to the views (e.g. IndexChanged) and to general functionality (e.g. ConfigRead) it's very easy to couple all controls and components via the Presenter. The app is built with wxPython and includes a shell window which exposes some objects including the app itself and the model. In this shell you may manipulate the model interactively or by loading a Python script. For the GUI to catch up you need to issue a "Changed" message afterwards. It would be possible to follow e.g. the original MVP and do all modifications (GUI and shell) via the Presenter to avoid the requirement of issuing this message, but that would require wrapping of much functionality and usage would be less elegant. As the app, including all menu items, is available from the shell, this can also be used for automatic testing. E.g. shell input or script may look like that: >>> filename = "c:\\test.dat" >>> self.menu.file.open( filename=filename ) >>> # or self.menu.file.open() to let the user select a file >>> # or model = ModelModule.open( filename ) >>> if model.filename!=filename: raise ValueError, "test failed" >>> new_filename = "c:\\output.dat" >>> model.filename = new_filename >>> presenter.notify("AttributeChanged", "filename", new_filename) >>> # or presenter.set_filename( new_filename ) >>> # or presenter() as shortcut for presenter.notify("Changed", model) >>> # or presenter.save( new_filename ) Also, it's possible to automatically test dialogs... Regards, Dietmar From news at redlamb.net Thu Dec 3 13:21:52 2009 From: news at redlamb.net (Pete) Date: Thu, 3 Dec 2009 10:21:52 -0800 (PST) Subject: Ignoring XML Namespaces with ElementTree Message-ID: Is there anyway to configure ElementTree to ignore the XML namespace? For the past couple months, I've been using minidom to parse an XML file that is generated by a unit within my organization that can't stick with a standard. This hasnt been a problem until recently when the script was provided a 30MB file that once parsed, increased the python memory footprint by 1.0GB and now I'm running into Memory Errors. Based on Google searches and testing it looks like ElementTree is much more efficient with memory and I'd like to switch, however I'd like to be able to ignore the namespaces. These XML files tend to randomly switch the namespace for no reason and ignoring these namespaces would help the script adapt to the changes. Any help on this would be greatly appreciated. I'm having a hard time finding the answer. Additionally, anyone know how ElementTree handle's XML elements that include Unicode? From ashwin.shirvanthe at gmail.com Thu Dec 3 13:29:13 2009 From: ashwin.shirvanthe at gmail.com (Ashwin Rao) Date: Thu, 3 Dec 2009 10:29:13 -0800 (PST) Subject: Incorrect number of bytes returned by getsockopt(socket.SOL_SOCKET, socket.TCP_INFO, buflen) Message-ID: <5c2800de-a6d2-4863-b423-87ef80d95e6b@k17g2000yqh.googlegroups.com> Hi, I need to retrieve the tcp_info from a socket using getsockopt. The details of structure tcp_info are available at [http://src.gnu- darwin.org/src/sys/netinet/tcp.h.html]. The getsockopt method for a socket whose documentation is available at [http://docs.python.org/ library/socket.html#socket.socket.getsockopt] specifies that - "if buflen is present, it specifies the maximum length of the buffer used to receive the option in, and this buffer is returned as a string". To confirm my calculation, I computed the size of the tcp_info using the following program, which returned 104. --- #include #include int main() { printf("%d", sizeof(struct tcp_info)); } --- I then added the following lines to my program tcp_info = sock.getsockopt(socket.SOL_SOCKET, socket.TCP_INFO, 104) print "Return len"+str(len(tcp_info)) for cnt in range(len(tcp_info)): print tcp_info[cnt] The output for the length is 4, which is less than 104. I would like to know the technique to obtain the tcp_info structure using the getsocktopt method. I am currently using python 2.5.2. Regards, Ashwin From roy at panix.com Thu Dec 3 13:38:28 2009 From: roy at panix.com (Roy Smith) Date: Thu, 03 Dec 2009 13:38:28 -0500 Subject: Does Python mess with the (unicode) code page? Message-ID: We've got a windows executable which used to get run out of a shell script (Cygwin bash) and is now being run with subprocess.Popen(). The windows app is misbehaving. To make a long story short, the guy who wrote the code in question says, > it's all based on the return values of the WinAPI calls GetACP and GetOEMCP > [...] so maybe Python is doing something like setting the active code page > and OEM code page prior to the point when they "exec" stuff? Does Python do these things? I'm using Python 2.5.1. From roy at panix.com Thu Dec 3 13:42:18 2009 From: roy at panix.com (Roy Smith) Date: Thu, 03 Dec 2009 13:42:18 -0500 Subject: Incorrect number of bytes returned by getsockopt(socket.SOL_SOCKET, socket.TCP_INFO, buflen) References: <5c2800de-a6d2-4863-b423-87ef80d95e6b@k17g2000yqh.googlegroups.com> Message-ID: In article <5c2800de-a6d2-4863-b423-87ef80d95e6b at k17g2000yqh.googlegroups.com>, Ashwin Rao wrote: > I computed the size of the tcp_info using the > following program, which returned 104. > --- > #include > #include > > int main() > { > printf("%d", sizeof(struct tcp_info)); > } In general, the right way to do stuff like this in Python is to use the struct module. In particular, struct.calcsize() will tell you how long the string has to be. Try that and see if you come up with the same value. From stefan_ml at behnel.de Thu Dec 3 14:55:17 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 03 Dec 2009 20:55:17 +0100 Subject: Ignoring XML Namespaces with ElementTree In-Reply-To: References: Message-ID: <4b1817a5$0$6584$9b4e6d93@newsspool3.arcor-online.net> Pete, 03.12.2009 19:21: > Is there anyway to configure ElementTree to ignore the XML namespace? > For the past couple months, I've been using minidom to parse an XML > file that is generated by a unit within my organization that can't > stick with a standard. This hasnt been a problem until recently when > the script was provided a 30MB file that once parsed, increased the > python memory footprint by 1.0GB and now I'm running into Memory > Errors. Based on Google searches and testing it looks like ElementTree > is much more efficient with memory and I'd like to switch, Make sure you use cElementTree, then that's certainly the right choice to make. > however I'd > like to be able to ignore the namespaces. These XML files tend to > randomly switch the namespace for no reason and ignoring these > namespaces would help the script adapt to the changes. Any help on > this would be greatly appreciated. I'm having a hard time finding the > answer. ET uses namespace URIs as part of the tag name, so if you want to ignore namespaces, just strip the leading "{...}" (if any) from the tag and work with the rest (so-called "local name"). > Additionally, anyone know how ElementTree handle's XML elements that > include Unicode? It's an XML parser, so the answer is: without any difficulties. Stefan From pruebauno at latinmail.com Thu Dec 3 15:13:12 2009 From: pruebauno at latinmail.com (nn) Date: Thu, 3 Dec 2009 12:13:12 -0800 (PST) Subject: Question about file objects... References: <01fd9f0b-aa15-41c8-86ac-1d719d87999a@m35g2000vbi.googlegroups.com> <36dec4ff0912020811w32be2430rd6692de96ffd2671@mail.gmail.com> Message-ID: <0020aac5-6781-42a8-917e-49a085041f0f@h10g2000vbm.googlegroups.com> On Dec 2, 6:56?pm, Terry Reedy wrote: > J wrote: > > On Wed, Dec 2, 2009 at 09:27, nn wrote: > >>> Is there a way to read the file, one item at a time, delimited by > >>> commas WITHOUT having to read all 16,000 items from that one line, > >>> then split them out into a list or dictionary?? > > >> File iteration is a convenience since it is the most common case. If > >> everything is on one line, you will have to handle record separators > >> manually by using the .read() method on the file > >> object and searching for the comma. If everything fits in memory the > >> straightforward way would be to read the whole file with .read() and > >> use .split(",") on the returned string. That should give you a nice > >> list of everything. > > > Agreed. The confusion came because the guy teaching said that > > iterating the file is delimited by a carriage return character... > > If he said exactly that, he is not exactly correct. File iteration looks > for line ending character(s), which depends on the system or universal > newline setting. > > > which to me sounds like it's an arbitrary thing that can be changed... > > > I was already thinking that I'd have to read it in small chunks and > > search for the delimiter i want... ?and reading the whole file into a > > string and then splitting that would would be nice, until the file is > > so large that it starts taking up significant amounts of memory. > > > Anyway, thanks both of you for the explanations... I appreciate the help! > > I would not be surprised if a generic file chunk generator were posted > somewhere. It would be a good entry for the Python Cookbook, if not > there already. > > tjr There should be but writing one isn't too difficult: def chunker(file_obj): parts=[''] while True: fdata=file_obj.read(8192) if not fdata: break parts=(parts[-1]+fdata).split(',') for col in parts[:-1]: yield col yield parts[-1] From as at sci.fi Thu Dec 3 15:33:29 2009 From: as at sci.fi (Anssi Saari) Date: Thu, 03 Dec 2009 22:33:29 +0200 Subject: Bored. References: <16097008-372c-4522-889d-a78319c3575c@b2g2000yqi.googlegroups.com> Message-ID: Necronymouse writes: > Hello, I am learning python for about 2 years and I am bored. Not with > python but I have a little problem, when i want to write something I > realise that somebody had alredy written it! So i don?t want to make a > copy of something but i wanna get better in python skills. Don?t you > know what I should do? If I may propose something, I'm pretty annoyed that it's so hard to get contact and calendar data out of my Nokia phone. However, there's Python available for Symbian phones and the implementation is supposed to have access to that data on the phone... So a calendar and contacts sync tool would be a nice thing. From clp2 at rebertia.com Thu Dec 3 15:41:45 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Thu, 3 Dec 2009 12:41:45 -0800 Subject: Help with function prototype In-Reply-To: <97FB089C6E1F404CB0132AC3BB3E5C2701948253@exchange.qualisystems.local> References: <97FB089C6E1F404CB0132AC3BB3E5C2701948253@exchange.qualisystems.local> Message-ID: <50697b2c0912031241o77c3c4e7t5eadff4a2560075d@mail.gmail.com> On Thu, Dec 3, 2009 at 3:02 AM, Nadav Chernin wrote: > Hi, all > > In past I asked about module ? inspect, that can?t to get me prototype of > C-implemented functions ( usually all built-in functions ). > > But, still I see that all Python Editors ( IDLE for example ) can to show > prototype of built-in functions ? by tooltip. When you print for example: > sum(, you see what kind of parameters you must to enter. > > So, how IDLE know it? It doesn't really; it only shows the function's docstring, which /just so happens/ to document the parameters in the particular case of the built-in functions: $ python Python 2.6.2 Type "help", "copyright", "credits" or "license" for more information. >>> print sum.__doc__ sum(sequence[, start]) -> value Returns the sum of a sequence of numbers (NOT strings) plus the value of parameter 'start' (which defaults to 0). When the sequence is empty, returns start. >>> type(sum.__doc__) Cheers, Chris -- http://blog.rebertia.com From torriem at gmail.com Thu Dec 3 15:46:45 2009 From: torriem at gmail.com (Michael Torrie) Date: Thu, 03 Dec 2009 13:46:45 -0700 Subject: Language mavens: Is there a programming with "if then else ENDIF" syntax? In-Reply-To: References: <3f466a96-70f2-4b0e-bbd1-558fb9292b65@u25g2000prh.googlegroups.com> Message-ID: <4B1823B5.6060508@gmail.com> Steven D'Aprano wrote: > But you're right, the convention of using verbs for functions isn't as > strong as the convention of using nouns for classes and types. The idea that functions should be verbs is plain wrong, coming from the traditional world of functional programming. Since functions should never have any side effects, ideally, they don't ever "do" anything to something. Rather they return a result. I suppose if you were in a language that had statements, that they could be the verbs. One could argue that _methods_ should be verbs (which obviously doesn't apply to Java and their over use of patterns to compensate for a weak language) since methods are the means by which change to an object can be effected. From torriem at gmail.com Thu Dec 3 15:56:41 2009 From: torriem at gmail.com (Michael Torrie) Date: Thu, 03 Dec 2009 13:56:41 -0700 Subject: Language mavens: Is there a programming with "if then else ENDIF" syntax? In-Reply-To: References: Message-ID: <4B182609.2040709@gmail.com> Steve Ferg wrote: > Is there any particular reason why this might be a *bad* language- > design idea? Syntactically, using braces, begin/end blocks, python white space, and your if/elif/then/endif structures, amounts to the same thing; they are all equivalent. Thus from a language pov, there's no compelling reason to do one over the other. One good reason to avoid the if/elif/then/endif syntax and its related friends in a language (while/wend, do/loop, for/next) is that they require parser support for what amounts to three or four versions of precisely the same construct: the block. Thus from a parser or compiler point of view, it's far better and easier to have blocks begin and end with something that is consistent and recognizable without a lot of look-ahead or context. I once started to write a parser for the QuickBasic language but found very quickly that the grammar required a fair amount of token look-ahead. For example, if I found the token "End", I had to look at least one token ahead to find out if this was an "end if" or just an "end." Also "end" could, if I recall, have an optional number parameter that would set the exit errorlevel code. Certainly QuickBasic was not context-free and was not LL(1). I'm not sure, but Python's grammar is LL(1) I think, and probably darn close to context-free. From robert.kern at gmail.com Thu Dec 3 16:10:53 2009 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 03 Dec 2009 15:10:53 -0600 Subject: Language mavens: Is there a programming with "if then else ENDIF" syntax? In-Reply-To: <4B182609.2040709@gmail.com> References: <4B182609.2040709@gmail.com> Message-ID: On 2009-12-03 14:56 PM, Michael Torrie wrote: > I'm not sure, but Python's grammar is LL(1) I think, and probably darn > close to context-free. It is LL(1) after some non-formal postprocessing of the tokens to properly handle the indentation. -- 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 coldtortuga at gmail.com Thu Dec 3 16:17:02 2009 From: coldtortuga at gmail.com (Francis Carr) Date: Thu, 3 Dec 2009 13:17:02 -0800 (PST) Subject: python bijection References: <5a99def7-e182-4782-9054-f1035affa34d@x5g2000prf.googlegroups.com> <7n39ojF3jj6iuU1@mid.individual.net> <12c55890-118d-4655-b6c0-c908c9734a17@a32g2000yqm.googlegroups.com> <85100df7-a8b0-47e9-a854-ba8a8a2f3b98@r31g2000vbi.googlegroups.com> Message-ID: <39a95e47-3851-42ae-892c-82b07e0dc25b@u7g2000yqm.googlegroups.com> [In re R. Hettinger's critiques] > * it extends the language with arcane syntax tricks... I think most of these in the current version of J. Bronson's "bidict" can be left unused, or removed altogether. In almost all cases, a bidict should be accessed as an ordinary python dict. > * we've already got one (actually two). > The two dictionary approach... Solutions such as bidict just automate the two-dict approach. > ? ...sqlite3 provides another way... In many many cases, using a dB (even a lightweight such as sqlite3) is swatting the fly with a sledgehammer :-) > Since bijections are symmetrical, they do not have an obvious > direction (which is the primary key, the husband or the wife?). I think this is easy to solve with a classmethod constructor that produces a pair of "linked" dicts. For example, husband2wife, wife2husband = bidict.makepair(('Fred', 'John'), ('Mary', 'Ruth')) Obviously from the code this pair of bidicts are "linked", and the direction of each mapping is obvious from its name. Metaprogramming idioms like namedtuple are not required. > * the semantics of a bijection aren't obvious: > ? ? ?b['x'] = 'ex' ? ? ?# first record: ?('x', 'ex') > ? ? ?b['y'] = 'why' ? ? # second record: ('y', 'why') > ? ? ?b[:'why'] = 'x' ? ?# do two records collapse into one? > # is there an error? Among the various critiques, I think this is the most significant. When I was fiddling with my implementation, I was disturbed that the code bidict[newKey] = oldValue should have the subtle side-effect del bidict.inv[oldValue] And there is a much stranger case. Suppose bidict[key1]=val1 and bidict[key2]=val2. Then the code bidict[key1] = val2 should have the extremely subtle side-effects del bidict[key2] # because val2 has been re-mapped del bidict.inv[val1] # because key1 has been re-mapped Blech! I think there must be something better. It would be interesting to hear more opinions on the matter. I propose raising ValueError when operating on one key would also silently re-map or delete a different (key,value) pair. This would disallow both of the above cases. To get the effect of the first case, one would simply operate on the inverse mapping: bidict.inv[oldValue] = newKey This should not be confusing: it's exactly how a python dict would operate, except the "linked" mapping is altered to match, which is the bookkeeping we want to automate in the first place. To get the effect of the second case, one would have to explicitly demand the side- effects: del bidict[key2] del bidict.inv[val1] bidict[key1] = val2 Also not confusing. -- FC From dreadpiratejeff at gmail.com Thu Dec 3 16:20:24 2009 From: dreadpiratejeff at gmail.com (J) Date: Thu, 3 Dec 2009 16:20:24 -0500 Subject: slightly OT: Python BootCamp In-Reply-To: References: <36dec4ff0911281815p583598i43a476bc66083e29@mail.gmail.com> Message-ID: <36dec4ff0912031320m337ab5a5s19cd77d390552bfc@mail.gmail.com> On Sun, Nov 29, 2009 at 20:14, Terry Reedy wrote: > J wrote: >> >> Ok... so I've been re-teaching myself python, as it's been several >> years since I last really used it. ?And in the midst of this, my >> contracting company came up to me on Friday and asked if I'd be >> interested in filling a last minute vacancy in this: >> >> http://www.otg-nc.com/python-bootcamp > The list of topics seems to cover basic + intermediate issues. > If you do go, perhaps you could review it here. > Same for people who have attended other Python training courses, of course. The last day is tomorrow, so I'll actually try and write something real then... I just wanted to say that this has been a pretty good class. Really good, compared to others I've taken (in college and so forth)... Anyway, just thought I'd share this: The difference between me (learning a new language) and the guy teaching (who knows it inside and out) My code: import os startDir = '/home/student/testdirectory' #raw_input("Enter starting location: ") searchList=['html','py','jpg'] filenames=[] report={} try: fhtml=open('HTMLFiles','w') fpy=open('PYFiles','w') fjpg=open('JPGFiles','w') except: assert 0, 'Unable to open file' for root, dirs, files in os.walk(startDir): filenames += [os.path.normcase(os.path.join(root,f)) for f in files if f[f.rfind('.')+1:] in searchList] for file in filenames: ext=file.split('.')[1] if report.has_key(ext): report[ext].extend([file]) else: report.update({ext:[file]}) for k,v in report.iteritems(): if k == 'html': for item in v: fhtml.write("%s\n" % item) if k == 'py': for item in v: fpy.write("%s\n" % item) if k == 'jpg': for item in v: fjpg.write("%s\n" % item) His code: import os def FindFiles(base_dir="/", exten=[]): results={} # Initialize results dictionary with blank arrays for l in exten: results[l]=[] for root, dirs, files in os.walk(base_dir): for e in exten: results[e] += [os.path.join(root,fn) for fn in files if fn.endswith(e)] return results files=FindFiles('C:/Python26',['exe','html']) for (exten, list) in files.iteritems(): try: f=open('extensions-%s.txt' % exten,'w') f.write('\n'.join(list)) except: assert 0, 'Unable to create output file extensions-%s.txt.' % exten Different thought processes, plus experience makes a difference too... That and while I have an educational background in programming, the only programming I've been able to do in my professional (read daily) life is BASH... I think it shows. Cheers, Jeff -- Ted Turner - "Sports is like a war without the killing." - http://www.brainyquote.com/quotes/authors/t/ted_turner.html From nobody at nowhere.com Thu Dec 3 16:22:19 2009 From: nobody at nowhere.com (Nobody) Date: Thu, 03 Dec 2009 21:22:19 +0000 Subject: Help in wxpython References: <86b3db7d0912020020k51cf6bc8me0bc543214c582f1@mail.gmail.com> Message-ID: On Thu, 03 Dec 2009 07:55:19 +0000, r0g wrote: > I have to recommend to opposite, stick with wx. What's the point of > tying yourself into GTK when wx works on Mac, PC and Linux? The main drawbacks are that wxWidgets sucks compared to GTK or Qt (mostly due to being modelled on the Win32 API, which itself sucks compared to most Unix/X11 toolkits), and that wxPython is woefully under-documented (whereas PyGTK is better documented than GTK itself). But if you need portability, wxPython is the way to go. From doomster at knuut.de Thu Dec 3 16:28:09 2009 From: doomster at knuut.de (Ulrich Eckhardt) Date: Thu, 03 Dec 2009 22:28:09 +0100 Subject: More elegant solution for diffing two sequences Message-ID: <7nqorbF3n7go3U1@mid.uni-berlin.de> Hi! I'm trying to write some code to diff two fonts. What I have is every character (glyph) of the two fonts in a list. I know that the list is sorted by the codepoints of the characters. What I'd like to ask is whether there is a more elegant solution to the loop below or whether there are any rough corners in my code (see below). Note that I'm targeting Python 2, not 3 yet. Thank you! Uli def diff_font(font1, font2): it1 = iter(font1.glyphs) it2 = iter(font2.glyphs) try: glyph1 = it1.next() glyph2 = it2.next() while True: if glyph1.codepoint < glyph2.codepoint: # glyph only in first font diff_glyph(glyph1, None) glyph1 = it1.next() elif glyph2.codepoint < glyph2.codepoint: # glyph only in second font diff_glyph(None, glyph2) glyph2 = it2.next() else: # glyph in both fonts diff_glyph(glyph1, glyph2) glyph1 = it1.next() glyph2 = it2.next() except StopIteration, msg: # remaining glyphs in either font are exclusive to that font for glyph in it1: diff_glyph(glyph, None) for glyph in it1: diff_glyph(None, glyph) From martien.verbruggen at invalid.see.sig Thu Dec 3 16:36:20 2009 From: martien.verbruggen at invalid.see.sig (Martien Verbruggen) Date: Fri, 4 Dec 2009 08:36:20 +1100 Subject: Incorrect number of bytes returned by getsockopt(socket.SOL_SOCKET, socket.TCP_INFO, buflen) References: <5c2800de-a6d2-4863-b423-87ef80d95e6b@k17g2000yqh.googlegroups.com> Message-ID: On Thu, 3 Dec 2009 10:29:13 -0800 (PST), Ashwin Rao wrote: > tcp_info = sock.getsockopt(socket.SOL_SOCKET, socket.TCP_INFO, 104) In C, to get tcp_info, SOL_SOCKET should be IPPROTO_TCP. I'm assuming it's the same in Python, although I've never tried it. Martien -- | Martien Verbruggen | Never hire a poor lawyer. Never buy first.last at heliotrope.com.au | from a rich salesperson. | From news at redlamb.net Thu Dec 3 16:39:45 2009 From: news at redlamb.net (Pete) Date: Thu, 3 Dec 2009 13:39:45 -0800 (PST) Subject: Ignoring XML Namespaces with ElementTree References: <4b1817a5$0$6584$9b4e6d93@newsspool3.arcor-online.net> Message-ID: On Dec 3, 2:55?pm, Stefan Behnel wrote: > Pete, 03.12.2009 19:21: > > > Is there anyway to configure ElementTree to ignore the XML namespace? > > For the past couple months, I've been using minidom to parse an XML > > file that is generated by a unit within my organization that can't > > stick with a standard. This hasnt been a problem until recently when > > the script was provided a 30MB file that once parsed, increased the > > python memory footprint by 1.0GB and now I'm running into Memory > > Errors. Based on Google searches and testing it looks like ElementTree > > is much more efficient with memory and I'd like to switch, > > Make sure you use cElementTree, then that's certainly the right choice to make. > > > however I'd > > like to be able to ignore the namespaces. These XML files tend to > > randomly switch the namespace for no reason and ignoring these > > namespaces would help the script adapt to the changes. Any help on > > this would be greatly appreciated. I'm having a hard time finding the > > answer. > > ET uses namespace URIs as part of the tag name, so if you want to ignore > namespaces, just strip the leading "{...}" (if any) from the tag and work > with the rest (so-called "local name"). > > > Additionally, anyone know how ElementTree handle's XML elements that > > include Unicode? > > It's an XML parser, so the answer is: without any difficulties. > > Stefan Perfect... I can work with that. Thanks. From phartley at gmail.com Thu Dec 3 16:42:20 2009 From: phartley at gmail.com (paul) Date: Thu, 3 Dec 2009 13:42:20 -0800 (PST) Subject: confusing thread behavior Message-ID: <63e08b25-a576-452c-82fb-06e0c4b4f489@13g2000prl.googlegroups.com> I have been experiencing strange thread behavior when I pass a message received via a Queue to a wx.PostEvent method (from wxPython). The relevant code in the thread is: def run(self): while self.is_running: task = self.queue.get() wx.PostEvent(self.app.handle_task, task) self.queue is a Queue.Queue instance and self.app is a wx.Window instance I have a case where two items are placed in the queue one after the other, and it appears that only the first item is passed to wx.PostEvent. If I place a time.sleep(0.1) call anywhere within the while loop, both items get passed to wx.PostEvent. It works if I put time.sleep before the self.queue.get(), in between get() and PostEvent () or after PostEvent(). So it seems like a short delay is enough to get two items handled, although it doesn't seem to matter where I place the delay within the while loop. Does someone know what might explain this behavior? Thanks. From lie.1296 at gmail.com Thu Dec 3 16:43:04 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Fri, 04 Dec 2009 08:43:04 +1100 Subject: More elegant solution for diffing two sequences In-Reply-To: <7nqorbF3n7go3U1@mid.uni-berlin.de> References: <7nqorbF3n7go3U1@mid.uni-berlin.de> Message-ID: <4b183159@dnews.tpgi.com.au> On 12/4/2009 8:28 AM, Ulrich Eckhardt wrote: > I'm trying to write some code to diff two fonts. What I have is every > character (glyph) of the two fonts in a list. I know that the list is sorted > by the codepoints of the characters. What I'd like to ask is whether there > is a more elegant solution to the loop below or whether there are any rough > corners in my code (see below). Note that I'm targeting Python 2, not 3 yet. > Use sets: glyph_1 = set(font1.glyphs) glyph_2 = set(font2.glyphs) only_in_1 = glyph_1 - glyph_2 only_in_2 = glyph_2 - glyph_1 in_both = glyph_1 & glyph_2 that is assuming font1.glyphs's value are hashable. From aahz at pythoncraft.com Thu Dec 3 16:48:42 2009 From: aahz at pythoncraft.com (Aahz) Date: 3 Dec 2009 13:48:42 -0800 Subject: confused with os.fork() References: <7fc44f39-c6f8-4283-bb64-88d8f30f1d01@m16g2000yqc.googlegroups.com> Message-ID: In article , Dennis Lee Bieber wrote: >On Wed, 25 Nov 2009 13:52:09 -0800 (PST), Sandy >declaimed the following in gmane.comp.python.general: >> >> Sometimes (very rare) it prints something like this: >> ab >> c >> d >> e > > Not > >ab > >c >d >e > >? That's what I would guess, too. > Since all the forked processes are sharing the same output device, >it is quite possible that their output is getting interleaved. Actually, I am a tiny bit surprised; I would have expected that a single output call at the C level would not get interleaved. Of course, it's quite likely that the string and the \n are separate API calls. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ The best way to get information on Usenet is not to ask a question, but to post the wrong information. From kyosohma at gmail.com Thu Dec 3 17:03:40 2009 From: kyosohma at gmail.com (Mike Driscoll) Date: Thu, 3 Dec 2009 14:03:40 -0800 (PST) Subject: confusing thread behavior References: <63e08b25-a576-452c-82fb-06e0c4b4f489@13g2000prl.googlegroups.com> Message-ID: <6126c9b0-bcde-4223-b39e-70630317fe09@e27g2000yqd.googlegroups.com> On Dec 3, 3:42?pm, paul wrote: > I have been experiencing strange thread behavior when I pass a message > received via a Queue to a wx.PostEvent method (from wxPython). The > relevant code in the thread is: > > def run(self): > ? ? while self.is_running: > ? ? ? ? task = self.queue.get() > ? ? ? ? wx.PostEvent(self.app.handle_task, task) > > self.queue is a Queue.Queue instance and self.app is a wx.Window > instance > > I have a case where two items are placed in the queue one after the > other, and it appears that only the first item is passed to > wx.PostEvent. ?If I place a time.sleep(0.1) call anywhere within the > while loop, both items get passed to wx.PostEvent. ?It works if I put > time.sleep before the self.queue.get(), in between get() and PostEvent > () or after PostEvent(). ?So it seems like a short delay is enough to > get two items handled, although it doesn't seem to matter where I > place the delay within the while loop. ?Does someone know what might > explain this behavior? ?Thanks. [Note: I cross-posted this to wxPython where Paul had also cross- posted] Not sure if this will help or not, but see the following article on the wxPython wiki: http://wiki.wxpython.org/LongRunningTasks There's a section called "More Tips" where Queues are discussed. Robin Dunn (creator of wxPython) seems to recommend using wx.CallAfter there rather than PostEvent. ------------------- Mike Driscoll Blog: http://blog.pythonlibrary.org From heintest at web.de Thu Dec 3 17:06:01 2009 From: heintest at web.de (=?ISO-8859-1?Q?Hans_M=FCller?=) Date: Thu, 03 Dec 2009 23:06:01 +0100 Subject: Strange unicode / no unicode phenomen with mysql In-Reply-To: <4b17d84c$0$3296$8e6e7893@newsreader.ewetel.de> References: <4b17d84c$0$3296$8e6e7893@newsreader.ewetel.de> Message-ID: <4b1835cc$0$6562$9b4e6d93@newsspool4.arcor-online.net> I found the bug, it's in the mysql module. When a column has COLLATE=utf8_bin set, the column is NOT returned as unicode. It's a known bug #541198 Thanks all for reading. Greetings Hans From kyosohma at gmail.com Thu Dec 3 17:07:01 2009 From: kyosohma at gmail.com (Mike Driscoll) Date: Thu, 3 Dec 2009 14:07:01 -0800 (PST) Subject: Help in wxpython References: <86b3db7d0912020020k51cf6bc8me0bc543214c582f1@mail.gmail.com> Message-ID: <7515ad37-847b-44f7-b9b6-de058861d386@n35g2000yqm.googlegroups.com> On Dec 2, 10:05?pm, Krishnakant wrote: > On Wed, 2009-12-02 at 00:20 -0800, madhura vadvalkar wrote: > > Hi > > > I am trying to write an ?PAINT like application where on the mouse > > click a circle is drawn on canvas. I am new to python and using > > wxpython to create this. > > > here is the code: > > > import wx > > > class SketchWindow(wx.Window): > > > ? ? def __init__ (self, parent,ID): > > > ? ? ? ? wx.Window.__init__(self, parent, ID) > > > ? ? ? ? self.panel =wx.Panel(self, size= (350,350)) > > ? ? ? ? self.pen=wx.Pen( 'blue',4) > > ? ? ? ? self.pos=(0,0) > > ? ? ? ? self.InitBuffer() > > ? ? ? ? self.Bind(wx.EVT_LEFT_DOWN,self.OnLeftDown) > > > ? ? def InitBuffer(self): > > > ? ? ? ? size=self.GetClientSize() > > ? ? ? ? self.Buffer=wx.EmptyBitmap(size.width,size.height) > > ? ? ? ? dc=wx.BufferedDC(None,self.buffer) > > ? ? ? ? dc.SetBackground(wx.Brush(self.GetBackgroundColour())) > > ? ? ? ? dc.Clear() > > ? ? ? ? self.Drawcircle(dc) > > ? ? ? ? self.reInitBuffer=False > > > ? ? def OnLeftDown(self,event): > > ? ? ? ? self.pos=event.GetPositionTuple() > > ? ? ? ? self.CaptureMouse() > > > ? ? def Drawcircle(self,dc): > > ? ? ? ? pen=wx.Pen(colour,thickness,wx.SOLID) > > ? ? ? ? dc.SetPen(pen) > > ? ? ? ? dc.DrawCircle(self.pos.x,self.pos.y,r) > > > class SketchFrame(wx.Frame): > > ? ? def __init__(self, parent): > > > ? ? ? ? wx.Frame.__init__(self, parent, -1, "Sketch Frame",size=(800,600)) > > ? ? ? ? self.sketch = SketchWindow(self, -1) > > > if __name__=='__main__': > > ? ? app=wx.PySimpleApp() > > ? ? frame=SketchFrame(None) > > ? ? frame.Show(True) > > ? ? app.MainLoop() > > > I am getting the following error: > > > Traceback (most recent call last): > > ? File "C:/Python26/circle.py", line 42, in > > ? ? frame=SketchFrame(None) > > ? File "C:/Python26/circle.py", line 38, in __init__ > > ? ? self.sketch = SketchWindow(self, -1) > > ? File "C:/Python26/circle.py", line 12, in __init__ > > ? ? self.InitBuffer() > > ? File "C:/Python26/circle.py", line 19, in InitBuffer > > ? ? dc=wx.BufferedDC(None,self.buffer) > > AttributeError: 'SketchWindow' object has no attribute 'buffer' > > > Please tell me what I am doing wrong. > > > Thanks > > Madhura, Sorry to be a bit off-topic, but, I would really recommend you > to use pygtk instead of wx. > For one thing, the developers at pygtk are very active (they have their > mailing list as well ) and it comes by default with python on almost all > linux distros. ?You can also easily install it on windows. wxPython has some very active developers as well, but the core isn't released all that often. I think this may be caused somewhat by the slow release cycle of wx itself though. > > Most important, the api for pygtk is closely similar to wx. > Not to mention the quick responses you will get with pygtk related > problems. The wxPython mailing list has very fast responses to questions as well (most of the time) ------------------- Mike Driscoll Blog: http://blog.pythonlibrary.org From kyosohma at gmail.com Thu Dec 3 17:09:26 2009 From: kyosohma at gmail.com (Mike Driscoll) Date: Thu, 3 Dec 2009 14:09:26 -0800 (PST) Subject: Help in wxpython References: <86b3db7d0912020020k51cf6bc8me0bc543214c582f1@mail.gmail.com> Message-ID: On Dec 3, 3:22?pm, Nobody wrote: > On Thu, 03 Dec 2009 07:55:19 +0000, r0g wrote: > > I have to recommend to opposite, stick with wx. What's the point of > > tying yourself into GTK when wx works on Mac, PC and Linux? > > The main drawbacks are that wxWidgets sucks compared to GTK or Qt (mostly > due to being modelled on the Win32 API, which itself sucks compared to > most Unix/X11 toolkits), and that wxPython is woefully under-documented > (whereas PyGTK is better documented than GTK itself). > > But if you need portability, wxPython is the way to go. There is currently an on-going documentation initiative going on for wxPython. Robin Dunn is doing some work on it that will allow much easier documentation patching (as I understand it), so that should get better. Also, I am slowly working my way through wxPython many widgets and doing tutorials on them on my blog, which I then stick in the official wxPython wiki if I think the article is good enough. ------------------- Mike Driscoll Blog: http://blog.pythonlibrary.org From bdesth.quelquechose at free.quelquepart.fr Thu Dec 3 17:20:56 2009 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 03 Dec 2009 23:20:56 +0100 Subject: Overriding module's class In-Reply-To: References: Message-ID: <4b184757$0$2702$426a34cc@news.free.fr> Pavel Skvazh a ?crit : > Is it possible to override a class in the module or the module itself > that is imported across the project to add new methods to it? > > For example I've got > > module 'a' with class A > > from a import A > > but I don't want to add a method to that A class not just in this > unit, but across the project, so everywhere I'll import class A - it > would be a modified one. > Google for "monkey patch". FWIW, what turns a function into a method is not the fact that it has been defined with a class statement, but the fact that it's an attribute of a class object. Where the function is defined is totally irrelevant. From phartley at gmail.com Thu Dec 3 17:29:43 2009 From: phartley at gmail.com (paul) Date: Thu, 3 Dec 2009 14:29:43 -0800 (PST) Subject: confusing thread behavior References: <63e08b25-a576-452c-82fb-06e0c4b4f489@13g2000prl.googlegroups.com> <6126c9b0-bcde-4223-b39e-70630317fe09@e27g2000yqd.googlegroups.com> Message-ID: On Dec 3, 2:03?pm, Mike Driscoll wrote: > On Dec 3, 3:42?pm, paul wrote: > > > > > > > I have been experiencing strange thread behavior when I pass a message > > received via a Queue to a wx.PostEvent method (from wxPython). The > > relevant code in the thread is: > > > def run(self): > > ? ? while self.is_running: > > ? ? ? ? task = self.queue.get() > > ? ? ? ? wx.PostEvent(self.app.handle_task, task) > > > self.queue is a Queue.Queue instance and self.app is a wx.Window > > instance > > > I have a case where two items are placed in the queue one after the > > other, and it appears that only the first item is passed to > > wx.PostEvent. ?If I place a time.sleep(0.1) call anywhere within the > > while loop, both items get passed to wx.PostEvent. ?It works if I put > > time.sleep before the self.queue.get(), in between get() and PostEvent > > () or after PostEvent(). ?So it seems like a short delay is enough to > > get two items handled, although it doesn't seem to matter where I > > place the delay within the while loop. ?Does someone know what might > > explain this behavior? ?Thanks. > > [Note: I cross-posted this to wxPython where Paul had also cross- > posted] > > Not sure if this will help or not, but see the following article on > the wxPython wiki: > > http://wiki.wxpython.org/LongRunningTasks > > There's a section called "More Tips" where Queues are discussed. Robin > Dunn (creator of wxPython) seems to recommend using wx.CallAfter there > rather than PostEvent. > > ------------------- > Mike Driscoll > > Blog: ?http://blog.pythonlibrary.org I apologize -- I meant to type wx.CallAfter instead of wx.PostEvent in my posting here (I've actually tried both approaches and did not see any difference...). I've looked over the LongRunningTasks wiki. I'll look at it again! From pavel.skvazh at gmail.com Thu Dec 3 17:56:55 2009 From: pavel.skvazh at gmail.com (Pavel Skvazh) Date: Thu, 3 Dec 2009 14:56:55 -0800 (PST) Subject: Overriding module's class Message-ID: Is it possible to override a class in the module or the module itself that is imported across the project to add new methods to it? For example I've got module 'a' with class A from a import A but I don't want to add a method to that A class not just in this unit, but across the project, so everywhere I'll import class A - it would be a modified one. Thank you. From Ognjen at mailshack.com Thu Dec 3 18:05:32 2009 From: Ognjen at mailshack.com (Ognjen Bezanov) Date: Thu, 03 Dec 2009 23:05:32 +0000 Subject: Bored. In-Reply-To: References: <16097008-372c-4522-889d-a78319c3575c@b2g2000yqi.googlegroups.com> Message-ID: <4B18443C.8090406@mailshack.com> Anssi Saari wrote: > Necronymouse writes: > >> Hello, I am learning python for about 2 years and I am bored. Not with >> python but I have a little problem, when i want to write something I >> realise that somebody had alredy written it! So i don?t want to make a >> copy of something but i wanna get better in python skills. Don?t you >> know what I should do? > > If I may propose something, I'm pretty annoyed that it's so hard to > get contact and calendar data out of my Nokia phone. However, there's > Python available for Symbian phones and the implementation is supposed > to have access to that data on the phone... So a calendar and contacts > sync tool would be a nice thing. > Also take into account, a lot of open source projects out there would not mind help! I host two (public) open source projects, and would love to have more development help from people interested in them! Find a project which you would find interesting, then ask them if you can join. You would not get to do something from scratch, but you would be able to help further develop the project, perhaps even extend it in some way you want to. From vmail at mycircuit.org Thu Dec 3 18:18:06 2009 From: vmail at mycircuit.org (Peter) Date: Fri, 04 Dec 2009 00:18:06 +0100 Subject: testing command line scripts that use optparse Message-ID: <4B18472E.7040801@mycircuit.org> Hi I have a script like this: def doit(input, output): parser = OptionParser() parser.add_option("-a", "--accounts", dest="accounts", default="all", help="list available accounts") ... (options, args) = parser.parse_args() # main driver if __name__ == "__main__": import sys doit(sys.stdin, sys.stdout) that I would like to test like this: def test_accounts(self): input = """-aRoot""" output = """Results""" self.runtest(input, output) def runtest(self, input, expected): inputStream = cStringIO.StringIO(input) actual = cStringIO.StringIO() doit(inputStream, actual) assert_equal(actual.getvalue(), expected) But when running test_accounts, I get: ... File "/usr/local/python2.6/lib/python2.6/optparse.py", line 1578, in error self.exit(2, "%s: error: %s\n" % (self.get_prog_name(), msg)) File "/usr/local/python2.6/lib/python2.6/optparse.py", line 1568, in exit sys.exit(status) SystemExit: 2 -------------------- >> begin captured stdout << --------------------- stdin optparse expects a file object and gets a cStringIO. What is the correct way to set up this ? Thanks for your help. Peter From torriem at gmail.com Thu Dec 3 18:40:05 2009 From: torriem at gmail.com (Michael Torrie) Date: Thu, 03 Dec 2009 16:40:05 -0700 Subject: Organization of GUIs In-Reply-To: <4b17cdb8$1@dnews.tpgi.com.au> References: <424dcb65-735c-4779-ae0a-5c4e662b24ac@b36g2000prf.googlegroups.com> <4b17cdb8$1@dnews.tpgi.com.au> Message-ID: <4B184C55.6070606@gmail.com> Lie Ryan wrote: > On 12/4/2009 12:44 AM, Michael Mossey wrote: >> I have a question about typical organization of GUIs. I will be using >> PyQt. >> > > Model-View-Controller (MVC) pattern. > > Model - all the business logic lives in the model. > View - your GUI > Controller - Takes input No, you've got it wrong: Model - Your data or database, some rules to enforce integrity Controller - your business logic View - Your gui, takes input From kw at codebykevin.com Thu Dec 3 18:42:52 2009 From: kw at codebykevin.com (Kevin Walzer) Date: Thu, 03 Dec 2009 18:42:52 -0500 Subject: Help in wxpython In-Reply-To: References: <86b3db7d0912020020k51cf6bc8me0bc543214c582f1@mail.gmail.com> Message-ID: <82524$4b184cfc$4275d90a$14696@FUSE.NET> > Madhura, Sorry to be a bit off-topic, but, I would really recommend you > to use pygtk instead of wx. > For one thing, the developers at pygtk are very active (they have their > mailing list as well ) and it comes by default with python on almost all > linux distros. You can also easily install it on windows. > > Most important, the api for pygtk is closely similar to wx. > Not to mention the quick responses you will get with pygtk related > problems. > If you want to include the Mac in your distribution, PyGtk isn't a good choice. Native support is quite experimental at this point, which basically means you'll be running it under X11. (WingIDE's Mac version runs on PyGTK, and it doesn't feel native at all.) -- Kevin Walzer Code by Kevin http://www.codebykevin.com From michael at stroeder.com Thu Dec 3 18:52:35 2009 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Fri, 04 Dec 2009 00:52:35 +0100 Subject: UnicodeDecodeError? Argh! Nothing works! I'm tired and hurting and... In-Reply-To: References: <031bc732$0$1336$c3e8da3@news.astraweb.com> Message-ID: <3jvlu6-0g4.ln1@nb2.stroeder.com> Aahz wrote: > In article <031bc732$0$1336$c3e8da3 at news.astraweb.com>, > Steven D'Aprano wrote: >> Good grief, it's about six weeks away from 2010 and Thunderbird still >> uses mbox as it's default mail box format. Hello, the nineties called, >> they want their mail formats back! Are the tbird developers on crack or >> something? I can't believe that they're still using that crappy format. > > Just to be contrary, I *like* mbox. Me too. :-) Ciao, Michael. From debatem1 at gmail.com Thu Dec 3 18:54:47 2009 From: debatem1 at gmail.com (geremy condra) Date: Thu, 3 Dec 2009 18:54:47 -0500 Subject: python bijection In-Reply-To: <4B17FBFE.8070903@egenix.com> References: <7n39ojF3jj6iuU1@mid.individual.net> <12c55890-118d-4655-b6c0-c908c9734a17@a32g2000yqm.googlegroups.com> <85100df7-a8b0-47e9-a854-ba8a8a2f3b98@r31g2000vbi.googlegroups.com> <4B17A960.1090700@egenix.com> <4B17FBFE.8070903@egenix.com> Message-ID: On Thu, Dec 3, 2009 at 12:57 PM, M.-A. Lemburg wrote: > geremy condra wrote: >> On Thu, Dec 3, 2009 at 7:04 AM, M.-A. Lemburg wrote: >>> I think the only major CS data type missing from Python is some >>> form of (fast) directed graph implementation ? la kjGraph: >>> >>> ? ?http://gadfly.sourceforge.net/kjbuckets.html >>> >>> With these, you can easily build all sorts of relations between >>> objects and apply fast operations on them. In fact, it should then >>> be possible to build a complete relational database in Python >>> (along the lines of Gadfly). >> >> If you're in the market for a Python graph library, you may want >> to check out Graphine- I'm obviously biased (I wrote most of it) >> but it has a few more bells and whistles than kjbuckets, and is >> pretty darned easy to use. It also supports undirected and >> bridge graphs. > > Thanks for the hint :-) > > The lib looks nice and would probably serve as a good prototype > for writing a new built-in type for Python. I suspect that it would have a better chance at getting into collections than becoming a builtin, but who knows. I'd just like to have something like it in the standard library. > This would have to be written in C, though, That's currently in the works, along with database backing. We'd welcome any help though... hint, hint... > and come under a Python compatible license. I'm willing to dual license under the Python license if there were a substantial interest in doing so, and I'm confident that the other authors and maintainers would feel the same way. The question in my mind is whether such an interest exists. > With the built-in feature moratorium > currently in place, there's about 1.5-2 years time to get this > done; perhaps a good GSoC project for next year :-) I'd love to have Graphine be a GSoC project, although if the target were to get it into collections the moratorium wouldn't change the timeline AFAICS. Geremy Condra From steve at REMOVE-THIS-cybersource.com.au Thu Dec 3 19:07:51 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 04 Dec 2009 00:07:51 GMT Subject: Insane Problem References: <4dc0cfea0912021218g797f782esa2c174923b6ac492@mail.gmail.com> <4B16D739.5080408@mrabarnett.plus.com> <4dc0cfea0912030307j7556eb06j469ccc4e6a29d1ee@mail.gmail.com> <4dc0cfea0912030502x1532319dy92e6f62868b6ef5e@mail.gmail.com> Message-ID: <00a1d75d$0$26893$c3e8da3@news.astraweb.com> On Thu, 03 Dec 2009 10:13:14 -0500, Carsten Haese wrote: > Victor Subervi wrote: >> I believe I mentioned in my first post that the "print test" does print >> the exact fields being called from the referring page. > > Was any part of "What do the print statements actually print? Please > copy and paste their output." unclear to you in any way? > >> Perhaps this >> is a bug in the cgi interface? > > Unlikely. > > It's much more likely that whatever frankencode you stitched together > from examples you found on the internet without understanding how they > work is doing something unexpected, and you are unable to diagnose the > problem because you don't understand how your code works. Oh come on, how likely is that??? It's much more likely that the original poster has discovered a bug in the standard library that thousands of users before him never noticed! *wink* -- Steven From timmygee at gmail.com Thu Dec 3 19:26:01 2009 From: timmygee at gmail.com (TimmyGee) Date: Thu, 3 Dec 2009 16:26:01 -0800 (PST) Subject: Question on Python as career References: <614b8dde-324b-4d54-8e73-7a96e4c0b1cf@a21g2000yqc.googlegroups.com> Message-ID: <6fde3200-984a-4948-9f94-6c0f9ebfcc07@r24g2000prf.googlegroups.com> On Dec 4, 2:48?am, Grant Edwards wrote: > On 2009-12-03, r0g wrote: > > >>> I have done one MA in Linguistics, did a PhD in Natural > >>> Language Processing and doing a Post Doctoral now. ... > > >>> After I complete my Post Doctoral which may be only 2-3 months > >>> away, with this knowledge can I join IT? > > Getting involved in an open source project or two may bolster your CV > > and help you get your foot in the door. > > Having some real experience would help offset the liability of > having a PhD. > > 1/2 ;) > > -- > Grant Edwards ? ? ? ? ? ? ? ? ? grante ? ? ? ? ? ? Yow! Eisenhower!! ?Your > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? at ? ? ? ? ? ? ? mimeograph machine upsets > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?visi.com ? ? ? ? ? ?my stomach!! www.rentacoder.com? From steve at REMOVE-THIS-cybersource.com.au Thu Dec 3 19:30:27 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 04 Dec 2009 00:30:27 GMT Subject: Declaring a class level nested class? References: Message-ID: <00a1dca8$0$26893$c3e8da3@news.astraweb.com> On Thu, 03 Dec 2009 06:59:43 -0800, cmckenzie wrote: > It was late when I posted my example, so I don't think I made my > question clear enough. I want to be able to construct a class level > class variable, so its global to the class, then reference it from a > class method. My brain is spinning, because you seem to be using terms in ways that aren't common in Python circles (or at least not familiar to *me*). This makes it really hard for me to be sure I understand you. You say you want a "class level class variable" -- what do you mean by that? What's "class level" mean to you? When you say "class variable", do you mean "a variable that is a class", like a string variable is a variable that is a string, or do you mean an attribute of the class? What do you mean by "global to the class"? In your code sample, you say: class module: nestedClass but nestedClass isn't defined. Assuming nestedClass already exists, defined elsewhere (which implies it is NOT nested at all!) it would be syntactically legal, but meaningless. It would be as pointless as this: class module: # Define class [1, 2, 3] # create a list and throw it away immediately Where is nestedClass defined? Outside the class "module"? Inside the class? If so, where? I *think* you mean you want a class attribute which happens to hold a class, which you want to be nested, but I'm not sure. If that's what you want, you would write it like this: class module: # Horrible name, because module is a term already # used in Python for something else class nestedclass: pass Once you do that, you have a class "module" containing a nested class "nestedclass" which is available as a class-attribute "module.nestedclass". > The declaration of a class level nestedClass class variable is wrong, > but I was hoping someone could just say, "dummy, this is how to declare > a class variable when you can't construct it just yet", Python doesn't need declarations. If you can't declare something, don't. You could put a placeholder and test for it: class K: attribute = None # Placeholder for the real value. def method(self): if self.attribute is None: print "attribute not initialised yet, this design sucks" else: print "do something useful" or simply catch the AttributeError: class K: def method(self): try: self.attribute except AttributeError: print "attribute not initialised yet, this design sucks" else: print "do something useful" > or "you have to > construct an empty version of nestedClass at the class level, then just > re-construct it with any parameters during __init__". > > class module: > nestedClass > > def __init__(): > self.nestedClass = nested(10) > print self.nestedClass.nestedVar That gives every instance of "module" its own instance-level attribute called "nestedClass". It will only work if nested is a global-level function. To call the method called "nested" as you probably intend, you need to do this: def __init__(): self.nestedClass = self.nested(10) print self.nestedClass.nestedVar which still makes nestedClass an attribute on the instance, not the class. To make it a class attribute, you have to refer to the class directly. Either of these will do, although the first is better because it will do the right thing if you subclass: self.__class__.nestedClass = self.nested(10) module.nestedClass = self.nested(10) > class nested(): > nestedVar = 1 > def __init__(self, value): > nestedVar = value > print "Initialized..." Given that every instance is given an attribute nestedVar, what's the point of the class attribute "nestedVar"? It's never used. -- Steven From steve at REMOVE-THIS-cybersource.com.au Thu Dec 3 19:33:57 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 04 Dec 2009 00:33:57 GMT Subject: UnicodeDecodeError? Argh! Nothing works! I'm tired and hurting and... References: <031bc732$0$1336$c3e8da3@news.astraweb.com> <3jvlu6-0g4.ln1@nb2.stroeder.com> Message-ID: <00a1dd7b$0$26893$c3e8da3@news.astraweb.com> On Fri, 04 Dec 2009 00:52:35 +0100, Michael Str?der wrote: > Aahz wrote: >> In article <031bc732$0$1336$c3e8da3 at news.astraweb.com>, Steven D'Aprano >> wrote: >>> Good grief, it's about six weeks away from 2010 and Thunderbird still >>> uses mbox as it's default mail box format. Hello, the nineties called, >>> they want their mail formats back! Are the tbird developers on crack >>> or something? I can't believe that they're still using that crappy >>> format. >> >> Just to be contrary, I *like* mbox. > > Me too. :-) Why? What features or benefits of mbox do you see that make up for it's disadvantages? -- Steven From rhodri at wildebst.demon.co.uk Thu Dec 3 19:44:26 2009 From: rhodri at wildebst.demon.co.uk (Rhodri James) Date: Fri, 04 Dec 2009 00:44:26 -0000 Subject: Which is more pythonic? In-Reply-To: <1be78d220912030741p39e966e0s96bc82c61818c8e0@mail.gmail.com> References: <1be78d220912030741p39e966e0s96bc82c61818c8e0@mail.gmail.com> Message-ID: On Thu, 03 Dec 2009 15:41:56 -0000, Filip Gruszczy?ski wrote: > I have just written a very small snippet of code and started thinking, > which version would be more pythonic. Basically, I am adding a list of > string to combo box in qt. So, the most obvious way is: > > for choice in self.__choices: > choicesBox.addItem(choice) > > But I could also do: > > map(self.__choices, choicesBox.addItem) > > or > > [choicesBox.addItem(choice) for choice in self.__choices] > > I guess map version would be fastest and explicit for is the slowest > version. I vaguely recall someone (Steven?) doing some timings that came up with the opposite answer. The list comprehension is probably the worst performing, since it creates a whole new list of the return values of choicesBox.addItem(choice), then throws it away. > However, the first, most obvious way seems most clear to me > and I don't have to care about speed with adding elements to combo > box. Still, it's two lines instead of one, so maybe it's not the best. > So, which one is? Your instincts are right, the explicit for loop is the more pythonic way in this case. More efficient or not, map() isn't a particularly pythonic way to do things, and there's no point using a list comprehension when you aren't building a list. -- Rhodri James *-* Wildebeest Herder to the Masses From python at mrabarnett.plus.com Thu Dec 3 19:52:31 2009 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 04 Dec 2009 00:52:31 +0000 Subject: Which is more pythonic? In-Reply-To: <1be78d220912030741p39e966e0s96bc82c61818c8e0@mail.gmail.com> References: <1be78d220912030741p39e966e0s96bc82c61818c8e0@mail.gmail.com> Message-ID: <4B185D4F.40704@mrabarnett.plus.com> Filip Gruszczy?ski wrote: > I have just written a very small snippet of code and started thinking, > which version would be more pythonic. Basically, I am adding a list of > string to combo box in qt. So, the most obvious way is: > > for choice in self.__choices: > choicesBox.addItem(choice) > > But I could also do: > > map(self.__choices, choicesBox.addItem) > > or > > [choicesBox.addItem(choice) for choice in self.__choices] > > I guess map version would be fastest and explicit for is the slowest > version. However, the first, most obvious way seems most clear to me > and I don't have to care about speed with adding elements to combo > box. Still, it's two lines instead of one, so maybe it's not the best. > So, which one is? > Is .addItem() a function (returns a result) or a procedure (called for its side-effect, ie adding an item to a collection)? It's a procedure, so the first form is Pythonic. If it was a function then the third form would be Pythonic. The second form is what you would've done before list comprehensions were introduced. From drobinow at gmail.com Thu Dec 3 19:59:30 2009 From: drobinow at gmail.com (David Robinow) Date: Thu, 3 Dec 2009 19:59:30 -0500 Subject: UnicodeDecodeError? Argh! Nothing works! I'm tired and hurting and... In-Reply-To: <00a1dd7b$0$26893$c3e8da3@news.astraweb.com> References: <031bc732$0$1336$c3e8da3@news.astraweb.com> <3jvlu6-0g4.ln1@nb2.stroeder.com> <00a1dd7b$0$26893$c3e8da3@news.astraweb.com> Message-ID: <4eb0089f0912031659r4f7e5a6em31d3ac9662089b20@mail.gmail.com> On Thu, Dec 3, 2009 at 7:33 PM, Steven D'Aprano wrote: > On Fri, 04 Dec 2009 00:52:35 +0100, Michael Str?der wrote: > >> Aahz wrote: >>> Just to be contrary, I *like* mbox. >> >> Me too. :-) > > > Why? What features or benefits of mbox do you see that make up for it's > disadvantages? I've never heard of mbox. Is it written in Python? From steve at REMOVE-THIS-cybersource.com.au Thu Dec 3 20:21:28 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 04 Dec 2009 01:21:28 GMT Subject: slightly OT: Python BootCamp References: <36dec4ff0911281815p583598i43a476bc66083e29@mail.gmail.com> Message-ID: <00a1e89d$0$26893$c3e8da3@news.astraweb.com> On Thu, 03 Dec 2009 16:20:24 -0500, J wrote: > The difference between me (learning a new language) and the guy teaching > (who knows it inside and out) I don't know about that. He's teaching some pretty atrocious habits. See below. > His code: [...] > for (exten, list) in files.iteritems(): > try: > f=open('extensions-%s.txt' % exten,'w') > f.write('\n'.join(list)) > except: > assert 0, 'Unable to create output file extensions-%s.txt.' % > exten Wrong! Bad! Don't do this!!! There are no less than five errors here. Some people might argue that given the context (a short script), none of them matter in practice. For a script you use once then throw away, maybe. I've written sloppy scripts myself, and lazy can be a virtue. But *teaching* sloppy is a terrible thing -- even if you disagree that this are the sorts of errors that matter in this script, they are bad, bad habits that you should avoid. Error #1: Bare excepts are nearly always wrong. Bare excepts catch *everything*, including exceptions caused by bugs in your code. Including the user trying to interrupt the code with ctrl-D. Don't use bare excepts unless you know what you're doing. Catch the specific exceptions you actually want instead. Error #2: Wrapping multiple operations in a single try block. This conflates errors in four different operations: generate the file name open the file merge strings into a single newline-delimited string write the strings to the file The instructor assumes that only the open can fail. That's incorrect. His try...except will mask coding errors, as well as conflating open errors and write errors. Error #3: Throwing away useful debugging information and replacing it with a generic error message that isn't useful. If an error occurs, Python will generate a useful exception telling exactly what error occurred and why. If it happens in a file operation, it will include the error code. The given code throws that away and replaces it with a generic error that tells you nothing except that an assertion failed. Error #4: Using assert for anything other than what it was designed for. If you want to break this script, run it with optimizations switched on and trigger a failure-mode (perhaps by removing write-permission from the current directory). With optimizations switched on, the assert statement will be compiled away, and the script will catch the open errors and ignore them. Error #5: Failing to close each file after you're done with it. Python does close files for you, if you don't do it yourself, but when it does so is implementation dependent. Some versions of Python won't close them until the very end of the program, as it closes down. That means that if the list of files is large enough, you will run out of file descriptors and the program will stop working. How would I re-write this? Just get rid of the try block and add a close: for (exten, list) in files.iteritems(): f=open('extensions-%s.txt' % exten,'w') f.write('\n'.join(list)) f.close() If an error occurs, Python's normal exception-raising mechanism will halt the script and print a useful error message. If you want to mask the traceback from the user (but I'm not sure why you would want to...) then wrap the entire loop in a single try, catching keyboard interrupt separately: try: for (exten, list) in files.iteritems(): f=open('extensions-%s.txt' % exten,'w') f.write('\n'.join(list)) f.close() except KeyboardInterrupt: print "Interrupted by user." raise except Exception: raise ValueError('failed for some unspecified reason') That's still not quite "best practice" -- best practice would be to use a with block, but (to my shame) I'm not entirely familiar with that so I'll leave it for others. -- Steven From steve at REMOVE-THIS-cybersource.com.au Thu Dec 3 20:27:11 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 04 Dec 2009 01:27:11 GMT Subject: UnicodeDecodeError? Argh! Nothing works! I'm tired and hurting and... References: <031bc732$0$1336$c3e8da3@news.astraweb.com> <3jvlu6-0g4.ln1@nb2.stroeder.com> <00a1dd7b$0$26893$c3e8da3@news.astraweb.com> Message-ID: <00a1e9f5$0$26893$c3e8da3@news.astraweb.com> On Thu, 03 Dec 2009 19:59:30 -0500, David Robinow wrote: > I've never heard of mbox. Is it written in Python? It is a file format used for storing email. Wikipedia is your friend: http://en.wikipedia.org/wiki/Mbox -- Steven From cjns1989 at gmail.com Thu Dec 3 20:47:55 2009 From: cjns1989 at gmail.com (Chris Jones) Date: Thu, 03 Dec 2009 20:47:55 -0500 Subject: UnicodeDecodeError? Argh! Nothing works! I'm tired and hurting and... In-Reply-To: <4eb0089f0912031659r4f7e5a6em31d3ac9662089b20@mail.gmail.com> References: <031bc732$0$1336$c3e8da3@news.astraweb.com> <3jvlu6-0g4.ln1@nb2.stroeder.com> <00a1dd7b$0$26893$c3e8da3@news.astraweb.com> <4eb0089f0912031659r4f7e5a6em31d3ac9662089b20@mail.gmail.com> Message-ID: <20091204014755.GB2966@turki.gavron.org> On Thu, Dec 03, 2009 at 07:59:30PM EST, David Robinow wrote: > On Thu, Dec 3, 2009 at 7:33 PM, Steven D'Aprano > wrote: > > On Fri, 04 Dec 2009 00:52:35 +0100, Michael Str?der wrote: > > > >> Aahz wrote: > >>> Just to be contrary, I *like* mbox. > >> > >> Me too. :-) > > > > > > Why? What features or benefits of mbox do you see that make up for it's > > disadvantages? > > I've never heard of mbox. Is it written in Python? English, actually.. short for mail box, I gather. CJ From aioe.org at technicalbloke.com Thu Dec 3 21:08:28 2009 From: aioe.org at technicalbloke.com (r0g) Date: Fri, 04 Dec 2009 02:08:28 +0000 Subject: Question on Python as career References: <614b8dde-324b-4d54-8e73-7a96e4c0b1cf@a21g2000yqc.googlegroups.com> <6fde3200-984a-4948-9f94-6c0f9ebfcc07@r24g2000prf.googlegroups.com> Message-ID: TimmyGee wrote: > On Dec 4, 2:48 am, Grant Edwards wrote: >> On 2009-12-03, r0g wrote: >> >>>>> I have done one MA in Linguistics, did a PhD in Natural >>>>> Language Processing and doing a Post Doctoral now. ... >>>>> After I complete my Post Doctoral which may be only 2-3 months >>>>> away, with this knowledge can I join IT? >>> Getting involved in an open source project or two may bolster your CV >>> and help you get your foot in the door. >> Having some real experience would help offset the liability of >> having a PhD. >> >> 1/2 ;) >> >> -- >> Grant Edwards grante Yow! Eisenhower!! Your >> at mimeograph machine upsets >> visi.com my stomach!! > > www.rentacoder.com? Euwww, that's not an experience I'd recommend! Roger. From dreadpiratejeff at gmail.com Thu Dec 3 21:09:48 2009 From: dreadpiratejeff at gmail.com (J) Date: Fri, 4 Dec 2009 10:09:48 +0800 Subject: slightly OT: Python BootCamp In-Reply-To: <00a1e89d$0$26893$c3e8da3@news.astraweb.com> References: <36dec4ff0911281815p583598i43a476bc66083e29@mail.gmail.com> <00a1e89d$0$26893$c3e8da3@news.astraweb.com> Message-ID: <36dec4ff0912031809m16d9a7b1xccbd568fa7fe1685@mail.gmail.com> On Fri, Dec 4, 2009 at 09:21, Steven D'Aprano wrote: > On Thu, 03 Dec 2009 16:20:24 -0500, J wrote: > >> The difference between me (learning a new language) and the guy teaching >> (who knows it inside and out) > > I don't know about that. He's teaching some pretty atrocious habits. See > below. Ok... I snipped it because I don't know enough really to comment on any one thing... I supposed in his defense, I could say that the point of the exercise had nothing to do with exception handling, and the part that DID handle exceptions covered a good bit on actually catching individual exceptions for various things, as well as doing things like writing extensions to handle things. Also, consider that this is a "boot camp" that's geared toward getting you up to speed and writing functional code as quickly as possible. One week has gone from "This is a string variable and you can iterate it" to This is file operation, OS and SYS usage, exception handling, etc... really, just in 4 days. The last day, I think just covers database access and operations and a brief overview of python web development and the cgi module. It's more an intense introduction for people who already know how to write code (not necessarily, though, ones who know how to write it properly) than it is a formal "This is how you write code the right way". I'm not necessarily trying to make excuses, but, that's my take on it. All I wanted to get out of it was familiarity with Python, a refresh of OOP practices, and the ability to get REALLY started on some projects quickly, making the code pretty and better afterwards... Thankfully, I've got places like comp.lang.python and various books and online references to help me take what I know and make it better, but as a starting point, at least, it's not terrible. Now, that all being said... how atrocious was my OWN code sample. I'm a firm believer in constructive criticism, so I'd like to know how I'm doing so far. I can provide other samples if necessary, because I DO want to learn to write this cleanly and properly. Keep in mind that while I DO know how to write programs, the only thing I've really written in in 3 years now is BASH. It's been ages since I did anything in any other languages to amount to anything, and if I did, it was something quick and dirty that got the job done and that was that, not something I'd really want to give to anyone else to use... Hackery if you will... Cheers, Jeff -- Ted Turner - "Sports is like a war without the killing." - http://www.brainyquote.com/quotes/authors/t/ted_turner.html From bengioe at gmail.com Thu Dec 3 21:09:58 2009 From: bengioe at gmail.com (Emmanuel Bengio) Date: Thu, 3 Dec 2009 21:09:58 -0500 Subject: Directly converting Python to C using the C API Message-ID: I'm fairly new to the python world, and I often heard critics about it's speed, and also about it's "non-compilability". Then I thought, there is a complete C API that manages Python itself. Would it be feasible to transform pure Python code into pure Python "C API" code? It would spare the parsing time, which seems to be the an important factor in Python's speed. Given the following example: x=0 for i in xrange(100000): x+=x*i On my machine, this takes 79ms to run. while this: PyObject* x = PyInt_FromLong(0); int i; for (i=0;i<100000;i++) { x=PyNumber_Add(x,PyNumber_Multiply(x,PyInt_FromLong(i))); } takes about 16 ms to run. Any thoughts? -- Emmanuel Bengio -------------- next part -------------- An HTML attachment was scrubbed... URL: From benjamin.kaplan at case.edu Thu Dec 3 21:16:26 2009 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Thu, 3 Dec 2009 21:16:26 -0500 Subject: Organization of GUIs In-Reply-To: References: <424dcb65-735c-4779-ae0a-5c4e662b24ac@b36g2000prf.googlegroups.com> <4b17cdb8$1@dnews.tpgi.com.au> Message-ID: On Thu, Dec 3, 2009 at 9:59 AM, Michael Mossey wrote: > On Dec 3, 6:38?am, Lie Ryan wrote: >> On 12/4/2009 12:44 AM, Michael Mossey wrote: >> >> > I have a question about typical organization of GUIs. I will be using >> > PyQt. >> >> Model-View-Controller (MVC) pattern. >> >> Model - all the business logic lives in the model. >> View - your GUI >> Controller - Takes input >> >> Controller notifies Model if there is user input; Model notifies View if >> there is an update in the model; View "notifies" user if there is an >> update in the model; User "notifies" controller of the changes wanted. >> >> http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller > > I'm aware of Model-View-Controller, but my question is broader than > that for a couple reasons: > > View can be fine-grained. Often the View consists of a number of GUI > objects. Some people write this in a democratic arrangement---they all > talk to each other. This can make analyzing system behavior > complicated. Hence my proposal for a hierarchy. > Ideally, the controller should be the top of that hierarchy. > Also, often different parts of the Model talk to different parts of > the View. The question, then, is whether both the Model and View > should be structured hierarchically so that all messages pass through > a "master" or "root" object before going to the other Model/View, and > messages within a Model or View should only move along the hierarchy. > The model should never ever talk directly to the view. The whole point in using MVC is that the model parses the data, but doesn't care what you do with it. The controller takes the data from the model and processes it but doesn't care how the data is obtained, stored, or displayed. The controller then sends data to the view, which doesn't care how you got it or what you did with it. All it knows is that it's given data and it knows how to display it. Then, when the user interacts with the view, it sends the new data back to the controller which either passes it along to the model or tells the view (or another part of the view) to do something else. > In other words, you can easily make a complete mess of MVC. > -- > http://mail.python.org/mailman/listinfo/python-list > From clp2 at rebertia.com Thu Dec 3 21:19:07 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Thu, 3 Dec 2009 18:19:07 -0800 Subject: Directly converting Python to C using the C API In-Reply-To: References: Message-ID: <50697b2c0912031819t2952e936ye2e8c20acca87aee@mail.gmail.com> On Thu, Dec 3, 2009 at 6:09 PM, Emmanuel Bengio wrote: > I'm fairly new to the python world, and I often heard critics about it's > speed, and also about it's "non-compilability". > Then I thought, there is a complete C API that manages Python itself. > Would it be feasible to transform pure Python code into pure Python "C API" > code? It would spare the parsing time, which seems to be the an important > factor in Python's speed. > > Given the following example: > x=0 > for i in xrange(100000): > ?? ?x+=x*i > On my machine, this takes 79ms to run. > while this: > PyObject* x = PyInt_FromLong(0); > int i; > for (i=0;i<100000;i++) > { > ?? ?x=PyNumber_Add(x,PyNumber_Multiply(x,PyInt_FromLong(i))); > } > takes about 16 ms to run. > Any thoughts? You're going to have to check that xrange() hasn't been rebound for starters. Cheers, Chris -- http://blog.rebertia.com From aioe.org at technicalbloke.com Thu Dec 3 21:20:09 2009 From: aioe.org at technicalbloke.com (r0g) Date: Fri, 04 Dec 2009 02:20:09 +0000 Subject: More elegant solution for diffing two sequences References: <7nqorbF3n7go3U1@mid.uni-berlin.de> <4b183159@dnews.tpgi.com.au> Message-ID: Lie Ryan wrote: > On 12/4/2009 8:28 AM, Ulrich Eckhardt wrote: >> I'm trying to write some code to diff two fonts. What I have is every >> character (glyph) of the two fonts in a list. I know that the list is >> sorted >> by the codepoints of the characters. What I'd like to ask is whether >> there >> is a more elegant solution to the loop below or whether there are any >> rough >> corners in my code (see below). Note that I'm targeting Python 2, not >> 3 yet. >> > > Use sets: > > glyph_1 = set(font1.glyphs) > glyph_2 = set(font2.glyphs) > only_in_1 = glyph_1 - glyph_2 > only_in_2 = glyph_2 - glyph_1 > in_both = glyph_1 & glyph_2 > > that is assuming font1.glyphs's value are hashable. Ooh that's lovely! I wonder why I've never stumbled across sets in python before? These are SO going to be my favourite new things for the next few weeks. :D Roger. From philip at semanchuk.com Thu Dec 3 21:21:02 2009 From: philip at semanchuk.com (Philip Semanchuk) Date: Thu, 3 Dec 2009 21:21:02 -0500 Subject: Directly converting Python to C using the C API In-Reply-To: References: Message-ID: <06569A64-1D05-4B17-99E3-F7D83F6F2C0D@semanchuk.com> On Dec 3, 2009, at 9:09 PM, Emmanuel Bengio wrote: > I'm fairly new to the python world, and I often heard critics about > it's > speed, and also about it's "non-compilability". > Then I thought, there is a complete C API that manages Python itself. > Would it be feasible to transform pure Python code into pure Python > "C API" > code? It would spare the parsing time, which seems to be the an > important > factor in Python's speed. > > > Given the following example: > x=0 > for i in xrange(100000): > x+=x*i > > On my machine, this takes 79ms to run. > > while this: > PyObject* x = PyInt_FromLong(0); > int i; > for (i=0;i<100000;i++) > { > x=PyNumber_Add(x,PyNumber_Multiply(x,PyInt_FromLong(i))); > } > takes about 16 ms to run. > > Any thoughts? This is such a good idea that it has become a popular project: http://www.cython.org/ From lie.1296 at gmail.com Thu Dec 3 21:39:24 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Fri, 04 Dec 2009 13:39:24 +1100 Subject: Organization of GUIs In-Reply-To: References: <424dcb65-735c-4779-ae0a-5c4e662b24ac@b36g2000prf.googlegroups.com> <4b17cdb8$1@dnews.tpgi.com.au> Message-ID: <4b1876d6@dnews.tpgi.com.au> On 12/4/2009 10:40 AM, Michael Torrie wrote: > Lie Ryan wrote: >> On 12/4/2009 12:44 AM, Michael Mossey wrote: >>> I have a question about typical organization of GUIs. I will be using >>> PyQt. >>> >> >> Model-View-Controller (MVC) pattern. >> >> Model - all the business logic lives in the model. >> View - your GUI >> Controller - Takes input > > No, you've got it wrong: > > Model - Your data or database, some rules to enforce integrity > Controller - your business logic > View - Your gui, takes input perhaps you meant MVP: """ * The model is an interface defining the data to be displayed or otherwise acted upon in the user interface. * The view is an interface that displays data (the model) and routes user commands (events) to the presenter to act upon that data. * The presenter acts upon the model and the view. It retrieves data from repositories (the model), persists it, and formats it for display in the view. """ MVC: """ Model Is the domain-specific representation of the data upon which the application operates. Domain logic adds meaning to raw data (for example, calculating whether today is the user's birthday, or the totals, taxes, and shipping charges for shopping cart items). When a model changes its state, it notifies its associated views so they can refresh. Many applications use a persistent storage mechanism (such as a database) to store data. MVC does not specifically mention the data access layer because it is understood to be underneath or encapsulated by the model. Models are not data access objects; however, in very simple apps that have little domain logic there is no real distinction to be made. Also, the ActiveRecord is an accepted design pattern which merges domain logic and data access code - a model which knows how to persist itself. View Renders the model into a form suitable for interaction, typically a user interface element. Multiple views can exist for a single model for different purposes. Controller Receives input and initiates a response by making calls on model objects. """ [*] all source taken from wikipedia. From rami.chowdhury at gmail.com Thu Dec 3 21:45:29 2009 From: rami.chowdhury at gmail.com (Rami Chowdhury) Date: Thu, 3 Dec 2009 18:45:29 -0800 Subject: memory error In-Reply-To: <1482CDE5CD38BC4B99F6182262ADCB2925FAA4@EXCHVS02.ad.sfwmd.gov> References: <6e8c880b-a9f4-4063-8e77-e77679f6b54c@m3g2000yqf.googlegroups.com> <1482CDE5CD38BC4B99F6182262ADCB2925FAA4@EXCHVS02.ad.sfwmd.gov> Message-ID: <200912031845.29583.rami.chowdhury@gmail.com> On Thursday 03 December 2009 05:51:05 Ahmed, Shakir wrote: > I am getting a memory error while executing a script. Any idea is > highly appreciated. > > Error message: " The instruction at "0x1b009032" referenced memory at > "0x00000804:, The memory could not be "written" > > This error is appearing and I have to exit from the script. > > Thanks > sk > I'm afraid you'll really have to provide us a little more information. When does the error happen? At the beginning of the script? Halfway through? When you're closing the program? I don't know anything about Pythonwin, so I won't comment further, but IME Python scripts rarely get direct memory access errors so I would suspect a problem in Pythonwin. ---- Rami Chowdhury -----BEGIN GEEK CODE BLOCK----- Version: 3.1 GO d-(+++) s-:++ a-- C++> ULX+> P++ L++ E+ W+++ w-- PS+ PE t+ b+++ e++ !r z? ------END GEEK CODE BLOCK------ 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) From lie.1296 at gmail.com Thu Dec 3 21:46:53 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Fri, 04 Dec 2009 13:46:53 +1100 Subject: Which is more pythonic? In-Reply-To: References: <1be78d220912030741p39e966e0s96bc82c61818c8e0@mail.gmail.com> Message-ID: <4b187896$1@dnews.tpgi.com.au> On 12/4/2009 11:44 AM, Rhodri James wrote: >> map(self.__choices, choicesBox.addItem) >> >> or >> >> [choicesBox.addItem(choice) for choice in self.__choices] Aside from being pythonic or non-pythonic, using map or list comprehension with a method with side-effect is not the intention of functional programming; which strives to eliminates side-effect altogether. So it's unfunctional. The only pythonic form to use method with side effect is an explicit for. From lie.1296 at gmail.com Thu Dec 3 21:51:43 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Fri, 04 Dec 2009 13:51:43 +1100 Subject: memory error In-Reply-To: References: <6e8c880b-a9f4-4063-8e77-e77679f6b54c@m3g2000yqf.googlegroups.com> Message-ID: <4b1879b8$1@dnews.tpgi.com.au> On 12/4/2009 12:51 AM, Ahmed, Shakir wrote: > I am getting a memory error while executing a script. Any idea is highly > appreciated. > > Error message: " The instruction at "0x1b009032" referenced memory at > "0x00000804:, The memory could not be "written" > > This error is appearing and I have to exit from the script. > > Thanks > sk Would you mind telling what you were doing at that time? From lie.1296 at gmail.com Thu Dec 3 21:54:34 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Fri, 04 Dec 2009 13:54:34 +1100 Subject: can python do this? In-Reply-To: References: Message-ID: <4b187a63$1@dnews.tpgi.com.au> On 12/3/2009 4:55 AM, Anssi Saari wrote: > Rounak writes: > >> I am a complete newbie. I want to know if the following can be done >> using python or should I learn some other language: >> (Basically, these are applescripts that I wrote while I used Mac OS) >> 1.Web Page Image to Wallpaper: >> A script that takes the current image in a browser and sets it as a >> wallpaper. >> http://forums.obdev.at/viewtopic.php?f=24&t=3462 > > I don't know if any Linux web browsers are particularly scriptable. > Firefox at least is pretty much limited to opening URLs and some other > windows. OTOH, you can do that specific thing by just right clicking > on the image in question and selecting set as desktop background... Nope, you don't need to, you just need to find a way to pass the URL to your script and python can do the rest with urllib. Most browsers doesn't have functionality to pass url to an outside program, but with firefox you can be able to write an addon that do that (or perhaps onne is already available?). >> 2.Screenshot with name, format, Dropbox upload and public URL >> I used to run this script,type the name for screenshot and press return. >> The screenshot would be uploaded to Dropbox and public url would be >> copied to clipboard. >> http://forums.obdev.at/viewtopic.php?f=24&t=3448 If you're on linux, you can use ImageMagick's "import" or "scrot" with subprocess module to take screenshots. PIL (Python Imaging Library) can also do that more cleanly. Most windowing systems (GTK/Qt) also have their own ways (http://stackoverflow.com/questions/69645/take-a-screenshot-via-a-python-script-linux). You can use urllib and/or httplib to communicate with Dropbox. You just need to find the URLs to send HTTP POST to, and parse the resulting webpage to extract the public URL. (perhaps do some login as well, I don't know never used Dropbox) From timmygee at gmail.com Thu Dec 3 22:06:01 2009 From: timmygee at gmail.com (TimmyGee) Date: Thu, 3 Dec 2009 19:06:01 -0800 (PST) Subject: Question on Python as career References: <614b8dde-324b-4d54-8e73-7a96e4c0b1cf@a21g2000yqc.googlegroups.com> <6fde3200-984a-4948-9f94-6c0f9ebfcc07@r24g2000prf.googlegroups.com> Message-ID: <79474a9d-2def-49ba-9aa5-d5077ed3e695@m33g2000pri.googlegroups.com> On Dec 4, 1:08?pm, r0g wrote: > TimmyGee wrote: > > On Dec 4, 2:48 am, Grant Edwards wrote: > >> On 2009-12-03, r0g wrote: > > >>>>> I have done one MA in Linguistics, did a PhD in Natural > >>>>> Language Processing and doing a Post Doctoral now. ... > >>>>> After I complete my Post Doctoral which may be only 2-3 months > >>>>> away, with this knowledge can I join IT? > >>> Getting involved in an open source project or two may bolster your CV > >>> and help you get your foot in the door. > >> Having some real experience would help offset the liability of > >> having a PhD. > > >> 1/2 ;) > > >> -- > >> Grant Edwards ? ? ? ? ? ? ? ? ? grante ? ? ? ? ? ? Yow! Eisenhower!! ?Your > >> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? at ? ? ? ? ? ? ? mimeograph machine upsets > >> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?visi.com ? ? ? ? ? ?my stomach!! > > >www.rentacoder.com? > > Euwww, that's not an experience I'd recommend! > > Roger. Really? I was considering giving it a go one of these days. Not a good idea? From falk at mauve.rahul.net Thu Dec 3 22:07:42 2009 From: falk at mauve.rahul.net (Edward A. Falk) Date: Fri, 4 Dec 2009 03:07:42 +0000 (UTC) Subject: Which is more pythonic? References: Message-ID: In article , Filip Gruszczy? ski wrote: > >for choice in self.__choices: > choicesBox.addItem(choice) This is the easiest to read. I'm guessing that this is not inner-loop stuff that needs to be optimized, so you should favor readability over performance. -- -Ed Falk, falk at despams.r.us.com http://thespamdiaries.blogspot.com/ From wuwei23 at gmail.com Thu Dec 3 22:20:23 2009 From: wuwei23 at gmail.com (alex23) Date: Thu, 3 Dec 2009 19:20:23 -0800 (PST) Subject: Which is more pythonic? References: Message-ID: <184fd14b-05f0-4d25-a241-0c2b872ea8e4@u8g2000prd.googlegroups.com> Filip Gruszczy?ski wrote: > I guess map version would be fastest and explicit for is the slowest > version. However, the first, most obvious way seems most clear to me > and I don't have to care about speed with adding elements to combo > box. Still, it's two lines instead of one, so maybe it's not the best. > So, which one is? Both map and the listcomp create & modify a list, which seems kind of odd to do if you're just throwing the list away afterward. What's more important than a low line count is clarity of intent. The for-loop makes it clear to me that it's the action against each item that's important, not the resulting list of processed items. From apt.shansen at gmail.com Thu Dec 3 22:22:07 2009 From: apt.shansen at gmail.com (Stephen Hansen) Date: Thu, 3 Dec 2009 19:22:07 -0800 Subject: memory error In-Reply-To: <1482CDE5CD38BC4B99F6182262ADCB2925FAA4@EXCHVS02.ad.sfwmd.gov> References: <6e8c880b-a9f4-4063-8e77-e77679f6b54c@m3g2000yqf.googlegroups.com> <1482CDE5CD38BC4B99F6182262ADCB2925FAA4@EXCHVS02.ad.sfwmd.gov> Message-ID: <7a9c25c20912031922u416e9df6q26d4e3cc7a78bbe7@mail.gmail.com> On Thu, Dec 3, 2009 at 5:51 AM, Ahmed, Shakir wrote: > I am getting a memory error while executing a script. Any idea is highly > appreciated. > > Error message: " The instruction at "0x1b009032" referenced memory at > "0x00000804:, The memory could not be "written" > > This error is appearing and I have to exit from the script. > Vastly insufficient information; that basically is like saying, "Something broke." People can't really help you with that. You sorta need to show some code and/or at least describe what's going on at the time. But-- the image does say Pythonwin... are you running this from the Pythonwin editor/IDE? Does this script crash out if you run it through the normal 'python'(or pythonw) commands? If not, are you attempting to do any sort of GUI work in this script? That rarely works within Pythonwin directly. --S -------------- next part -------------- An HTML attachment was scrubbed... URL: From john at castleamber.com Thu Dec 3 23:08:48 2009 From: john at castleamber.com (John Bokma) Date: Thu, 03 Dec 2009 22:08:48 -0600 Subject: Question on Python as career References: <614b8dde-324b-4d54-8e73-7a96e4c0b1cf@a21g2000yqc.googlegroups.com> <6fde3200-984a-4948-9f94-6c0f9ebfcc07@r24g2000prf.googlegroups.com> <79474a9d-2def-49ba-9aa5-d5077ed3e695@m33g2000pri.googlegroups.com> Message-ID: <87einbmldb.fsf@castleamber.com> TimmyGee writes: > On Dec 4, 1:08?pm, r0g wrote: >> TimmyGee wrote: >> > On Dec 4, 2:48 am, Grant Edwards wrote: [..] >> >www.rentacoder.com? >> >> Euwww, that's not an experience I'd recommend! >> >> Roger. > > Really? I was considering giving it a go one of these days. Not a good > idea? If you have no problem with coding projects that take 80 hours and have a budget of 200 USD... -- John Bokma Read my blog: http://johnbokma.com/ Hire me (Perl/Python): http://castleamber.com/ From fearsomedragonfly at gmail.com Fri Dec 4 00:12:39 2009 From: fearsomedragonfly at gmail.com (Brad Harms) Date: Thu, 03 Dec 2009 23:12:39 -0600 Subject: Feature request: String-inferred names In-Reply-To: <009eaec9$0$26893$c3e8da3@news.astraweb.com> References: <17a26a8c-3358-4152-8871-2dcaa7e97220@g23g2000vbr.googlegroups.com> <87skc0zstu.fsf@benfinney.id.au> <009eaec9$0$26893$c3e8da3@news.astraweb.com> Message-ID: <1259903559.4287.21.camel@SpeedyG> On Tue, 2009-12-01 at 14:38 +0000, Steven D'Aprano wrote: > On Mon, 30 Nov 2009 18:55:46 -0800, The Music Guy wrote: > > > Lie Ryan, I think I see what you're saying about using __dict__ to add > > members to a class, but it's not quite the same. __dict__ is only for > > attributes, NOT properties, methods, etc. which all come from the class > > of an object rather than the object's __dict__. > > Almost but not quite. > > It's just special double-underscore methods like __init__ __add__ etc > that have to be in the class rather than the instance. (To be precise, > you can add such a method to the instance, but it won't be called > automatically.) Likewise staticmethods and classmethods won't work > correctly unless they are in the class. But ordinary methods work fine: > the only tricky bit is creating them in the first place. > > >>> class K(object): > ... pass > ... > >>> k = K() > >>> import types > >>> k.method = types.MethodType(lambda self: "I am %s" % self, k) > >>> k.method() > 'I am <__main__.K object at 0xb7cc7d4c>' ...I'm not sure I follow your logic. Yes, you can create an instancemethod out of a function and assign it to an instance after (or during) its instantiation, which is what Python's class/instance model provides automatically. However, to do so manually in this manner completely disregards the fundamentals of object-oriented programming, not to mention the basic guiding principles of nearly all Python code in existence. It totally breaks inheritance and polymorphism. Maybe I'm missing something, but I can't see how that line of thought helps anything. From sivaits4u at gmail.com Fri Dec 4 01:09:56 2009 From: sivaits4u at gmail.com (Siva B) Date: Fri, 4 Dec 2009 11:39:56 +0530 Subject: editor with autocompletion Message-ID: <581ce2790912032209m2f060e9agb2a7ada6dfb1f8c9@mail.gmail.com> Hi friends, I am writing a new language. So I want an editor with auto complete. I there any such tool in Python ?(not only in python any other) I want it for my new lang help me Thanks siva -------------- next part -------------- An HTML attachment was scrubbed... URL: From fearsomedragonfly at gmail.com Fri Dec 4 01:22:08 2009 From: fearsomedragonfly at gmail.com (Brad Harms) Date: Fri, 04 Dec 2009 00:22:08 -0600 Subject: Feature request: String-inferred names In-Reply-To: <4b153d02$0$11568$426a74cc@news.free.fr> References: <17a26a8c-3358-4152-8871-2dcaa7e97220@g23g2000vbr.googlegroups.com> <87skc0zstu.fsf@benfinney.id.au> <4b153d02$0$11568$426a74cc@news.free.fr> Message-ID: <1259907728.4287.90.camel@SpeedyG> On Tue, 2009-12-01 at 16:58 +0100, Bruno Desthuilliers wrote: > The Music Guy a ?crit : > (snip) > > Lie Ryan, I think I see what you're saying about using __dict__ to add > > members > > No "members" in Python - only attributes. > > to a class, but it's not quite the same. __dict__ is only for > > attributes, NOT properties, methods, etc. which all come from the > > class of an object rather than the object's __dict__. > > properties and methods (well, functions actually) ARE attributes... of > the class object. And you can of course access the obj.__class__.__dict__ > > Just for the record... When I say "member" I am using it as a general term that describes any value that can be accessed (get, set, del) through an object. If the object is referenced by a variable named `foo`, then by using `foo.name` or one of the XXXattr functions, one can access the member of `foo` called `name`. What's important to note, though, is that the term "member" does not make any assumption about how `foo.name` is implemented. When I say "attribute," however, I am referring specifically to a member of an object where the member's name is a key in the object's __dict__, and the value is the one that is paired with that key. Example: class Foo(object): def __init__(self): self._x = 5 @property def x(self): return self._x @x.setter def x(self,val): self._x = val def frob(self): print "I've been frobbed!" foo = Foo() foo._x # Each of these is both a member and an attribute. foo.y = 6 foo.x # Each of these is a member, but neither is an attribute. foo.frob To be perfectly precise, foo.y is only an attribute AFTER the assignment has been performed. Before 6 is assigned, foo.y is only a "member" and not an "attribute" because "y" does not yet exist as a key in foo's __dict__. Essentially, I just use "member" as a convenience term. I thought that was the convention among the community, but evidently it isn't as widely used as such as I thought. Anyway, it looks like the docs agree with you (http://docs.python.org/glossary.html#term-attribute), so I'm not going to argue. However, for the purpose of clean communication, I'd still like to have terms that refer specifically to: 1.) "Regular" attributes, ie. those that are shortcuts to items in the directly associated object's __dict__, 2.) Attributes whose values are determined or assigned dynamically by indirectly calling a function (like properties and instancemethods) 3.) Attributes that are read from an object with regular .dot syntax, but are actually attributes (in the sense of #1 above) of the __dict__ of the object's class. From alfps at start.no Fri Dec 4 01:24:21 2009 From: alfps at start.no (Alf P. Steinbach) Date: Fri, 04 Dec 2009 07:24:21 +0100 Subject: Formatting logically nested actions -- Pythonic way? Message-ID: Hi. I discovered with tkinter the registration of widgets with layout managers (tkinter "geometry" managers, e.g. calls to pack()) needs to be done very hierarchically. And this leads to hierarchical code, which would be nice to indicate by indenting, but oops, indenting in Python is syntactically significant... So first I thought of one routine per widget creation & layout registration, but that was very ugly and verbose. Then thought of simply using semicolons but I didn't even try that, because I imagined the sheer ugliness. Then I sort of landed on the solution below, but although using the language to define a kind of special purpose mini-language is common in C++ and Lisp I haven't seen so much of that in Python examples, and so I wonder whether this is Pythonic or perhaps so extremely un-Pythonic (unconventional) that it's scary -- I mean, calls that do nothing whatsoever, but I think of *visual structure* as very important here and IMHO (disregarding Pythonicity issues) worth the overhead... import tkinter as tk import contextlib @contextlib.contextmanager def this( object ): yield object window = tk.Tk() window.title( "Picture presentation test" ) with this( tk.Frame() ) as display_area: pic = tk.PhotoImage( file = "lightbulb_off.gif" ) with this( tk.Label( display_area, image = pic ) ) as pic_display: pic_display.pack( side = "left" ) with this( tk.Frame( display_area, width = 500 ) ) as interaction_area: with this( tk.Label( interaction_area ) ) as status_line: status_line.config( text = "The switch is OFF" ) status_line.pack( anchor = "w" ) with this( tk.Button( interaction_area ) ) as toggle_button: toggle_button.config( text = " Toggle it " ) toggle_button.pack( anchor = "w" ) interaction_area.pack( side = "left" ) display_area.place( relx = 0.5, rely = 0.5, anchor = "center" ) # Centered window.mainloop() Cheers, - Alf PS: I see a non-functional width specification in there. Just forgot to remove that. And better with code as-is straight from editor than fixing up manually! From themusicguy123 at gmail.com Fri Dec 4 01:35:28 2009 From: themusicguy123 at gmail.com (Bradley K. Harms) Date: Fri, 04 Dec 2009 00:35:28 -0600 Subject: Feature request: String-inferred names In-Reply-To: <009eaec9$0$26893$c3e8da3@news.astraweb.com> References: <17a26a8c-3358-4152-8871-2dcaa7e97220@g23g2000vbr.googlegroups.com> <87skc0zstu.fsf@benfinney.id.au> <009eaec9$0$26893$c3e8da3@news.astraweb.com> Message-ID: <1259908528.4287.101.camel@SpeedyG> On Tue, 2009-12-01 at 14:38 +0000, Steven D'Aprano wrote: > On Mon, 30 Nov 2009 18:55:46 -0800, The Music Guy wrote: > > > Lie Ryan, I think I see what you're saying about using __dict__ to add > > members to a class, but it's not quite the same. __dict__ is only for > > attributes, NOT properties, methods, etc. which all come from the class > > of an object rather than the object's __dict__. > > Almost but not quite. > > It's just special double-underscore methods like __init__ __add__ etc > that have to be in the class rather than the instance. (To be precise, > you can add such a method to the instance, but it won't be called > automatically.) Likewise staticmethods and classmethods won't work > correctly unless they are in the class. But ordinary methods work fine: > the only tricky bit is creating them in the first place. > > >>> class K(object): > ... pass > ... > >>> k = K() > >>> import types > >>> k.method = types.MethodType(lambda self: "I am %s" % self, k) > >>> k.method() > 'I am <__main__.K object at 0xb7cc7d4c>' > Yes, you can create an instancemethod out of a function and assign it to > an instance after (or during) its instantiation, which is what Python's > class/instance model provides automatically. [...] ...Hmm, let me clarify that statement as I think it could be misunderstood: When I say "which is what [Python] does automatically", I mean that Python automatically creates a BOUND instancemethod object from the UNBOUND instancemethod whenever you try to access the unbound instancemethod as an attribute of the instance _at the moment that you try to access it_. I did NOT mean to imply that the bound instancemethod objects are created and assigned to the instance at the time of its instantiation (because Python obviously doesn't do that). Sorry for the rapid-fire posting. From ben+python at benfinney.id.au Fri Dec 4 02:05:03 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 04 Dec 2009 18:05:03 +1100 Subject: Feature request: String-inferred names References: <17a26a8c-3358-4152-8871-2dcaa7e97220@g23g2000vbr.googlegroups.com> <87skc0zstu.fsf@benfinney.id.au> <4b153d02$0$11568$426a74cc@news.free.fr> Message-ID: <87fx7rjk2o.fsf@benfinney.id.au> Brad Harms writes: > Anyway, it looks like the docs agree with you > (http://docs.python.org/glossary.html#term-attribute), so I'm not > going to argue. That's good, because the terms are quite well established in Python terminology. > However, for the purpose of clean communication, I'd still like to > have terms that refer specifically to: > > 1.) "Regular" attributes, ie. those that are shortcuts to items in the > directly associated object's __dict__, I don't know what you mean by ?shortcuts to items?. The names are looked up in dictionaries; where do shortcuts play a part? Try ?instance attribute?, as distinct from ?class attribute?. > 2.) Attributes whose values are determined or assigned dynamically by > indirectly calling a function (like properties and instancemethods) Yes, the term ?property? seems to do what you want. The value of an instance method is *not* determined dynamically: its value is a function, and that value is no more dynamic than any other attribute of the instance. > 3.) Attributes that are read from an object with regular .dot syntax, > but are actually attributes (in the sense of #1 above) of the __dict__ > of the object's class. This is a ?class attribute? as distinct from an ?instance attribute?. The distinction isn't often worth knowing, though, so you'll probably still have to explain it when you use it. -- \ ??Did you sleep well?? ?No, I made a couple of mistakes.?? | `\ ?Steven Wright | _o__) | Ben Finney From james.harris.1 at googlemail.com Fri Dec 4 02:11:38 2009 From: james.harris.1 at googlemail.com (James Harris) Date: Thu, 3 Dec 2009 23:11:38 -0800 (PST) Subject: Language mavens: Is there a programming with "if then else ENDIF" syntax? References: Message-ID: <2718bb29-b3a0-4a21-be6e-0de622800078@k4g2000yqb.googlegroups.com> On 3 Dec, 20:56, Michael Torrie wrote: > Steve Ferg wrote: > > Is there any particular reason why this might be a *bad* language- > > design idea? > > Syntactically, using braces, begin/end blocks, python white space, and > your if/elif/then/endif structures, amounts to the same thing; they are > all equivalent. ?Thus from a language pov, there's no compelling reason > to do one over the other. > > One good reason to avoid the if/elif/then/endif syntax and its related > friends in a language (while/wend, do/loop, for/next) is that they > require parser support for what amounts to three or four versions of > precisely the same construct: the block. ?Thus from a parser or compiler > point of view, it's far better and easier to have blocks begin and end > with something that is consistent and recognizable without a lot of > look-ahead or context. I'm not disagreeing with the above paragraph but in the interests of even handedness an advantage of the other method is ease for a human to match begins and ends of large blocks. With statement or block brackets such as "begin" ... "end" (Pascal) and "{" ... "}" (C) because they are all the same it can be hard to see where each construct ends. C programmers sometimes write } /* for */ } /* while */ or similar to indicate which construct the terminating brace is closing. > I once started to write a parser for the QuickBasic language but found > very quickly that the grammar required a fair amount of token > look-ahead. ?For example, if I found the token "End", I had to look at > least one token ahead to find out if this was an "end if" or just an > "end." ?Also "end" could, if I recall, have an optional number parameter > that would set the exit errorlevel code. ?Certainly QuickBasic was not > context-free and was not LL(1). > > I'm not sure, but Python's grammar is LL(1) I think, and probably darn > close to context-free. James From user at domain.invalid Fri Dec 4 03:00:53 2009 From: user at domain.invalid (user at domain.invalid) Date: Fri, 04 Dec 2009 10:00:53 +0200 Subject: Manyfile Processing Message-ID: Hey, sorry if i bother you with a beginners question but i have an issue with processing a bunch of files. They are some arithmetic lists the processing of one file is an easy task but how do i process many files? I tried reading that files in to a list and looping over the list elements but the function won't accept any arguments other than a string. I would appreciate if you could help me. From steve at REMOVE-THIS-cybersource.com.au Fri Dec 4 04:00:42 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 04 Dec 2009 09:00:42 GMT Subject: Feature request: String-inferred names References: <17a26a8c-3358-4152-8871-2dcaa7e97220@g23g2000vbr.googlegroups.com> <87skc0zstu.fsf@benfinney.id.au> <4b153d02$0$11568$426a74cc@news.free.fr> <87fx7rjk2o.fsf@benfinney.id.au> Message-ID: <00a25441$0$26893$c3e8da3@news.astraweb.com> On Fri, 04 Dec 2009 18:05:03 +1100, Ben Finney wrote: > Brad Harms writes: ... >> 1.) "Regular" attributes, ie. those that are shortcuts to items in the >> directly associated object's __dict__, > > I don't know what you mean by ?shortcuts to items?. The names are looked > up in dictionaries; where do shortcuts play a part? > > Try ?instance attribute?, as distinct from ?class attribute?. Not all such attributes are actually found in instance.__dict__. >>> class Example(object): ... __slots__ = 'spam' ... >>> x = Example() >>> y = Example() >>> x.spam = 23 >>> >>> x.__dict__['spam'] Traceback (most recent call last): File "", line 1, in AttributeError: 'Example' object has no attribute '__dict__' >>> x.spam 23 >>> y.spam Traceback (most recent call last): File "", line 1, in AttributeError: spam So it is possible to have per-instance attributes that don't live inside the instance __dict__. >> 2.) Attributes whose values are determined or assigned dynamically by >> indirectly calling a function (like properties and instancemethods) > > Yes, the term ?property? seems to do what you want. Or dynamic attributes returned by __getattr__ or __getattribute__. -- Steven From FearsomeDragonfly at gmail.com Fri Dec 4 04:34:00 2009 From: FearsomeDragonfly at gmail.com (Brad Harms) Date: Fri, 04 Dec 2009 09:34:00 GMT Subject: Feature request: String-inferred names References: <17a26a8c-3358-4152-8871-2dcaa7e97220@g23g2000vbr.googlegroups.com> <87skc0zstu.fsf@benfinney.id.au> <4b153d02$0$11568$426a74cc@news.free.fr> <87fx7rjk2o.fsf@benfinney.id.au> Message-ID: On Fri, 04 Dec 2009 18:05:03 +1100, Ben Finney wrote: > Brad Harms writes: > >> Anyway, it looks like the docs agree with you >> (http://docs.python.org/glossary.html#term-attribute), so I'm not going >> to argue. > > That's good, because the terms are quite well established in Python > terminology. I'm just saying, if the official documentation defines the term "attribute" thusly, it would be silly of me to continue using my own made- up term that means pretty much the same thing. > >> However, for the purpose of clean communication, I'd still like to have >> terms that refer specifically to: >> >> 1.) "Regular" attributes, ie. those that are shortcuts to items in the >> directly associated object's __dict__, > > I don't know what you mean by ?shortcuts to items?. The names are looked > up in dictionaries; where do shortcuts play a part? > > Try ?instance attribute?, as distinct from ?class attribute?. > >> 2.) Attributes whose values are determined or assigned dynamically by >> indirectly calling a function (like properties and instancemethods) > > Yes, the term ?property? seems to do what you want. I wasn't asking what you call any object or any /kind/ of object. I was asking for a term (noun?) that describes the WAY the object is accessed as an attribute of an instance, with the connotation that the value of the attribute would be calculated dynamically (by calling a function) at the time the attribute was accessed. Note that the value does not have to exist in ANY __dict__ anywhere, it could, for example, be calculated by object.__getattribute__. Example: >>> obj.attr Without knowing what "obj" is or what "attr" is as it pertains to obj, but knowing that "attr" does not actually a key in obj.__dict_,_ and that its value has to be determined by some other means, what do you call the thing on the code line above? That is what I'm trying to find out. (HINT: Don't think about how the Python interpreter parses it or how the value is eventually determined. That's not relevant. Just understand that the value does not come directly from obj.__dict__.) By the way, a "property" is an object of type __builtin__.property. A property with a reference in an attribute of a class /does/ call a function when you try to access that property as an attribute of the class's instances. However, properties are not the only objects that have this behavior, so calling objects that behave in this way is ambiguous. I think the actual, general term for such an object is "data descriptor," or just "descriptor." (http://docs.python.org/glossary.html#term- descriptor) > > The value of an instance method is *not* determined dynamically: its > value is a function, and that value is no more dynamic than any other > attribute of the instance. That is incorrect. Indirectly accessing an instancemethod of a class through an instance of that class will trigger the descriptor behavior of the instancemethod type. This produces a new object, another instancemethod, that is bound to the instance through which it was accessed. It's a mouthful to say, but it is sufficiently accurate. Heck, just look at this: >>> class Foo(object): ... def spam(self): pass ... >>> foo = Foo() >>> foo.spam > >>> Foo.spam >>> foo.spam is Foo.spam False >>> foo.spam == Foo.spam False >>> Foo.spam.__get__(foo, Foo) > >>> Foo.__dict__["spam"].__get__(foo, Foo) > >>> Foo.__dict__["spam"].__get__(foo, Foo) is foo.spam False >>> Foo.__dict__["spam"].__get__(foo, Foo) == foo.spam True Also note the fact that Foo.spam is an _instancemethod_ object and not just a function, even though it was defined as "just a function" in the class body. That's because function objects are descriptors as well; it lets them produce unbound instancemethods. I'm not precisely sure how this works, though. I think it only happens when the metaclass of a class processes the functions in the class block. > >> 3.) Attributes that are read from an object with regular .dot syntax, >> but are actually attributes (in the sense of #1 above) of the __dict__ >> of the object's class. > > This is a ?class attribute? as distinct from an ?instance attribute?. > I know it's called that, but I was talking more about the fact of it being accessed through an instance of the class rather than > The distinction isn't often worth knowing, though, so you'll probably > still have to explain it when you use it. I beg to differ. For one thing, it affects descriptors. Anyway, these metadiscussions are starting to give me headaches. Let's talk about something more interesting... PS. I'm truly sorry once again for using email addresses and names inconsistently. I really am trying to solve the problem. I'm going to try accessing the list via comp.lang.python and Pan (newsreader for Gnome) for a while. Hopefully it will help. -- Brad Harms -- http://alphaios.net From deets at nospam.web.de Fri Dec 4 04:37:19 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 04 Dec 2009 10:37:19 +0100 Subject: Manyfile Processing In-Reply-To: References: Message-ID: <7ns3ifF3knh2uU1@mid.uni-berlin.de> user at domain.invalid schrieb: > Hey, > > sorry if i bother you with a beginners question but i have an issue > with processing a bunch of files. They are some arithmetic lists the > processing of one file is an easy task but how do i process many files? > I tried reading that files in to a list and looping over the list > elements but the function won't accept any arguments other than a string. > > I would appreciate if you could help me. for filename in list_of_filenames: do_something_with_one_file(filename) Unless you disclose more of what your actual code looks like, there isn't more we can do. Diez From FearsomeDragonfly at gmail.com Fri Dec 4 04:40:04 2009 From: FearsomeDragonfly at gmail.com (Brad Harms) Date: Fri, 04 Dec 2009 09:40:04 GMT Subject: Feature request: String-inferred names References: <17a26a8c-3358-4152-8871-2dcaa7e97220@g23g2000vbr.googlegroups.com> <87skc0zstu.fsf@benfinney.id.au> <4b153d02$0$11568$426a74cc@news.free.fr> <87fx7rjk2o.fsf@benfinney.id.au> <00a25441$0$26893$c3e8da3@news.astraweb.com> Message-ID: On Fri, 04 Dec 2009 09:00:42 +0000, Steven D'Aprano wrote: > Not all such attributes are actually found in instance.__dict__. ...I hadn't even considered __slots__ yet. Hm... > Or dynamic attributes returned by __getattr__ or __getattribute__. I'm looking for a generic term, because it's too cumbersome to say "properties or dynamic attributes using __getattr__ or __getattribute__" all the time. That will be my last message for a while...good night, c.p.l. -- Brad Harms -- http://alphaios.net From alfps at start.no Fri Dec 4 05:03:22 2009 From: alfps at start.no (Alf P. Steinbach) Date: Fri, 04 Dec 2009 11:03:22 +0100 Subject: Are routine objects guaranteed mutable & with dictionary? Message-ID: Is this guaranteed to work in Python 3.x? >>> def foo(): pass ... >>> foo.blah = 222 >>> foo.blah 222 >>> _ Cheers, - Alf From victorsubervi at gmail.com Fri Dec 4 05:05:12 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Fri, 4 Dec 2009 05:05:12 -0500 Subject: Insane Problem In-Reply-To: <00a1d75d$0$26893$c3e8da3@news.astraweb.com> References: <4dc0cfea0912021218g797f782esa2c174923b6ac492@mail.gmail.com> <4B16D739.5080408@mrabarnett.plus.com> <4dc0cfea0912030307j7556eb06j469ccc4e6a29d1ee@mail.gmail.com> <4dc0cfea0912030502x1532319dy92e6f62868b6ef5e@mail.gmail.com> <00a1d75d$0$26893$c3e8da3@news.astraweb.com> Message-ID: <4dc0cfea0912040205o57897f11u2bc16751784f1d77@mail.gmail.com> On Thu, Dec 3, 2009 at 7:07 PM, Steven D'Aprano < steve at remove-this-cybersource.com.au> wrote: > On Thu, 03 Dec 2009 10:13:14 -0500, Carsten Haese wrote: > > > Victor Subervi wrote: > >> I believe I mentioned in my first post that the "print test" does print > >> the exact fields being called from the referring page. > > > > Was any part of "What do the print statements actually print? Please > > copy and paste their output." unclear to you in any way? > > > >> Perhaps this > >> is a bug in the cgi interface? > > > > Unlikely. > > > > It's much more likely that whatever frankencode you stitched together > > from examples you found on the internet without understanding how they > > work is doing something unexpected, and you are unable to diagnose the > > problem because you don't understand how your code works. > > Oh come on, how likely is that??? It's much more likely that the original > poster has discovered a bug in the standard library that thousands of > users before him never noticed! > > *wink* > Please don't be rude. I never suggested that, but only said that there may be a possibility that there was some problem, and in the context I wrote it, it was perfectly obvious, because I made it so, that I was pulling at straws. I might not be as good a programmer as you, but I'm not rude, and that makes me a better person. You can't take your programming with you when you die, but I can take my pure, peaceful and joy-filled soul with me. Think about that and don't be rude. V -------------- next part -------------- An HTML attachment was scrubbed... URL: From marco at sferacarta.com Fri Dec 4 05:47:00 2009 From: marco at sferacarta.com (Marco Mariani) Date: Fri, 04 Dec 2009 11:47:00 +0100 Subject: Are routine objects guaranteed mutable & with dictionary? In-Reply-To: References: Message-ID: Alf P. Steinbach wrote: > Is this guaranteed to work in Python 3.x? > > > >>> def foo(): pass > .... > >>> foo.blah = 222 > >>> foo.blah > 222 > >>> _ I don't see why it shouldn't work. BTW, it's a function, not a "routine" From alfps at start.no Fri Dec 4 05:58:15 2009 From: alfps at start.no (Alf P. Steinbach) Date: Fri, 04 Dec 2009 11:58:15 +0100 Subject: Are routine objects guaranteed mutable & with dictionary? In-Reply-To: References: Message-ID: * Marco Mariani: > Alf P. Steinbach wrote: > > >> Is this guaranteed to work in Python 3.x? >> >> >> >>> def foo(): pass >> .... >> >>> foo.blah = 222 >> >>> foo.blah >> 222 >> >>> _ > > I don't see why it shouldn't work. For example, (42).blah = 666 The question is what guarantees or absence thereof the language specification, PEPs, intentions, whatever gives/has. > BTW, it's a function, not a "routine" Wikipedia is your friend, . Cheers & hth., - Alf From somm1105 at bellsouth.net Fri Dec 4 05:58:59 2009 From: somm1105 at bellsouth.net (Dan Sommers) Date: Fri, 4 Dec 2009 10:58:59 +0000 (UTC) Subject: Manyfile Processing References: Message-ID: On Fri, 04 Dec 2009 10:00:53 +0200, user wrote: > sorry if i bother you with a beginners question but i have an issue > with processing a bunch of files. They are some arithmetic lists the > processing of one file is an easy task but how do i process many files? > I tried reading that files in to a list and looping over the list > elements but the function won't accept any arguments other than a > string. Maybe the fileinput module can help. Dan From bruno.42.desthuilliers at websiteburo.invalid Fri Dec 4 06:26:58 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 04 Dec 2009 12:26:58 +0100 Subject: Which is more pythonic? In-Reply-To: References: Message-ID: <4b18f1eb$0$17810$426a34cc@news.free.fr> Filip Gruszczy?ski a ?crit : > I have just written a very small snippet of code and started thinking, > which version would be more pythonic. Basically, I am adding a list of > string to combo box in qt. So, the most obvious way is: > > for choice in self.__choices: > choicesBox.addItem(choice) > > But I could also do: > > map(self.__choices, choicesBox.addItem) this should actually be map(choicesBox.addItem, self.__choices) !-) > or > > [choicesBox.addItem(choice) for choice in self.__choices] > > I guess map version would be fastest and explicit for is the slowest > version. I don't think so - there's at least the overhead of creating a useless list. But if you're after micro-optimization, there's an obvious one : addItem = choicesBox.addItem for choice in self.__choices: addItem(choice) Attribute lookup can be costly, specially when the attribute is a method. Now unless you have a _very_ big choices list - which is probably not the case - the gain will still be marginal. > However, the first, most obvious way seems most clear to me It is. > and I don't have to care about speed with adding elements to combo > box. Still, it's two lines instead of one, so maybe it's not the best. > So, which one is? The first, obviously - and I'm the kind of guy that really dig obscure one-liners !-) From tuomas.vesterinen at iki.fi Fri Dec 4 06:28:37 2009 From: tuomas.vesterinen at iki.fi (Tuomas Vesterinen) Date: Fri, 04 Dec 2009 13:28:37 +0200 Subject: Connecting to the users preferred email client Message-ID: <4b18f265$0$26369$9b536df3@news.fv.fi> If I want to open a html-page from Python code I can say: >>> import webbrowser >>> webbrowser.open('index.html') Is there a standard way to init an email in users preferred email client like Thubderbird, Evolution etc.? Tuomas Vesterinen From mal at egenix.com Fri Dec 4 06:46:13 2009 From: mal at egenix.com (M.-A. Lemburg) Date: Fri, 04 Dec 2009 12:46:13 +0100 Subject: python bijection In-Reply-To: References: <7n39ojF3jj6iuU1@mid.individual.net> <12c55890-118d-4655-b6c0-c908c9734a17@a32g2000yqm.googlegroups.com> <85100df7-a8b0-47e9-a854-ba8a8a2f3b98@r31g2000vbi.googlegroups.com> <4B17A960.1090700@egenix.com> <4B17FBFE.8070903@egenix.com> Message-ID: <4B18F685.8050102@egenix.com> geremy condra wrote: > On Thu, Dec 3, 2009 at 12:57 PM, M.-A. Lemburg wrote: >> geremy condra wrote: >>> On Thu, Dec 3, 2009 at 7:04 AM, M.-A. Lemburg wrote: >>>> I think the only major CS data type missing from Python is some >>>> form of (fast) directed graph implementation ? la kjGraph: >>>> >>>> http://gadfly.sourceforge.net/kjbuckets.html >>>> >>>> With these, you can easily build all sorts of relations between >>>> objects and apply fast operations on them. In fact, it should then >>>> be possible to build a complete relational database in Python >>>> (along the lines of Gadfly). >>> >>> If you're in the market for a Python graph library, you may want >>> to check out Graphine- I'm obviously biased (I wrote most of it) >>> but it has a few more bells and whistles than kjbuckets, and is >>> pretty darned easy to use. It also supports undirected and >>> bridge graphs. >> >> Thanks for the hint :-) >> >> The lib looks nice and would probably serve as a good prototype >> for writing a new built-in type for Python. > > I suspect that it would have a better chance at getting into > collections than becoming a builtin, but who knows. I'd just > like to have something like it in the standard library. Integrating an easy-to-use graph library into the collections module (and it's C companion) is good idea. >> This would have to be written in C, though, > > That's currently in the works, along with database backing. > We'd welcome any help though... hint, hint... > >> and come under a Python compatible license. > > I'm willing to dual license under the Python license if > there were a substantial interest in doing so, and I'm > confident that the other authors and maintainers > would feel the same way. Great ! > The question in my mind is whether such an interest exists. Since Python is being used more and more in CS classes, such an addition would complete the tool-set and make Python even more attractive for undergrad CS courses. Finding out how much interest exists in advance is always a bit difficult with new data-structures. People have to get a feeling of how they can be put to good use first, so it's a chicken-and-egg problem. We've seen the same thing happen with sets. They were first made available via a separate module and then became built-ins after people realized how useful they are in practice. With graphs, it's probably going to take a little longer before people realize their usefulness - graph theory is certainly a lot more complicated than set theory :-) >> With the built-in feature moratorium >> currently in place, there's about 1.5-2 years time to get this >> done; perhaps a good GSoC project for next year :-) > > I'd love to have Graphine be a GSoC project, although > if the target were to get it into collections the > moratorium wouldn't change the timeline AFAICS. True. -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Dec 04 2009) >>> 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 our new mxODBC.Connect Python Database Interface 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 http://www.egenix.com/company/contact/ From denis-bz-gg at t-online.de Fri Dec 4 07:03:13 2009 From: denis-bz-gg at t-online.de (denis) Date: Fri, 4 Dec 2009 04:03:13 -0800 (PST) Subject: Organization of GUIs References: <424dcb65-735c-4779-ae0a-5c4e662b24ac@b36g2000prf.googlegroups.com> Message-ID: On Dec 3, 2:44?pm, Michael Mossey wrote: > complete VISIBILITY and control of messages ... is most important: being able to SEE messages (filtered on from, to, ...) in a running system really helps to understand it. Hierarchy does help structure messages coarse/fine, but visibility is orthogonal to structure (you can have visible democracy, blind hierarchy, in real life too.) Visibility has to be built in from the beginning -- wrap all connect() s in a visconnect() that can trace. Dietmar's shell sounds Right; anyone know of such in PyQt ? cheers -- denis From gmdidro at gmail.com Fri Dec 4 07:17:27 2009 From: gmdidro at gmail.com (=?KOI8-R?B?8MXU0s/XIOHMxcvTwc7E0g==?=) Date: Fri, 4 Dec 2009 15:17:27 +0300 Subject: Why the expression "(1)" is not an one-arity tuple, but int ? Message-ID: <1dcb5c470912040417mbd6d8e0q4cdd1e66c3c2b4e4@mail.gmail.com> Hello All ! In my code I try to use a generic approach to work with tuples. Let "X" be a tuple. When I want to access a first element of a tuple, I can write: "X[0]". And that is really working when X is a n-arity tuple, with n>1 (for example "foo( (1,2,3) )" ). But when I call my library function with a 1-arity tuple (for example "foo( (1) )" ) I have an error: TypeError: 'int' object is unsubscriptable How could I tell Python that "(1)" is not an integer, but an one-arity tuple ? Thank you, Alexander Petrov From andreengels at gmail.com Fri Dec 4 07:26:13 2009 From: andreengels at gmail.com (Andre Engels) Date: Fri, 4 Dec 2009 13:26:13 +0100 Subject: Why the expression "(1)" is not an one-arity tuple, but int ? In-Reply-To: <1dcb5c470912040417mbd6d8e0q4cdd1e66c3c2b4e4@mail.gmail.com> References: <1dcb5c470912040417mbd6d8e0q4cdd1e66c3c2b4e4@mail.gmail.com> Message-ID: <6faf39c90912040426t25d67b60s66cfcbe137d1686e@mail.gmail.com> 2009/12/4 ?????? ????????? : > Hello All ! > > In my code I try to use a generic approach to work with tuples. Let > "X" be a tuple. > When I want to access a first element of a tuple, I can write: "X[0]". > And that is really working when X is a n-arity tuple, with n>1 (for > example "foo( (1,2,3) )" ). > But when I call my library function with a 1-arity tuple (for example > "foo( (1) )" ) I have an error: > > TypeError: 'int' object is unsubscriptable > > How could I tell Python that "(1)" is not an integer, but an one-arity tuple ? Tuples in Python are recognized/defined not by the brackets, but by the commas; the brackets just function to specify the exact beginning and ending of the tuple in cases where that is not directly clear. "(1,2,3)" is a tuple, but "1,2,3" is also the same tuple. A 1-tuple can be created as "1," or "(1,)". -- Andr? Engels, andreengels at gmail.com From baptiste.lepilleur at gmail.com Fri Dec 4 07:26:56 2009 From: baptiste.lepilleur at gmail.com (Baptiste Lepilleur) Date: Fri, 4 Dec 2009 13:26:56 +0100 Subject: Why the expression "(1)" is not an one-arity tuple, but int ? In-Reply-To: <1dcb5c470912040417mbd6d8e0q4cdd1e66c3c2b4e4@mail.gmail.com> References: <1dcb5c470912040417mbd6d8e0q4cdd1e66c3c2b4e4@mail.gmail.com> Message-ID: By adding a before the closing brace of the tuple. Python allow this to disambiguate between braced expression and tuple >>> type( (1,) ) 2009/12/4 ?????? ????????? > > How could I tell Python that "(1)" is not an integer, but an one-arity > tuple ? > > Thank you, > Alexander Petrov > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From baptiste.lepilleur at gmail.com Fri Dec 4 07:27:43 2009 From: baptiste.lepilleur at gmail.com (Baptiste Lepilleur) Date: Fri, 4 Dec 2009 13:27:43 +0100 Subject: Why the expression "(1)" is not an one-arity tuple, but int ? In-Reply-To: <1dcb5c470912040417mbd6d8e0q4cdd1e66c3c2b4e4@mail.gmail.com> References: <1dcb5c470912040417mbd6d8e0q4cdd1e66c3c2b4e4@mail.gmail.com> Message-ID: By adding a before the closing brace of the tucomma after 1. Python allow this to disambiguate between braced expression and tuple >>> type( (1,) ) 2009/12/4 ?????? ????????? > > How could I tell Python that "(1)" is not an integer, but an one-arity > tuple ? > > Thank you, > Alexander Petrov > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From wentland at cl.uni-heidelberg.de Fri Dec 4 07:29:46 2009 From: wentland at cl.uni-heidelberg.de (Wolodja Wentland) Date: Fri, 4 Dec 2009 13:29:46 +0100 Subject: Why the expression "(1)" is not an one-arity tuple, but int ? In-Reply-To: <1dcb5c470912040417mbd6d8e0q4cdd1e66c3c2b4e4@mail.gmail.com> References: <1dcb5c470912040417mbd6d8e0q4cdd1e66c3c2b4e4@mail.gmail.com> Message-ID: <20091204122946.GJ3430@kinakuta.local> On Fri, Dec 04, 2009 at 15:17 +0300, ?????? ????????? wrote: > In my code I try to use a generic approach to work with tuples. Let > "X" be a tuple. > When I want to access a first element of a tuple, I can write: "X[0]". > And that is really working when X is a n-arity tuple, with n>1 (for > example "foo( (1,2,3) )" ). > But when I call my library function with a 1-arity tuple (for example > "foo( (1) )" ) I have an error: > > TypeError: 'int' object is unsubscriptable > > How could I tell Python that "(1)" is not an integer, but an one-arity tuple ? The following might clarify the issue: >>> t = (1) >>> type(t) >>> t = (1,) >>> type(t) >>> t = 1, >>> type(t) It is the ',' not the '(' and ')' ... -- .''`. Wolodja Wentland : :' : `. `'` 4096R/CAF14EFC `- 081C B7CD FF04 2BA9 94EA 36B2 8B7F 7D30 CAF1 4EFC -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 836 bytes Desc: Digital signature URL: From sturlamolden at yahoo.no Fri Dec 4 07:31:17 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Fri, 4 Dec 2009 04:31:17 -0800 (PST) Subject: Formatting logically nested actions -- Pythonic way? References: Message-ID: <97040a3d-e39e-44a5-83c9-4cac2f2cd124@o10g2000yqa.googlegroups.com> On 4 Des, 07:24, "Alf P. Steinbach" wrote: > And this leads to hierarchical code, which would be nice to indicate by > indenting, but oops, indenting in Python is syntactically significant... I've seen this with OpenGL as well. Intendation between glBegin and glEnd can be achieved with a context manager that calls glBegin in __enter__ and glEnd in __exit__. Same thing for glColor* and other functions that set state attributes: call glPushAttrib in __enter__ (before setting new state) and glPopAttrib in __exit__. Context managers (i.e. with statement) should be used for this, as it guards against havoc from exceptions. If a context manager is used to call glPushAttrib and glPopAttrib, a raised exception cannot leave OpenGL's colour bit and colour stack in an undefined state by skipping glPopAttrib. The with statement is not just a pritty printer for your code. I don't see anything wrong with using context managers for tkinter as well. But personally I prefer to design GUIs using tools like wxFormBuilder, GLADE or QtDesigner. From mynthon1 at gmail.com Fri Dec 4 07:31:51 2009 From: mynthon1 at gmail.com (mynthon) Date: Fri, 4 Dec 2009 04:31:51 -0800 (PST) Subject: logging module, SMTPHandler and gmail in python 2.6 Message-ID: You cannot use gmail account for sending emails with logging module. It is because google requires TLS connection and logging module doesn't support it. To use gmail you have to extend logging.handlers.SMTPHandler class and override SMTPHandler.emit() method. Here is source code. (There really should be option to add user comments on pythons documentation page!) #--code--# import logging import logging.handlers class TlsSMTPHandler(logging.handlers.SMTPHandler): def emit(self, record): """ Emit a record. Format the record and send it to the specified addressees. """ try: import smtplib import string # for tls add this line try: from email.utils import formatdate except ImportError: formatdate = self.date_time port = self.mailport if not port: port = smtplib.SMTP_PORT smtp = smtplib.SMTP(self.mailhost, port) msg = self.format(record) msg = "From: %s\r\nTo: %s\r\nSubject: %s\r\nDate: %s\r\n\r \n%s" % ( self.fromaddr, string.join(self.toaddrs, ","), self.getSubject(record), formatdate(), msg) if self.username: smtp.ehlo() # for tls add this line smtp.starttls() # for tls add this line smtp.ehlo() # for tls add this line smtp.login(self.username, self.password) smtp.sendmail(self.fromaddr, self.toaddrs, msg) smtp.quit() except (KeyboardInterrupt, SystemExit): raise except: self.handleError(record) logger = logging.getLogger() gm = TlsSMTPHandler(("smtp.gmail.com", 587), 'bugs at my_company.com', ['admin at my_company.com'], 'Error found!', ('my_company_account at gmail.com', 'top_secret_gmail_password')) gm.setLevel(logging.ERROR) logger.addHandler(gm) try: 1/0 except: logger.exception('FFFFFFFFFFFFFFFFFFFFFFFUUUUUUUUUUUUUUUUUUUUUU-') #--/code--# see also fortmatted version at http://mynthon.net/howto/-/python/python%20-%20logging.SMTPHandler-how-to-use-gmail-smtp-server.txt. From python.list at tim.thechases.com Fri Dec 4 07:37:07 2009 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 04 Dec 2009 06:37:07 -0600 Subject: editor with autocompletion In-Reply-To: <581ce2790912032209m2f060e9agb2a7ada6dfb1f8c9@mail.gmail.com> References: <581ce2790912032209m2f060e9agb2a7ada6dfb1f8c9@mail.gmail.com> Message-ID: <4B190273.9020801@tim.thechases.com> > So I want an editor with auto complete. > I there any such tool in Python ?(not only in python any other) > I want it for my new lang vim? emacs? or do you want the editor to be written in Python? -tkc From steve at REMOVE-THIS-cybersource.com.au Fri Dec 4 07:58:09 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 04 Dec 2009 12:58:09 GMT Subject: Feature request: String-inferred names References: <17a26a8c-3358-4152-8871-2dcaa7e97220@g23g2000vbr.googlegroups.com> <87skc0zstu.fsf@benfinney.id.au> <009eaec9$0$26893$c3e8da3@news.astraweb.com> Message-ID: <00a28be7$0$26893$c3e8da3@news.astraweb.com> On Thu, 03 Dec 2009 23:12:39 -0600, Brad Harms wrote: > On Tue, 2009-12-01 at 14:38 +0000, Steven D'Aprano wrote: [...] >> It's just special double-underscore methods like __init__ __add__ etc >> that have to be in the class rather than the instance. (To be precise, >> you can add such a method to the instance, but it won't be called >> automatically.) Likewise staticmethods and classmethods won't work >> correctly unless they are in the class. But ordinary methods work fine: >> the only tricky bit is creating them in the first place. >> >> >>> class K(object): >> ... pass >> ... >> >>> k = K() >> >>> import types >> >>> k.method = types.MethodType(lambda self: "I am %s" % self, k) >> >>> k.method() >> 'I am <__main__.K object at 0xb7cc7d4c>' > > ...I'm not sure I follow your logic. > > Yes, you can create an instancemethod out of a function and assign it to > an instance after (or during) its instantiation, which is what Python's > class/instance model provides automatically. However, to do so manually > in this manner completely disregards the fundamentals of object-oriented > programming, not to mention the basic guiding principles of nearly all > Python code in existence. It totally breaks inheritance and > polymorphism. Maybe I'm missing something, but I can't see how that line > of thought helps anything. I'm not recommending it as a standard technique instead of defining methods via the usual class statement. But it does work, and can be handy for the odd occasion where you want per-instance behaviour of some class. I'm not saying this is a common occurrence, but it does happen -- it's particularly handy if you have a standard behaviour which you want to override, e.g. monkey-patching specific instances. Instead of this: class K: marker = None def method(self): if self.marker: return "special" return "normal" k = K() k.marker = 1 you can do this: class K: def method(self): return "normal" k = K() k.method = type(k.method)(lambda self: "special", k) So although unusual, it is useful. As for breaking inheritance and polymorphism, not at all. Inheritance still works, and polymorphism is irrelevant: methods are, or aren't, polymorphic regardless of whether they are per instance or shared. Fundamentally, per-instance methods are nothing more than as per-instance attributes which happen to be callable. It is "magic methods" like __len__ and friends that break the usual rules of inheritance. The normal lookup chain for instance.name, whether name is a callable method or a non-callable attribute, is: instance class base class(es) but for magic methods, the chain skips the instance step. That's done as an optimization, and given how rare it is to have per-instance methods, that's quite reasonable. -- Steven From srikrishnamohan at gmail.com Fri Dec 4 08:04:59 2009 From: srikrishnamohan at gmail.com (km) Date: Fri, 4 Dec 2009 22:04:59 +0900 Subject: Manyfile Processing In-Reply-To: <7ns3ifF3knh2uU1@mid.uni-berlin.de> References: <7ns3ifF3knh2uU1@mid.uni-berlin.de> Message-ID: use glob module Krishna On Fri, Dec 4, 2009 at 6:37 PM, Diez B. Roggisch wrote: > user at domain.invalid schrieb: > >> Hey, >> >> sorry if i bother you with a beginners question but i have an issue >> with processing a bunch of files. They are some arithmetic lists the >> processing of one file is an easy task but how do i process many files? >> I tried reading that files in to a list and looping over the list >> elements but the function won't accept any arguments other than a string. >> >> I would appreciate if you could help me. >> > > for filename in list_of_filenames: > do_something_with_one_file(filename) > > Unless you disclose more of what your actual code looks like, there isn't > more we can do. > > Diez > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From mynthon1 at gmail.com Fri Dec 4 08:24:53 2009 From: mynthon1 at gmail.com (mynthon) Date: Fri, 4 Dec 2009 05:24:53 -0800 (PST) Subject: editor with autocompletion References: <581ce2790912032209m2f060e9agb2a7ada6dfb1f8c9@mail.gmail.com> Message-ID: On 4 Gru, 13:37, Tim Chase wrote: > > So I want an editor with auto complete. > > I there any such tool in Python ?(not only in python any other) > > I want it for my new lang > > vim? ?emacs? ?or do you want the editor to be written in Python? > > -tkc Try ActiveState Komodo (or free version: Komodo Edit): http://www.activestate.com/komodo_edit/ From michele.simionato at gmail.com Fri Dec 4 08:53:02 2009 From: michele.simionato at gmail.com (Michele Simionato) Date: Fri, 4 Dec 2009 05:53:02 -0800 (PST) Subject: Question on Python as career References: <614b8dde-324b-4d54-8e73-7a96e4c0b1cf@a21g2000yqc.googlegroups.com> Message-ID: <8813587f-850a-4727-b49f-9aa722067722@v25g2000yqk.googlegroups.com> After 5 years of postdoc in Physics I decided to change career and to move to IT. I decided to learn Object Oriented Programming first. I chose Python since it was already installed on my Linux machine and it was easy to tackle for a beginner. In the process of learning Python I began posting to this newsgroup: first asking questions, then answering them. I also wrote a few papers about Python. After a year or so I was kind of known in the Python world, with a respectable curriculum. Then I got my first job by answering a job offer on comp.lang.python. My advice is to contact some local Python user group, to go to conferences and to make yourself known in a way or another. It takes time. Good luck! Michele Simionato From kyosohma at gmail.com Fri Dec 4 08:59:42 2009 From: kyosohma at gmail.com (Mike Driscoll) Date: Fri, 4 Dec 2009 05:59:42 -0800 (PST) Subject: Connecting to the users preferred email client References: <4b18f265$0$26369$9b536df3@news.fv.fi> Message-ID: <5ad6194e-a7b5-4bce-8f82-177447da6649@v30g2000yqm.googlegroups.com> On Dec 4, 5:28?am, Tuomas Vesterinen wrote: > If I want to open a html-page from Python code I can say: > > ?>>> import webbrowser > ?>>> webbrowser.open('index.html') > > Is there a standard way to init an email in users preferred email client > like Thubderbird, Evolution etc.? > > Tuomas Vesterinen Check this thread out: http://www.megasolutions.net/python/invoke-users-standard-mail-client-64348.aspx Basically, the idea is to pass the mailto url to webbrowser. ------------------- Mike Driscoll Blog: http://blog.pythonlibrary.org From shahmed at sfwmd.gov Fri Dec 4 09:16:01 2009 From: shahmed at sfwmd.gov (Ahmed, Shakir) Date: Fri, 4 Dec 2009 09:16:01 -0500 Subject: memory error In-Reply-To: <7a9c25c20912031922u416e9df6q26d4e3cc7a78bbe7@mail.gmail.com> References: <6e8c880b-a9f4-4063-8e77-e77679f6b54c@m3g2000yqf.googlegroups.com><1482CDE5CD38BC4B99F6182262ADCB2925FAA4@EXCHVS02.ad.sfwmd.gov> <7a9c25c20912031922u416e9df6q26d4e3cc7a78bbe7@mail.gmail.com> Message-ID: <1482CDE5CD38BC4B99F6182262ADCB2925FAAE@EXCHVS02.ad.sfwmd.gov> From: python-list-bounces+shahmed=sfwmd.gov at python.org [mailto:python-list-bounces+shahmed=sfwmd.gov at python.org] On Behalf Of Stephen Hansen Sent: Thursday, December 03, 2009 10:22 PM To: python-list at python.org Subject: Re: memory error On Thu, Dec 3, 2009 at 5:51 AM, Ahmed, Shakir wrote: I am getting a memory error while executing a script. Any idea is highly appreciated. Error message: " The instruction at "0x1b009032" referenced memory at "0x00000804:, The memory could not be "written" This error is appearing and I have to exit from the script. Vastly insufficient information; that basically is like saying, "Something broke." People can't really help you with that. You sorta need to show some code and/or at least describe what's going on at the time. But-- the image does say Pythonwin... are you running this from the Pythonwin editor/IDE? Does this script crash out if you run it through the normal 'python'(or pythonw) commands? If not, are you attempting to do any sort of GUI work in this script? That rarely works within Pythonwin directly. --S I am using python to do some gp ( geo processing ) for accuracy analysis. This analysis is based on application numbers. The script is going through each application number to process the data and looping through. The error appears after running few loops ( mean it process few applications). There is no certainty of how many loops it is going through but stopped with the error message and. The code is attached herewith so I hope it would make more clear to you. Any help is highly appreciated. --sk -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: ReverseBufferOverLay.py Type: application/octet-stream Size: 10032 bytes Desc: ReverseBufferOverLay.py URL: From gh at ghaering.de Fri Dec 4 09:34:30 2009 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Fri, 04 Dec 2009 15:34:30 +0100 Subject: editor with autocompletion In-Reply-To: <581ce2790912032209m2f060e9agb2a7ada6dfb1f8c9@mail.gmail.com> References: <581ce2790912032209m2f060e9agb2a7ada6dfb1f8c9@mail.gmail.com> Message-ID: Siva B wrote: > Hi friends, > > I am writing a new language. > So I want an editor with auto complete. > I there any such tool in Python ?(not only in python any other) > I want it for my new lang IDLE, the Integrated Development Environment included with your Python installation nowadays has autocompletion (I just check with the one included in Python 2.6). -- Gerhard From user at domain.invalid Fri Dec 4 09:38:52 2009 From: user at domain.invalid (user at domain.invalid) Date: Fri, 04 Dec 2009 16:38:52 +0200 Subject: Manyfile Processing In-Reply-To: References: Message-ID: On 12/04/2009 12:58 PM, Dan Sommers wrote: > On Fri, 04 Dec 2009 10:00:53 +0200, user wrote: > >> sorry if i bother you with a beginners question but i have an issue >> with processing a bunch of files. They are some arithmetic lists the >> processing of one file is an easy task but how do i process many files? >> I tried reading that files in to a list and looping over the list >> elements but the function won't accept any arguments other than a >> string. > > Maybe the fileinput module can help. > > Dan > Hi, seems like the fileinput module works fine for me though i am having quite an issue with the paths. if i do: something = fileinput.input("/some/absolute/path/to/list/file.txt") #the text file contains absolute paths for line in something: data=scipy.io.array_import.read_array(line) print data it claims that the paths given in the textfiles don't exist "no file or directory" though taking one entry from the textfile and inserting it directly to the command does its job... Any idea? Thanks so far From subhakolkata1234 at gmail.com Fri Dec 4 09:54:36 2009 From: subhakolkata1234 at gmail.com (joy99) Date: Fri, 4 Dec 2009 06:54:36 -0800 (PST) Subject: Question on Python as career References: <614b8dde-324b-4d54-8e73-7a96e4c0b1cf@a21g2000yqc.googlegroups.com> <8813587f-850a-4727-b49f-9aa722067722@v25g2000yqk.googlegroups.com> Message-ID: On Dec 4, 6:53?pm, Michele Simionato wrote: > After 5 years of postdoc in Physics I decided to changecareerand to > move to IT. I decided to learn Object Oriented Programming first. I > chosePythonsince it was already installed on my Linux machine and it > was easy to tackle for a beginner. In the process of learningPythonI > began posting to this newsgroup: first asking questions, then > answering them. I also wrote a few papers aboutPython. After a year > or so I was kind of known in thePythonworld, with a respectable > curriculum. Then I got my first job by answering a job offer on > comp.lang.python. My advice is to contact some localPythonuser > group, to go to conferences and to make yourself known in a way or > another. > It takes time. Good luck! > > ? ? ? ?Michele Simionato Dear All, This really came out to be a resourceful discussion. Every one tried to help me with some nice idea(s). Now, it is my time to act. Let me first summarize them and proceed on them suiting my need and capability. Wishing you all a nice day ahead, Best Regards, Subhabrata Banerjee. From sven at uni-hd.de Fri Dec 4 10:01:19 2009 From: sven at uni-hd.de (sven) Date: Fri, 4 Dec 2009 07:01:19 -0800 (PST) Subject: Difference between mutex.mutex and threading.Lock Message-ID: Hi, what is the difference between mutex.mutex and threading.Lock? Neither the documentation nor a Google search gave me any clue. Another issue: The documentation of mutex in version 2.6.4 says: "Deprecated since version The: mutex module has been removed in Python 3.0." Maybe it should also say what to use instead (probably threading.Lock?). Also the "version The" part seems a bit strange. Greetings, Sven From bruno.42.desthuilliers at websiteburo.invalid Fri Dec 4 10:11:08 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 04 Dec 2009 16:11:08 +0100 Subject: Feature request: String-inferred names In-Reply-To: References: <17a26a8c-3358-4152-8871-2dcaa7e97220@g23g2000vbr.googlegroups.com> <87skc0zstu.fsf@benfinney.id.au> <4b153d02$0$11568$426a74cc@news.free.fr> Message-ID: <4b192674$0$12680$426a34cc@news.free.fr> Brad Harms a ?crit : > On Tue, 2009-12-01 at 16:58 +0100, Bruno Desthuilliers wrote: >> The Music Guy a ?crit : >> (snip) >>> Lie Ryan, I think I see what you're saying about using __dict__ to add >>> members >> No "members" in Python - only attributes. > >>> to a class, but it's not quite the same. __dict__ is only for >>> attributes, NOT properties, methods, etc. which all come from the >>> class of an object rather than the object's __dict__. >> properties and methods (well, functions actually) ARE attributes... of >> the class object. And you can of course access the obj.__class__.__dict__ >> >> Just for the record... > > When I say "member" I am using it as a general term that describes any > value that can be accessed (get, set, del) through an object. These are what we call "attributes". > If the > object is referenced by a variable named `foo`, then by using `foo.name` > or one of the XXXattr functions, one can access the member of `foo` > called `name`. What's important to note, though, is that the term > "member" does not make any assumption about how `foo.name` is > implemented. > > When I say "attribute," however, I am referring specifically to a member > of an object where the member's name is a key in the object's __dict__, > and the value is the one that is paired with that key. What if the class uses slots then ?-) Ok, just kidding. More seriously: these are named "instance attributes". > Essentially, I just use "member" as a convenience term. I thought that > was the convention among the community, but evidently it isn't as widely > used as such as I thought. "members" is really C++ vocabulary. > Anyway, it looks like the docs agree with you > (http://docs.python.org/glossary.html#term-attribute), I'd put it the other way round - I have no responsabilities wrt/ the usual Pythonic vocabulary !-) > so I'm not going > to argue. However, for the purpose of clean communication, I'd still > like to have terms that refer specifically to: > > 1.) "Regular" attributes, ie. those that are shortcuts to items in the > directly associated object's __dict__, instance attributes > 2.) Attributes whose values are determined or assigned dynamically by > indirectly calling a function (like properties and instancemethods) computed attributes > 3.) Attributes that are read from an object with regular .dot syntax, > but are actually attributes (in the sense of #1 above) of the __dict__ > of the object's class. class attributes. Now things are even a bit more complex since computed attributes are usually handled by objects implementing the descriptor protocol (instance of the function or property type or any other custom descriptor), which are themselves class attributes. So sometimes - depending on the context - you may have to make clear whether you're talking about the descriptor object itself or the attribute as seen by client code. HTH From bruno.42.desthuilliers at websiteburo.invalid Fri Dec 4 10:14:42 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 04 Dec 2009 16:14:42 +0100 Subject: Feature request: String-inferred names In-Reply-To: <87fx7rjk2o.fsf@benfinney.id.au> References: <17a26a8c-3358-4152-8871-2dcaa7e97220@g23g2000vbr.googlegroups.com> <87skc0zstu.fsf@benfinney.id.au> <4b153d02$0$11568$426a74cc@news.free.fr> <87fx7rjk2o.fsf@benfinney.id.au> Message-ID: <4b19274a$0$24616$426a74cc@news.free.fr> Ben Finney a ?crit : > Brad Harms writes: (snip) >> 2.) Attributes whose values are determined or assigned dynamically by >> indirectly calling a function (like properties and instancemethods) > > Yes, the term ?property? seems to do what you want. The property type is just one possible application of the descriptor protocol which provides most of the support for computed attributes in Python, so it might be way too restrictive. > The value of an instance method is *not* determined dynamically: It is, actually. The function type implements the protocol descriptor, with the __get__ method returning an instancemethod object. From bruno.42.desthuilliers at websiteburo.invalid Fri Dec 4 10:24:42 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 04 Dec 2009 16:24:42 +0100 Subject: Feature request: String-inferred names In-Reply-To: References: <17a26a8c-3358-4152-8871-2dcaa7e97220@g23g2000vbr.googlegroups.com> <87skc0zstu.fsf@benfinney.id.au> <4b153d02$0$11568$426a74cc@news.free.fr> <87fx7rjk2o.fsf@benfinney.id.au> Message-ID: <4b1929a3$0$29974$426a74cc@news.free.fr> Brad Harms a ?crit : > On Fri, 04 Dec 2009 18:05:03 +1100, Ben Finney wrote: (snip) >>> 2.) Attributes whose values are determined or assigned dynamically by >>> indirectly calling a function (like properties and instancemethods) >> Yes, the term ?property? seems to do what you want. > > I wasn't asking what you call any object or any /kind/ of object. I was > asking for a term (noun?) that describes the WAY the object is accessed > as an attribute of an instance, with the connotation that the value of > the attribute would be calculated dynamically (by calling a function) at > the time the attribute was accessed. Then you definitly want "computed attribute" - which is quite standard OO terminology FWIW. (snip - Ben, I think you shouldn't have tred to teach your grandmother how to suck eggs ) > Also note the fact that Foo.spam is an _instancemethod_ object and not > just a function, even though it was defined as "just a function" in the > class body. That's because function objects are descriptors as well; it > lets them produce unbound instancemethods. I'm not precisely sure how > this works, class function(object): def __get__(self, instance, cls): if instance: assert isinstance(instance, cls) return boundmethod(instance, cls) else return unboundmethod(cls) > though. I think it only happens when the metaclass of a class > processes the functions in the class block. Nope, this is totally unrelated. class Foo(object): def __init__(self, bar): self.bar = 42 def baaz(obj, whatever): print obj.bar, whatever Foo.baaz = baaz f= Foo() f.baaz("is the answer") >>> 3.) Attributes that are read from an object with regular .dot syntax, >>> but are actually attributes (in the sense of #1 above) of the __dict__ >>> of the object's class. >> This is a ?class attribute? as distinct from an ?instance attribute?. >> > > I know it's called that, but I was talking more about the fact of it > being accessed through an instance of the class rather than Except for descriptors, this doesn't make much difference difference. From jeanmichel at sequans.com Fri Dec 4 10:31:31 2009 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Fri, 04 Dec 2009 16:31:31 +0100 Subject: testing command line scripts that use optparse In-Reply-To: <4B18472E.7040801@mycircuit.org> References: <4B18472E.7040801@mycircuit.org> Message-ID: <4B192B53.3020403@sequans.com> Peter wrote: > Hi > I have a script like this: > > def doit(input, output): > parser = OptionParser() > parser.add_option("-a", "--accounts", dest="accounts", default="all", > help="list available accounts") > ... > > (options, args) = parser.parse_args() > > > # main driver > if __name__ == "__main__": > import sys > doit(sys.stdin, sys.stdout) > > that I would like to test like this: > > def test_accounts(self): > input = """-aRoot""" output = """Results""" > self.runtest(input, output) > def runtest(self, input, expected): > inputStream = cStringIO.StringIO(input) > actual = cStringIO.StringIO() > doit(inputStream, actual) > assert_equal(actual.getvalue(), expected) > > But when running test_accounts, I get: > ... > File "/usr/local/python2.6/lib/python2.6/optparse.py", line 1578, in > error > self.exit(2, "%s: error: %s\n" % (self.get_prog_name(), msg)) > File "/usr/local/python2.6/lib/python2.6/optparse.py", line 1568, in > exit > sys.exit(status) > SystemExit: 2 > -------------------- >> begin captured stdout << --------------------- > stdin > > optparse expects a file object and gets a cStringIO. > > What is the correct way to set up this ? > Thanks for your help. > > Peter > It seems there is something wrong with the type of the paramaters given to the doit function. We can't say more cause cause you remove the related code of the doit function. But the error seems pretty clear to me : "optparse expects a file object and gets a cStringIO" JM From __peter__ at web.de Fri Dec 4 10:42:59 2009 From: __peter__ at web.de (Peter Otten) Date: Fri, 04 Dec 2009 16:42:59 +0100 Subject: Manyfile Processing References: Message-ID: user at domain.invalid wrote: > On 12/04/2009 12:58 PM, Dan Sommers wrote: > > On Fri, 04 Dec 2009 10:00:53 +0200, user wrote: > > > >> sorry if i bother you with a beginners question but i have an issue > >> with processing a bunch of files. They are some arithmetic lists the > >> processing of one file is an easy task but how do i process many files? > >> I tried reading that files in to a list and looping over the list > >> elements but the function won't accept any arguments other than a > >> string. > > > > Maybe the fileinput module can help. > > > > Dan > > > > Hi, > > seems like the fileinput module works fine for me though i am having > quite an issue with the paths. > > if i do: > > > something = fileinput.input("/some/absolute/path/to/list/file.txt") > #the text file contains absolute paths > for line in something: > data=scipy.io.array_import.read_array(line) > print data > > it claims that the paths given in the textfiles don't exist "no file or > directory" though taking one entry from the textfile and inserting it > directly to the command does its job... > > Any idea? line includes a trailing newline. You can see that if you modify your code to for line in something: print repr(line) Use line = line.strip() to remove the newline (in fact all leading and trailing whitespace). Peter From list at qtrac.plus.com Fri Dec 4 10:43:55 2009 From: list at qtrac.plus.com (Mark Summerfield) Date: Fri, 4 Dec 2009 07:43:55 -0800 (PST) Subject: Moving from Python 2 to Python 3: 4 page "cheat sheet" issue#3 References: <291d64cb-cc5c-4109-822c-84d58ed7b18b@k17g2000yqh.googlegroups.com> Message-ID: <3ea95225-4f53-4115-ba4d-d1b4dc967c4b@c3g2000yqd.googlegroups.com> On 3 Dec, 01:17, Antoine Pitrou wrote: > Le Tue, 01 Dec 2009 06:03:36 -0800, Mark Summerfield a ?crit?: > > > I've produced a 4 page document that provides a very concise summary of > > Python 2<->3 differences plus the most commonly used new Python 3 > > features. It is aimed at existing Python 2 programmers who want to start > > writing Python 3 programs and want to use Python 3 idioms rather than > > those from Python 2 where the idioms differ. > [...] > > > It is available as a free PDF download (no registration or anything) > > from InformIT's website. Here's the direct link: > > This is great! > > Just one thing: > > ? Copyright ? Qtrac Ltd. 2009. All rights reserved ? > > Might I suggest that you release it under a free license instead? > (such as the CC by, CC by-sa, or the Free Art License) > > Regards OK, issue#3 of the document is now available: http://www.informit.com/promotions/promotion.aspx?promo=137519 In the light of feedback from [these people] it now has: - an entry for file() vs. open() [Martin P. Hellwig] - an entry for %* vs. {:{}} syntax [John Posner, Mark Dickinson, & Carsten Haese] - creative commons license "CC by-sa" [Antoine Pitrou] So I hope it will prove even more useful now:-) From victorsubervi at gmail.com Fri Dec 4 10:52:43 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Fri, 4 Dec 2009 10:52:43 -0500 Subject: Killing Another Bug Message-ID: <4dc0cfea0912040752m98d81edi87adf659be72283c@mail.gmail.com> Hi; I have this code: for table in tables: if table == 'products': optionsCode = optionsCodeProducts fromForm = prodsFromForm try: fn = getattr(options, table) fromForm = form.getfirst('%s-options' % table) fromForm = string.split(fromForm[2:-2], "', '") optionsCode = fn(table, 'specificCode', fromForm) except: if table != 'products': # We recall we must add the products table fields to all tables. optionsCode = optionsCodeProducts i = 0 j = 0 oldJ = 0 try: y = 0 while y < len(optionsCode): if table == 'prescriptions': print len(optionsCode) # prints '2' for inputName in optionsCode[y]: if table == 'prescriptions': print len(optionsCode[y]) # prints '7' print inputName # prints 'Extra-small', which is only the first inputName in optionsCode[0] if j != oldJ: i = 0 oldJ = j x = '%s-%s%d' % (table, fromForm[y], i) x = form.getfirst(x) if x is not None: ourInputNames.append('%s-%s' % (table, inputName)) i += 1 j += 1 y += 1 except: pass As you can see in the supplied comments, when I loop through for table 'prescriptions', it only prints out the first element of each variable. When I loop through for table 'products', it prints out all of them! Why? TIA, Victor -------------- next part -------------- An HTML attachment was scrubbed... URL: From neilc at norwich.edu Fri Dec 4 10:57:31 2009 From: neilc at norwich.edu (Neil Cerutti) Date: 4 Dec 2009 15:57:31 GMT Subject: slightly OT: Python BootCamp References: <36dec4ff0911281815p583598i43a476bc66083e29@mail.gmail.com> <00a1e89d$0$26893$c3e8da3@news.astraweb.com> Message-ID: <7nsprbF3l73hoU1@mid.individual.net> On 2009-12-04, Steven D'Aprano wrote: > How would I re-write this? Just get rid of the try block and > add a close: > > for (exten, list) in files.iteritems(): > f=open('extensions-%s.txt' % exten,'w') > f.write('\n'.join(list)) "\n".join is a cute shortcut, but if you use it you must remember to write the last, trailing '\n' manually. > That's still not quite "best practice" -- best practice would > be to use a with block, but (to my shame) I'm not entirely > familiar with that so I'll leave it for others. from __future__ import with_statement # Etc. for (exten, list) in files.iteritems(): with open('extensions-%s.txt' % exten,'w') as f: f.write('\n'.join(list)) f.write('\n') -- Neil Cerutti From python at mrabarnett.plus.com Fri Dec 4 11:17:20 2009 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 04 Dec 2009 16:17:20 +0000 Subject: python bijection In-Reply-To: <4B18F685.8050102@egenix.com> References: <7n39ojF3jj6iuU1@mid.individual.net> <12c55890-118d-4655-b6c0-c908c9734a17@a32g2000yqm.googlegroups.com> <85100df7-a8b0-47e9-a854-ba8a8a2f3b98@r31g2000vbi.googlegroups.com> <4B17A960.1090700@egenix.com> <4B17FBFE.8070903@egenix.com> <4B18F685.8050102@egenix.com> Message-ID: <4B193610.6050700@mrabarnett.plus.com> M.-A. Lemburg wrote: > geremy condra wrote: >> On Thu, Dec 3, 2009 at 12:57 PM, M.-A. Lemburg wrote: >>> geremy condra wrote: >>>> On Thu, Dec 3, 2009 at 7:04 AM, M.-A. Lemburg wrote: >>>>> I think the only major CS data type missing from Python is some >>>>> form of (fast) directed graph implementation ? la kjGraph: >>>>> >>>>> http://gadfly.sourceforge.net/kjbuckets.html >>>>> >>>>> With these, you can easily build all sorts of relations between >>>>> objects and apply fast operations on them. In fact, it should then >>>>> be possible to build a complete relational database in Python >>>>> (along the lines of Gadfly). >>>> If you're in the market for a Python graph library, you may want >>>> to check out Graphine- I'm obviously biased (I wrote most of it) >>>> but it has a few more bells and whistles than kjbuckets, and is >>>> pretty darned easy to use. It also supports undirected and >>>> bridge graphs. >>> Thanks for the hint :-) >>> >>> The lib looks nice and would probably serve as a good prototype >>> for writing a new built-in type for Python. >> I suspect that it would have a better chance at getting into >> collections than becoming a builtin, but who knows. I'd just >> like to have something like it in the standard library. > > Integrating an easy-to-use graph library into the collections > module (and it's C companion) is good idea. > >>> This would have to be written in C, though, >> That's currently in the works, along with database backing. >> We'd welcome any help though... hint, hint... >> >>> and come under a Python compatible license. >> I'm willing to dual license under the Python license if >> there were a substantial interest in doing so, and I'm >> confident that the other authors and maintainers >> would feel the same way. > > Great ! > >> The question in my mind is whether such an interest exists. > > Since Python is being used more and more in CS classes, > such an addition would complete the tool-set and make Python > even more attractive for undergrad CS courses. > > Finding out how much interest exists in advance is always > a bit difficult with new data-structures. People have to > get a feeling of how they can be put to good use first, > so it's a chicken-and-egg problem. > > We've seen the same thing happen with sets. They were first > made available via a separate module and then became built-ins > after people realized how useful they are in practice. > I'd like to add that people (myself included) were already using dicts for sets before the module was written, so there was already a clear demand for them. > With graphs, it's probably going to take a little longer > before people realize their usefulness - graph theory is > certainly a lot more complicated than set theory :-) > >>> With the built-in feature moratorium >>> currently in place, there's about 1.5-2 years time to get this >>> done; perhaps a good GSoC project for next year :-) >> I'd love to have Graphine be a GSoC project, although >> if the target were to get it into collections the >> moratorium wouldn't change the timeline AFAICS. > > True. > From python at mrabarnett.plus.com Fri Dec 4 11:19:50 2009 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 04 Dec 2009 16:19:50 +0000 Subject: Why the expression "(1)" is not an one-arity tuple, but int ? In-Reply-To: <6faf39c90912040426t25d67b60s66cfcbe137d1686e@mail.gmail.com> References: <1dcb5c470912040417mbd6d8e0q4cdd1e66c3c2b4e4@mail.gmail.com> <6faf39c90912040426t25d67b60s66cfcbe137d1686e@mail.gmail.com> Message-ID: <4B1936A6.6090406@mrabarnett.plus.com> Andre Engels wrote: > 2009/12/4 ?????? ????????? : >> Hello All ! >> >> In my code I try to use a generic approach to work with tuples. Let >> "X" be a tuple. >> When I want to access a first element of a tuple, I can write: "X[0]". >> And that is really working when X is a n-arity tuple, with n>1 (for >> example "foo( (1,2,3) )" ). >> But when I call my library function with a 1-arity tuple (for example >> "foo( (1) )" ) I have an error: >> >> TypeError: 'int' object is unsubscriptable >> >> How could I tell Python that "(1)" is not an integer, but an one-arity tuple ? > > Tuples in Python are recognized/defined not by the brackets, but by > the commas; the brackets just function to specify the exact beginning > and ending of the tuple in cases where that is not directly clear. > "(1,2,3)" is a tuple, but "1,2,3" is also the same tuple. A 1-tuple > can be created as "1," or "(1,)". > The only exception is the 0-tuple (). No comma. From duncan.booth at invalid.invalid Fri Dec 4 11:23:09 2009 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 4 Dec 2009 16:23:09 GMT Subject: Are routine objects guaranteed mutable & with dictionary? References: Message-ID: "Alf P. Steinbach" wrote: > The question is what guarantees or absence thereof the language > specification, PEPs, intentions, whatever gives/has. See the documentation: http://docs.python.org/3.1/reference/datamodel.html > > >> BTW, it's a function, not a "routine" > > Wikipedia is your friend, http://en.wikipedia.org/wiki/Subroutine>. > Yes, but if you use the same terminology as everyone else you'll look under 'User-defined functions' on the page I referenced above. Looking under 'routine' or 'subroutine' won't get you very far. -- Duncan Booth http://kupuguy.blogspot.com From python at mrabarnett.plus.com Fri Dec 4 11:43:56 2009 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 04 Dec 2009 16:43:56 +0000 Subject: Killing Another Bug In-Reply-To: <4dc0cfea0912040752m98d81edi87adf659be72283c@mail.gmail.com> References: <4dc0cfea0912040752m98d81edi87adf659be72283c@mail.gmail.com> Message-ID: <4B193C4C.6080802@mrabarnett.plus.com> Victor Subervi wrote: > Hi; > I have this code: > [snip] > > As you can see in the supplied comments, when I loop through for table > 'prescriptions', it only prints out the first element of each variable. > When I loop through for table 'products', it prints out all of them! Why? > If you're serious about killing bugs, DON'T USE BARE EXCEPTS, especially ones which contain only "pass"! As for you're problem, it's not clear to me which one is behaving correctly. You should add more print statements to tell you where it is in the code, and then read through the output, checking the logic. Are the values what you expect? Is it following the route through the code that you expect? From doomster at knuut.de Fri Dec 4 12:20:25 2009 From: doomster at knuut.de (Ulrich Eckhardt) Date: Fri, 04 Dec 2009 18:20:25 +0100 Subject: More elegant solution for diffing two sequences References: <7nqorbF3n7go3U1@mid.uni-berlin.de> <4b183159@dnews.tpgi.com.au> Message-ID: <7nsumqF3ni9iqU1@mid.uni-berlin.de> Lie Ryan wrote: > On 12/4/2009 8:28 AM, Ulrich Eckhardt wrote: >> I'm trying to write some code to diff two fonts. What I have is every >> character (glyph) of the two fonts in a list. I know that the list is >> sorted by the codepoints of the characters. What I'd like to ask is >> whether there is a more elegant solution to the loop below or whether >> there are any rough corners in my code (see below). Note that I'm >> targeting Python 2, not 3 yet. >> > > Use sets: > > glyph_1 = set(font1.glyphs) > glyph_2 = set(font2.glyphs) > only_in_1 = glyph_1 - glyph_2 > only_in_2 = glyph_2 - glyph_1 > in_both = glyph_1 & glyph_2 > > that is assuming font1.glyphs's value are hashable. Thinking about it, I perhaps should store the glyphs in a set from the beginning. Question is, can I (perhaps by providing the right hash function) sort them by their codepoint? I'll have to look at the docs... Thank you for this nudge in the right direction! Uli From rami.chowdhury at gmail.com Fri Dec 4 12:56:21 2009 From: rami.chowdhury at gmail.com (Rami Chowdhury) Date: Fri, 4 Dec 2009 09:56:21 -0800 Subject: Are routine objects guaranteed mutable & with dictionary? In-Reply-To: References: Message-ID: <2f79f590912040956t278737a4vdda0ca4b09c9c7e0@mail.gmail.com> >> BTW, it's a function, not a "routine" > > Wikipedia is your friend, . > > I don't think it was a problem of comprehension, more one of appropriate terminology -- AFAIK in Python, they're called functions, so calling them 'routines' is likely to confuse anyone in a discussion of Python features. -------- Rami Chowdhury "Never assume malice when stupidity will suffice." -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) From apt.shansen at gmail.com Fri Dec 4 13:06:40 2009 From: apt.shansen at gmail.com (Stephen Hansen) Date: Fri, 4 Dec 2009 10:06:40 -0800 Subject: memory error In-Reply-To: <1482CDE5CD38BC4B99F6182262ADCB2925FAAE@EXCHVS02.ad.sfwmd.gov> References: <6e8c880b-a9f4-4063-8e77-e77679f6b54c@m3g2000yqf.googlegroups.com> <1482CDE5CD38BC4B99F6182262ADCB2925FAA4@EXCHVS02.ad.sfwmd.gov> <7a9c25c20912031922u416e9df6q26d4e3cc7a78bbe7@mail.gmail.com> <1482CDE5CD38BC4B99F6182262ADCB2925FAAE@EXCHVS02.ad.sfwmd.gov> Message-ID: <7a9c25c20912041006kff80f86lbd5ad2287e9cd351@mail.gmail.com> > > But-- the image does say Pythonwin... are you running this from the > Pythonwin editor/IDE? Does this script crash out if you run it through the > normal 'python'(or pythonw) commands? If not, are you attempting to do any > sort of GUI work in this script? That rarely works within Pythonwin > directly. > > I am using python to do some gp ( geo processing ) for accuracy analysis. > This analysis is based on application numbers. The script is going through > each application number to process the data and looping through. The error > appears after running few loops ( mean it process few applications). There > is no certainty of how many loops it is going through but stopped with the > error message and. > > > You didn't answer my other questions-- have you run this with python directly and not PythonWin? It doesn't look like it you're doing anything GUI-ish, but I don't know anything about "arcgisscripting"... which is almost certainly where the error is happening, its really hard to get access violations in pure Python. You'll probably need to add a (lot) of logging into the script to narrow down precisely where this error is happening, that it happens 'eventually' and 'somewhere' in the loop isn't going to help. I'd guess that eventually a certain piece of data in there gets passed to this library and everything explodes. --S -------------- next part -------------- An HTML attachment was scrubbed... URL: From victorsubervi at gmail.com Fri Dec 4 13:08:20 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Fri, 4 Dec 2009 14:08:20 -0400 Subject: Killing Another Bug In-Reply-To: <4B193C4C.6080802@mrabarnett.plus.com> References: <4dc0cfea0912040752m98d81edi87adf659be72283c@mail.gmail.com> <4B193C4C.6080802@mrabarnett.plus.com> Message-ID: <4dc0cfea0912041008q3ce5a557u782f8d5488895a5d@mail.gmail.com> On Fri, Dec 4, 2009 at 12:43 PM, MRAB wrote: > Victor Subervi wrote: > >> Hi; >> I have this code: >> >> > [snip] > > As you can see in the supplied comments, when I loop through for table >> 'prescriptions', it only prints out the first element of each variable. When >> I loop through for table 'products', it prints out all of them! Why? >> >> If you're serious about killing bugs, DON'T USE BARE EXCEPTS, especially > ones which contain only "pass"! > > As for you're problem, it's not clear to me which one is behaving > correctly. You should add more print statements to tell you where it is in > the code, and then read through the output, checking the logic. Are > the values what you expect? Is it following the route through the code > that you expect? > Forgive me, but I believe I already addressed your question. There are two tables: prescriptions and products, in that order, and both with (in this case) the exact same options. For some reason, when products goes through the loops, everything comes out exactly as expected. But when prescriptions goes through, only optionsCode[0] passes (there are two) and only optionsCode[0][0] goes through when there are 7. To restate that, both optionsCode[y] and all optionsCode[y][z] get correctly processed when 'products' goes through, but only one when 'prescriptions' goes through, and the options and options tables are identical! Here's the code again. Please advise. V for table in tables: if table == 'products': optionsCode = optionsCodeProducts fromForm = prodsFromForm try: fn = getattr(options, table) fromForm = form.getfirst('%s-options' % table) fromForm = string.split(fromForm[2:-2], "', '") optionsCode = fn(table, 'specificCode', fromForm) except: if table != 'products': # We recall we must add the products table fields to all tables. optionsCode = optionsCodeProducts i = 0 j = 0 oldJ = 0 try: y = 0 while y < len(optionsCode): if table == 'prescriptions': print len(optionsCode) # prints '2' for inputName in optionsCode[y]: if table == 'prescriptions': print len(optionsCode[y]) # prints '7' print inputName # prints 'Extra-small', which is only the first inputName in optionsCode[0] if j != oldJ: i = 0 oldJ = j x = '%s-%s%d' % (table, fromForm[y], i) x = form.getfirst(x) if x is not None: ourInputNames.append('%s-%s' % (table, inputName)) i += 1 j += 1 y += 1 except: pass -------------- next part -------------- An HTML attachment was scrubbed... URL: From neilc at norwich.edu Fri Dec 4 13:20:26 2009 From: neilc at norwich.edu (Neil Cerutti) Date: 4 Dec 2009 18:20:26 GMT Subject: More elegant solution for diffing two sequences References: <7nqorbF3n7go3U1@mid.uni-berlin.de> <4b183159@dnews.tpgi.com.au> <7nsumqF3ni9iqU1@mid.uni-berlin.de> Message-ID: <7nt27aF3n7f29U1@mid.individual.net> On 2009-12-04, Ulrich Eckhardt wrote: > Lie Ryan wrote: > Thinking about it, I perhaps should store the glyphs in a set > from the beginning. Question is, can I (perhaps by providing > the right hash function) sort them by their codepoint? I'll > have to look at the docs... No, sets are unordered in Python. You'll need to sort them when you need them sorted, or keep a sorted list separately. -- Neil Cerutti From victorsubervi at gmail.com Fri Dec 4 13:23:24 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Fri, 4 Dec 2009 14:23:24 -0400 Subject: Killing Another Bug In-Reply-To: <4dc0cfea0912041008q3ce5a557u782f8d5488895a5d@mail.gmail.com> References: <4dc0cfea0912040752m98d81edi87adf659be72283c@mail.gmail.com> <4B193C4C.6080802@mrabarnett.plus.com> <4dc0cfea0912041008q3ce5a557u782f8d5488895a5d@mail.gmail.com> Message-ID: <4dc0cfea0912041023n15e811e6ree2467b11076ebb2@mail.gmail.com> On Fri, Dec 4, 2009 at 2:08 PM, Victor Subervi wrote: > On Fri, Dec 4, 2009 at 12:43 PM, MRAB wrote: > >> Victor Subervi wrote: >> >>> Hi; >>> I have this code: >>> >>> >> [snip] >> >> As you can see in the supplied comments, when I loop through for table >>> 'prescriptions', it only prints out the first element of each variable. When >>> I loop through for table 'products', it prints out all of them! Why? >>> >>> If you're serious about killing bugs, DON'T USE BARE EXCEPTS, especially >> ones which contain only "pass"! >> >> As for you're problem, it's not clear to me which one is behaving >> correctly. You should add more print statements to tell you where it is in >> the code, and then read through the output, checking the logic. Are >> the values what you expect? Is it following the route through the code >> that you expect? >> > > Forgive me, but I believe I already addressed your question. There are two > tables: prescriptions and products, in that order, and both with (in this > case) the exact same options. For some reason, when products goes through > the loops, everything comes out exactly as expected. But when prescriptions > goes through, only optionsCode[0] passes (there are two) and only > optionsCode[0][0] goes through when there are 7. To restate that, both > optionsCode[y] and all optionsCode[y][z] get correctly processed when > 'products' goes through, but only one when 'prescriptions' goes through, and > the options and options tables are identical! Here's the code again. I just > now edited in a try statement to try to catch the bug, with no luck. Please > advise. > > V > > > for table in tables: > if table == 'products': > optionsCode = optionsCodeProducts > fromForm = prodsFromForm > try: > fn = getattr(options, table) > fromForm = form.getfirst('%s-options' % table) > fromForm = string.split(fromForm[2:-2], "', '") > optionsCode = fn(table, 'specificCode', fromForm) > except: > if table != 'products': # We recall we must add the products table > fields to all tables. > optionsCode = optionsCodeProducts > i = 0 > j = 0 > oldJ = 0 > try: > y = 0 > while y < len(optionsCode): > if table == 'prescriptions': > print len(optionsCode) # prints '2' > for inputName in optionsCode[y]: > if table == 'prescriptions': > print len(optionsCode[y]) # prints '7' > print inputName # prints 'Extra-small', which is only the first > inputName in optionsCode[0] > if j != oldJ: > i = 0 > oldJ = j > x = '%s-%s%d' % (table, fromForm[y], i) > try: > x = form.getfirst(x) > if x is not None: > ourInputNames.append('%s-%s' % (table, inputName)) > except: > print 'Oops!' > i += 1 > j += 1 > y += 1 > except: > pass > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at mrabarnett.plus.com Fri Dec 4 13:31:39 2009 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 04 Dec 2009 18:31:39 +0000 Subject: More elegant solution for diffing two sequences In-Reply-To: <7nsumqF3ni9iqU1@mid.uni-berlin.de> References: <7nqorbF3n7go3U1@mid.uni-berlin.de> <4b183159@dnews.tpgi.com.au> <7nsumqF3ni9iqU1@mid.uni-berlin.de> Message-ID: <4B19558B.1020900@mrabarnett.plus.com> Ulrich Eckhardt wrote: > Lie Ryan wrote: >> On 12/4/2009 8:28 AM, Ulrich Eckhardt wrote: >>> I'm trying to write some code to diff two fonts. What I have is every >>> character (glyph) of the two fonts in a list. I know that the list is >>> sorted by the codepoints of the characters. What I'd like to ask is >>> whether there is a more elegant solution to the loop below or whether >>> there are any rough corners in my code (see below). Note that I'm >>> targeting Python 2, not 3 yet. >>> >> Use sets: >> >> glyph_1 = set(font1.glyphs) >> glyph_2 = set(font2.glyphs) >> only_in_1 = glyph_1 - glyph_2 >> only_in_2 = glyph_2 - glyph_1 >> in_both = glyph_1 & glyph_2 >> >> that is assuming font1.glyphs's value are hashable. > > Thinking about it, I perhaps should store the glyphs in a set from the > beginning. Question is, can I (perhaps by providing the right hash function) > sort them by their codepoint? I'll have to look at the docs... > > Thank you for this nudge in the right direction! > For sets you need __hash__ and __eq__, and for sorting you need __lt__. Here's a simple example: class Glyph(object): def __init__(self, codepoint): self.codepoint = codepoint def __hash__(self): return self.codepoint def __eq__(self, other): return self.codepoint == other.codepoint def __lt__(self, other): return self.codepoint < other.codepoint def __repr__(self): return "Glyph(%s)" % self.codepoint From roy at panix.com Fri Dec 4 13:46:01 2009 From: roy at panix.com (Roy Smith) Date: Fri, 4 Dec 2009 10:46:01 -0800 (PST) Subject: How to tell if you're running on windows? Message-ID: <96d32eda-e021-4caa-a414-5f25b04b991d@o10g2000yqa.googlegroups.com> I'm using 2.5.1. How can I tell if I'm running on windows? The obvious answer, platform.system(), gets complicated. On the python that comes with cygwin, it returns 'CYGWIN_NT-5.2-WOW64', but I've got a native windows build of python where it returns 'Microsoft'. The real problem I'm trying to solve is whether to build a LIBPATH environment variable with ';' or ':' delimiting the entries. On the cygwin build, os.pathsep returns ':', which isn't really correct. If you use that, you end up building paths that look like c:foo:c:bar. It should be c:foo;c:bar From zephjc at gmail.com Fri Dec 4 14:19:47 2009 From: zephjc at gmail.com (zeph) Date: Fri, 4 Dec 2009 11:19:47 -0800 (PST) Subject: How to tell if you're running on windows? References: <96d32eda-e021-4caa-a414-5f25b04b991d@o10g2000yqa.googlegroups.com> Message-ID: <2afa780c-e779-47aa-8fd3-f718fe5fc353@u18g2000pro.googlegroups.com> On Dec 4, 10:46 am, Roy Smith wrote: > I'm using 2.5.1. How can I tell if I'm running on windows? The > obvious answer, platform.system(), gets complicated. On the python > that comes with cygwin, it returns 'CYGWIN_NT-5.2-WOW64', but I've got > a native windows build of python where it returns 'Microsoft'. > > The real problem I'm trying to solve is whether to build a LIBPATH > environment variable with ';' or ':' delimiting the entries. On the > cygwin build, os.pathsep returns ':', which isn't really correct. If > you use that, you end up building paths that look like c:foo:c:bar. > It should be c:foo;c:bar The Cygwin shell uses what appears to be its own pseudo-filesystem. If you open your Cygwin shell window and type echo $PATH you will see completely different results from the Windows command shell's PATH env variable, and you'll see the path sep is indeed ':'. Cygwin also seems to put drive mount points in /cygdrive/ so you will have for example "/cygdrive/c/foo:/cygdrive/c/bar" instead of "C: \foo;C:\bar". For python *outside* of Cygwin, on Windows, I assume os.path.pathsep is ';'. - zeph From lie.1296 at gmail.com Fri Dec 4 14:20:05 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Sat, 05 Dec 2009 06:20:05 +1100 Subject: More elegant solution for diffing two sequences In-Reply-To: <7nsumqF3ni9iqU1@mid.uni-berlin.de> References: <7nqorbF3n7go3U1@mid.uni-berlin.de> <4b183159@dnews.tpgi.com.au> <7nsumqF3ni9iqU1@mid.uni-berlin.de> Message-ID: <4b19615e$1@dnews.tpgi.com.au> On 12/5/2009 4:20 AM, Ulrich Eckhardt wrote: > Thinking about it, I perhaps should store the glyphs in a set from the > beginning. Question is, can I (perhaps by providing the right hash function) > sort them by their codepoint? I'll have to look at the docs... Python does not guarantee that a particular characteristic of the hash function will lead to a particular characteristic of the ordering of th eset. Though AFAICT, the current set's ordering is determined by the hash modulus the set's hashtable's real size, but if you rely on this you're on your own. It's better if you sorted() them when you want a sorted view (or turn to set just before finding the differences). You can reduce the penalty of creating new data structure with something like: a = [...] b = [...] s_a = set(a) s_a -= set(b) that only creates two new sets (instead of three) and probably might be faster too (though you'd need to profile to be sure). From alley at dragoncreativeworks.net Fri Dec 4 14:20:42 2009 From: alley at dragoncreativeworks.net (Allan Davis) Date: Fri, 4 Dec 2009 13:20:42 -0600 Subject: How to tell if you're running on windows? In-Reply-To: <96d32eda-e021-4caa-a414-5f25b04b991d@o10g2000yqa.googlegroups.com> References: <96d32eda-e021-4caa-a414-5f25b04b991d@o10g2000yqa.googlegroups.com> Message-ID: <61c507640912041120n5bbb7d5k8a2838ed3f1533f6@mail.gmail.com> Try this import sys import os sep = None if sys.platform == 'cygwin': sep = ';' else: sep = os.pathsep # then use sep in your path statment Hope this helps Thanks, -------------------------------------------------------------- Allan Davis Member of NetBeans Dream Team http://wiki.netbeans.org/NetBeansDreamTeam Lead Developer, nbPython http://wiki.netbeans.org/Python http://codesnakes.blogspot.com (my blog) Co-Chair, CajunJUG http://www.cajunjug.org On Fri, Dec 4, 2009 at 12:46 PM, Roy Smith wrote: > I'm using 2.5.1. How can I tell if I'm running on windows? The > obvious answer, platform.system(), gets complicated. On the python > that comes with cygwin, it returns 'CYGWIN_NT-5.2-WOW64', but I've got > a native windows build of python where it returns 'Microsoft'. > > The real problem I'm trying to solve is whether to build a LIBPATH > environment variable with ';' or ':' delimiting the entries. On the > cygwin build, os.pathsep returns ':', which isn't really correct. If > you use that, you end up building paths that look like c:foo:c:bar. > It should be c:foo;c:bar > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From lie.1296 at gmail.com Fri Dec 4 14:22:00 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Sat, 05 Dec 2009 06:22:00 +1100 Subject: Are routine objects guaranteed mutable & with dictionary? In-Reply-To: References: Message-ID: <4b1961d1$1@dnews.tpgi.com.au> On 12/5/2009 4:56 AM, Rami Chowdhury wrote: > I don't think it was a problem of comprehension, more one of > appropriate terminology -- AFAIK in Python, they're called functions, > so calling them 'routines' is likely to confuse anyone in a discussion > of Python features. Human language is not context-free, we can't parse human language with LL parser. From rridge at csclub.uwaterloo.ca Fri Dec 4 14:50:26 2009 From: rridge at csclub.uwaterloo.ca (Ross Ridge) Date: Fri, 04 Dec 2009 14:50:26 -0500 Subject: How to tell if you're running on windows? References: <96d32eda-e021-4caa-a414-5f25b04b991d@o10g2000yqa.googlegroups.com> Message-ID: Roy Smith wrote: >The real problem I'm trying to solve is whether to build a LIBPATH >environment variable with ';' or ':' delimiting the entries. On the >cygwin build, os.pathsep returns ':', which isn't really correct. If >you use that, you end up building paths that look like c:foo:c:bar. >It should be c:foo;c:bar What application is intepretting this LIBPATH environment variable? If it's another Cygwin app then ":" should be the correct seperator and you should be building paths that look like "/cygdrive/c/foo:/cygdrive/c/bar". I normally use the "os.name" variable to detect whether the script is running on Windows, but the Cygwin version of Python sets it to "posix". That works for me, since Cygwin tries hard to look like a Unix-type operating system, my scripts should too. In your case you can use the "sys.platform" variable to distinguish between Cygwin and a real Unix-type OS. You may end up needing to treat Cygwin as a special case. Ross Ridge -- l/ // Ross Ridge -- The Great HTMU [oo][oo] rridge at csclub.uwaterloo.ca -()-/()/ http://www.csclub.uwaterloo.ca/~rridge/ db // From debatem1 at gmail.com Fri Dec 4 14:53:39 2009 From: debatem1 at gmail.com (geremy condra) Date: Fri, 4 Dec 2009 14:53:39 -0500 Subject: python bijection In-Reply-To: References: <85100df7-a8b0-47e9-a854-ba8a8a2f3b98@r31g2000vbi.googlegroups.com> <4B17A960.1090700@egenix.com> <4B17FBFE.8070903@egenix.com> <4B18F685.8050102@egenix.com> <4B193610.6050700@mrabarnett.plus.com> Message-ID: On Fri, Dec 4, 2009 at 2:52 PM, geremy condra wrote: > On Fri, Dec 4, 2009 at 11:17 AM, MRAB wrote: >> M.-A. Lemburg wrote: >>> >>> geremy condra wrote: >>>> >>>> On Thu, Dec 3, 2009 at 12:57 PM, M.-A. Lemburg wrote: >>>>> >>>>> geremy condra wrote: >>>>>> >>>>>> On Thu, Dec 3, 2009 at 7:04 AM, M.-A. Lemburg wrote: >>>>>>> >>>>>>> I think the only major CS data type missing from Python is some >>>>>>> form of (fast) directed graph implementation ? la kjGraph: >>>>>>> >>>>>>> ? http://gadfly.sourceforge.net/kjbuckets.html >>>>>>> >>>>>>> With these, you can easily build all sorts of relations between >>>>>>> objects and apply fast operations on them. In fact, it should then >>>>>>> be possible to build a complete relational database in Python >>>>>>> (along the lines of Gadfly). >>>>>> >>>>>> If you're in the market for a Python graph library, you may want >>>>>> to check out Graphine- I'm obviously biased (I wrote most of it) >>>>>> but it has a few more bells and whistles than kjbuckets, and is >>>>>> pretty darned easy to use. It also supports undirected and >>>>>> bridge graphs. >>>>> >>>>> Thanks for the hint :-) >>>>> >>>>> The lib looks nice and would probably serve as a good prototype >>>>> for writing a new built-in type for Python. >>>> >>>> I suspect that it would have a better chance at getting into >>>> collections than becoming a builtin, but who knows. I'd just >>>> like to have something like it in the standard library. >>> >>> Integrating an easy-to-use graph library into the collections >>> module (and it's C companion) is good idea. >>> >>>>> This would have to be written in C, though, >>>> >>>> That's currently in the works, along with database backing. >>>> We'd welcome any help though... hint, hint... >>>> >>>>> and come under a Python compatible license. >>>> >>>> I'm willing to dual license under the Python license if >>>> there were a substantial interest in doing so, and I'm >>>> confident that the other authors and maintainers >>>> would feel the same way. >>> >>> Great ! >>> >>>> The question in my mind is whether such an interest exists. >>> >>> Since Python is being used more and more in CS classes, >>> such an addition would complete the tool-set and make Python >>> even more attractive for undergrad CS courses. >>> >>> Finding out how much interest exists in advance is always >>> a bit difficult with new data-structures. People have to >>> get a feeling of how they can be put to good use first, >>> so it's a chicken-and-egg problem. >>> >>> We've seen the same thing happen with sets. They were first >>> made available via a separate module and then became built-ins >>> after people realized how useful they are in practice. >>> >> I'd like to add that people (myself included) were already using dicts >> for sets before the module was written, so there was already a clear >> demand for them. >> To be fair, I don't think you'd have to look very far to find places where a graph representation is approximated using some combination of dicts, sets, and lists. ElementTree comes to mind immediately, and the dict-of-dicts idea for logging recently discussed on python-dev explicitly states that it uses that structure to represent object graphs. To me that says that there is at least some demand. Geremy Condra From lie.1296 at gmail.com Fri Dec 4 14:57:49 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Sat, 05 Dec 2009 06:57:49 +1100 Subject: Formatting logically nested actions -- Pythonic way? In-Reply-To: References: Message-ID: <4b196a36$1@dnews.tpgi.com.au> On 12/4/2009 5:24 PM, Alf P. Steinbach wrote: > Hi. > > I discovered with tkinter the registration of widgets with layout > managers (tkinter "geometry" managers, e.g. calls to pack()) needs to be > done very hierarchically. > > And this leads to hierarchical code, which would be nice to indicate by > indenting, but oops, indenting in Python is syntactically significant... > > So first I thought of one routine per widget creation & layout > registration, but that was very ugly and verbose. Then thought of simply > using semicolons but I didn't even try that, because I imagined the > sheer ugliness. Then I sort of landed on the solution below, but > although using the language to define a kind of special purpose > mini-language is common in C++ and Lisp I haven't seen so much of that > in Python examples, and so I wonder whether this is Pythonic or perhaps > so extremely un-Pythonic (unconventional) that it's scary -- I mean, > calls that do nothing whatsoever, but I think of *visual structure* as > very important here and IMHO (disregarding Pythonicity issues) worth the > overhead... maybe you can extend it a bit and make it more useful by auto-packing the widget when the with-block ended. As for the case when you need to pass arguments to the packer, perhaps the packing manager's argument could be turned into an attribute like so: import tkinter as tk root = tk.Tk() with Place(root, tk.Frame()) as display_area: pic = tk.PhotoImage( file = "lightbulb_off.gif" ) with Pack(display_area, tk.Label) as pic_display: pic_display.image = pic # or perhaps just pic_display.side = "left" pic_display.pack_side = "left" with Pack(display_area, tk.Frame) as interaction_area: interaction_area.width = 500 with Pack(interaction_area, tk.Label) as status_line: status_line.text = "The switch is OFF" status_line.pack_anchor = "w" with Pack(interaction_area, tk.Button) as toggle_button: toggle_button.text = " Toggle it " toggle_button.pack_anchor = "w" interaction_area.pack_side = "left" display_area.place_relx = 0.5 display_area.place_rely = 0.5 display_area.place_anchor = "center" something like this would make working with GUI much less painful... From drobinow at gmail.com Fri Dec 4 14:57:50 2009 From: drobinow at gmail.com (David Robinow) Date: Fri, 4 Dec 2009 14:57:50 -0500 Subject: How to tell if you're running on windows? In-Reply-To: <96d32eda-e021-4caa-a414-5f25b04b991d@o10g2000yqa.googlegroups.com> References: <96d32eda-e021-4caa-a414-5f25b04b991d@o10g2000yqa.googlegroups.com> Message-ID: <4eb0089f0912041157q10ef079ej24ce48a9965ad911@mail.gmail.com> On Fri, Dec 4, 2009 at 1:46 PM, Roy Smith wrote: > I'm using 2.5.1. ?How can I tell if I'm running on windows? ?The > obvious answer, platform.system(), gets complicated. ?On the python > that comes with cygwin, it returns 'CYGWIN_NT-5.2-WOW64', but I've got > a native windows build of python where it returns 'Microsoft'. > > The real problem I'm trying to solve is whether to build a LIBPATH > environment variable with ';' or ':' delimiting the entries. ?On the > cygwin build, os.pathsep returns ':', which isn't really correct. ?If > you use that, you end up building paths that look like c:foo:c:bar. > It should be c:foo;c:bar It's not clear to me what you're using LIBPATH for. Are you running a cygwin executable from Python? Or a Windows executable from cygwin? LIBPATH should be in the format desired by the consumer. From lie.1296 at gmail.com Fri Dec 4 15:10:14 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Sat, 05 Dec 2009 07:10:14 +1100 Subject: python bijection In-Reply-To: References: <85100df7-a8b0-47e9-a854-ba8a8a2f3b98@r31g2000vbi.googlegroups.com> <4B17A960.1090700@egenix.com> <4B17FBFE.8070903@egenix.com> <4B18F685.8050102@egenix.com> <4B193610.6050700@mrabarnett.plus.com> Message-ID: <4b196d1f$1@dnews.tpgi.com.au> On 12/5/2009 6:53 AM, geremy condra wrote: > To be fair, I don't think you'd have to look very far to find places > where a graph representation is approximated using some > combination of dicts, sets, and lists. ElementTree comes to mind > immediately, and the dict-of-dicts idea for logging recently > discussed on python-dev explicitly states that it uses that > structure to represent object graphs. To me that says that there > is at least some demand. Though I've never used ElementTree extensively before, I thought it was supposed to use a Tree structure (though it is a subset of graph, the need for tree is much more common than full-blown graph package). From callmeclaudius at gmail.com Fri Dec 4 15:22:55 2009 From: callmeclaudius at gmail.com (Joel Davis) Date: Fri, 4 Dec 2009 12:22:55 -0800 (PST) Subject: Partial list comprehensions Message-ID: Is it possible to run a list comprehension over a certain portion of the list? My goals is to be able to run the comprehension on the innermost elements of the list, but leaving the outermost intact. From apt.shansen at gmail.com Fri Dec 4 15:40:32 2009 From: apt.shansen at gmail.com (Stephen Hansen) Date: Fri, 4 Dec 2009 12:40:32 -0800 Subject: Partial list comprehensions In-Reply-To: References: Message-ID: <7a9c25c20912041240g884738bs479582289db329af@mail.gmail.com> > > Is it possible to run a list comprehension over a certain portion of > the list? My goals is to be able to run the comprehension on the > innermost elements of the list, but leaving the outermost intact. > Without seeing an example of what your list is, and what you want to turn it into, its sort of hard to be certain what it is you really want to do. Is it: >>> a = range(100) >>> a[2:-2] = [str(x) for x in a[2:-2]] >>> a [0, 1, '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '70', '71', '72', '73', '74', '75', '76', '77', '78', '79', '80', '81', '82', '83', '84', '85', '86', '87', '88', '89', '90', '91', '92', '93', '94', '95', '96', '97', 98, 99] Where I converted to a string the "inner" elements with a list comprehension but left the outer ones alone? --S -------------- next part -------------- An HTML attachment was scrubbed... URL: From mensanator at aol.com Fri Dec 4 15:41:11 2009 From: mensanator at aol.com (Mensanator) Date: Fri, 4 Dec 2009 12:41:11 -0800 (PST) Subject: Partial list comprehensions References: Message-ID: On Dec 4, 2:22?pm, Joel Davis wrote: > Is it possible to run a list comprehension over a certain portion of > the list? My goals is to be able to run the comprehension on the > innermost elements of the list, but leaving the outermost intact. Something like this? >>> a [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> b = [i for i in a[0:5]] >>> b [0, 1, 2, 3, 4] >>> c = [i for i in a if i%2==0] >>> c [0, 2, 4, 6, 8] >>> From debatem1 at gmail.com Fri Dec 4 15:46:37 2009 From: debatem1 at gmail.com (geremy condra) Date: Fri, 4 Dec 2009 15:46:37 -0500 Subject: python bijection In-Reply-To: <4b196d1f$1@dnews.tpgi.com.au> References: <4B17A960.1090700@egenix.com> <4B17FBFE.8070903@egenix.com> <4B18F685.8050102@egenix.com> <4B193610.6050700@mrabarnett.plus.com> <4b196d1f$1@dnews.tpgi.com.au> Message-ID: On Fri, Dec 4, 2009 at 3:10 PM, Lie Ryan wrote: > On 12/5/2009 6:53 AM, geremy condra wrote: >> >> To be fair, I don't think you'd have to look very far to find places >> where a graph representation is approximated using some >> combination of dicts, sets, and lists. ElementTree comes to mind >> immediately, and the dict-of-dicts idea for logging recently >> discussed on python-dev explicitly states that it uses that >> structure to represent object graphs. To me that says that there >> is at least some demand. > > Though I've never used ElementTree extensively before, I thought it was > supposed to use a Tree structure (though it is a subset of graph, the need > for tree is much more common than full-blown graph package). Sure, its a tree, which is also a graph. In this case it looks to me more like a directed acyclic graph than anything, but its pretty much just semantics since the interface is functionally equivalent. Geremy Condra From apt.shansen at gmail.com Fri Dec 4 15:46:38 2009 From: apt.shansen at gmail.com (Stephen Hansen) Date: Fri, 4 Dec 2009 12:46:38 -0800 Subject: Killing Another Bug In-Reply-To: <4dc0cfea0912040752m98d81edi87adf659be72283c@mail.gmail.com> References: <4dc0cfea0912040752m98d81edi87adf659be72283c@mail.gmail.com> Message-ID: <7a9c25c20912041246lc94d36fka444b9ca9d5693f@mail.gmail.com> On Fri, Dec 4, 2009 at 7:52 AM, Victor Subervi wrote: > except: > > except: > pass > If you want any hope of fixing the bug, remove both of these. Really -- do not use bare excepts. In the first one, it looks like you're expecting sometimes there to be an exception: that's okay. If you think an operation will produce one, its okay to catch it if you know how to handle it. But do NOT use bare excepts. Catch the actual exception you are expecting-- a KeyError maybe? ValueError? I don't know, can't tell without knowing what "fn" does. In the second-- that bare except with a pass is doing absolutely nothing but _destroying_ any chance you have of finding out what the bug IS and fixing the bug. Remove that entire try/except: pass statement. Really. You absolutely have to do it. The only reason you have not already found and fixed this bug is that you have done this-- you can't do this and then ask us to find the bug for you. Bare excepts are there for a reason, and there are times to use them. But those are the exception and not the rule; and the time to use a except: pass construct is NOT when you're trying to fix a bug. --S -------------- next part -------------- An HTML attachment was scrubbed... URL: From pruebauno at latinmail.com Fri Dec 4 15:57:35 2009 From: pruebauno at latinmail.com (nn) Date: Fri, 4 Dec 2009 12:57:35 -0800 (PST) Subject: Which is more pythonic? References: Message-ID: <44df9708-6d31-4f85-b34f-c04c57227bc5@k4g2000yqb.googlegroups.com> On Dec 3, 10:41?am, Filip Gruszczy?ski wrote: > I have just written a very small snippet of code and started thinking, > which version would be more pythonic. Basically, I am adding a list of > string to combo box in qt. So, the most obvious way is: > > for choice in self.__choices: > ? ? ? ? choicesBox.addItem(choice) > > But I could also do: > > map(self.__choices, choicesBox.addItem) > > or > > [choicesBox.addItem(choice) for choice in self.__choices] > > I guess map version would be fastest and explicit for is the slowest > version. However, the first, most obvious way seems most clear to me > and I don't have to care about speed with adding elements to combo > box. Still, it's two lines instead of one, so maybe it's not the best. > So, which one is? > > -- > Filip Gruszczy?ski First option is the most pythonic IMO. If it HAS to be one line I would still prefer: for choice in self.__choices: choicesBox.addItem(choice) From roy at panix.com Fri Dec 4 16:14:29 2009 From: roy at panix.com (Roy Smith) Date: Fri, 04 Dec 2009 16:14:29 -0500 Subject: How to tell if you're running on windows? References: <96d32eda-e021-4caa-a414-5f25b04b991d@o10g2000yqa.googlegroups.com> Message-ID: In article , David Robinow wrote: > On Fri, Dec 4, 2009 at 1:46 PM, Roy Smith wrote: > > I'm using 2.5.1. ?How can I tell if I'm running on windows? ?The > > obvious answer, platform.system(), gets complicated. ?On the python > > that comes with cygwin, it returns 'CYGWIN_NT-5.2-WOW64', but I've got > > a native windows build of python where it returns 'Microsoft'. > > > > The real problem I'm trying to solve is whether to build a LIBPATH > > environment variable with ';' or ':' delimiting the entries. ?On the > > cygwin build, os.pathsep returns ':', which isn't really correct. ?If > > you use that, you end up building paths that look like c:foo:c:bar. > > It should be c:foo;c:bar > > It's not clear to me what you're using LIBPATH for. > Are you running a cygwin executable from Python? Or a Windows > executable from cygwin? Our build and test environment for windows is cygwin. This is a Python test script running a native windows executable using subprocess.Popen(). The LIBPATH I'm building is for the executable's environment. We're looking to possibly replace cygwin with MinGW at some point in the future. In the past, we've always equated "cygwin" and "windows" in our build scripts, but now that we're thinking MinGW-ish thoughts, that's looking like a sub-optimal strategy. > LIBPATH should be in the format desired by the consumer. From tjreedy at udel.edu Fri Dec 4 16:23:44 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 04 Dec 2009 16:23:44 -0500 Subject: Are routine objects guaranteed mutable & with dictionary? In-Reply-To: References: Message-ID: Alf P. Steinbach wrote: > The question is what guarantees or absence thereof the language > specification, PEPs, intentions, whatever gives/has. The two docs backed up by PEPs. I suppose the docs could be clearer. 5.3.1 says "The primary must evaluate to an object of a type that supports attribute references, which most objects do." This is true for attribute access, but not for attribute setting. See http://bugs.python.org/issue7436 for my suggest addition. >> BTW, it's a function, not a "routine" > > Wikipedia is your friend, . which says "the C and C++ programming languages, subprograms are referred to as "functions" (or "methods" when associated with a class)." The same is true for Python and many other languages. Some languages have separate statements for defining functions and (non-function) subroutines. If you want to be understood, use function. I thought you mean 'routine' as opposed to 'special'. Terry Jan Reedy From tjreedy at udel.edu Fri Dec 4 16:27:40 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 04 Dec 2009 16:27:40 -0500 Subject: Insane Problem In-Reply-To: <4dc0cfea0912040205o57897f11u2bc16751784f1d77@mail.gmail.com> References: <4dc0cfea0912021218g797f782esa2c174923b6ac492@mail.gmail.com> <4B16D739.5080408@mrabarnett.plus.com> <4dc0cfea0912030307j7556eb06j469ccc4e6a29d1ee@mail.gmail.com> <4dc0cfea0912030502x1532319dy92e6f62868b6ef5e@mail.gmail.com> <00a1d75d$0$26893$c3e8da3@news.astraweb.com> <4dc0cfea0912040205o57897f11u2bc16751784f1d77@mail.gmail.com> Message-ID: Victor Subervi wrote: > I'm not rude To me, asking for help without providing sufficient information, especially when requested, is a form of rudeness. > Think about that and don't be rude. Exactly. Terry Jan Reedy From ross at biostat.ucsf.edu Fri Dec 4 16:38:11 2009 From: ross at biostat.ucsf.edu (Ross Boylan) Date: Fri, 04 Dec 2009 13:38:11 -0800 Subject: question about subprocess and shells Message-ID: <1259962691.10626.20.camel@markov.biostat.ucsf.edu> If one uses subprocess.Popen(args, ..., shell=True, ...) When args finishes execution, does the shell terminate? Either way seems problematic. If it does not terminate, then it seems as if calls like wait and communicate would never return. It also seems the subprocess would never die, and that most of the examples with the shell True would leave processes lying around. If it does terminate, then how can you stuff new commands down the pipe to the subprocesses stdin? Does this module contemplate receiving multiple commands for the shell to execute? I'm also unsure of the semantics of the pipes for the processes standard file handles. Do they need to be closed (judging from the examples, no)? When reads/writes to them return, and what state is the stream in at the time? Thanks for any wisdom you can offer. Ross Boylan From tjreedy at udel.edu Fri Dec 4 16:43:06 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 04 Dec 2009 16:43:06 -0500 Subject: python bijection In-Reply-To: <4B18F685.8050102@egenix.com> References: <7n39ojF3jj6iuU1@mid.individual.net> <12c55890-118d-4655-b6c0-c908c9734a17@a32g2000yqm.googlegroups.com> <85100df7-a8b0-47e9-a854-ba8a8a2f3b98@r31g2000vbi.googlegroups.com> <4B17A960.1090700@egenix.com> <4B17FBFE.8070903@egenix.com> <4B18F685.8050102@egenix.com> Message-ID: M.-A. Lemburg wrote: > Integrating an easy-to-use graph library into the collections > module (and it's C companion) is good idea. > >>> This would have to be written in C, though, >> That's currently in the works, along with database backing. >> We'd welcome any help though... hint, hint... The current thinking among deveopers is that new modules should be written and maintained in Python, which all implementations can use, with speed-critical parts written in C for speed and imported by the Python code. You can write a PEP offering Graphine. To be accepted, there would need to be some evidence that is the best Python graph module avaible and has some community support. I would probably use it more that 90% of the stdlib. Terry Jan Reedy From victorsubervi at gmail.com Fri Dec 4 16:46:46 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Fri, 4 Dec 2009 16:46:46 -0500 Subject: Killing Another Bug In-Reply-To: <7a9c25c20912041246lc94d36fka444b9ca9d5693f@mail.gmail.com> References: <4dc0cfea0912040752m98d81edi87adf659be72283c@mail.gmail.com> <7a9c25c20912041246lc94d36fka444b9ca9d5693f@mail.gmail.com> Message-ID: <4dc0cfea0912041346n685121b8uee936a9313730128@mail.gmail.com> On Fri, Dec 4, 2009 at 3:46 PM, Stephen Hansen wrote: > > On Fri, Dec 4, 2009 at 7:52 AM, Victor Subervi wrote: > >> except: >> > > >> except: >> pass >> > > If you want any hope of fixing the bug, remove both of these. Really -- do > not use bare excepts. > > In the first one, it looks like you're expecting sometimes there to be an > exception: that's okay. If you think an operation will produce one, its okay > to catch it if you know how to handle it. But do NOT use bare excepts. > Catch the actual exception you are expecting-- a KeyError maybe? ValueError? > I don't know, can't tell without knowing what "fn" does. > > In the second-- that bare except with a pass is doing absolutely nothing > but _destroying_ any chance you have of finding out what the bug IS and > fixing the bug. Remove that entire try/except: pass statement. Really. You > absolutely have to do it. The only reason you have not already found and > fixed this bug is that you have done this-- you can't do this and then ask > us to find the bug for you. > > Bare excepts are there for a reason, and there are times to use them. But > those are the exception and not the rule; and the time to use a except: pass > construct is NOT when you're trying to fix a bug. > Right <:-} I changed the "pass" to "raise" and discovered an error I "worked around" while I was trying to solve another problem...then subsequently forgot about this. You know, I'm really a poet and singer/songwriter, unfortunately that doesn't pay the bills. When will I ever learn to think in my left hemisphere like a programmer :-} Thanks, V -------------- next part -------------- An HTML attachment was scrubbed... URL: From lucaberto at libero.it Fri Dec 4 16:50:15 2009 From: lucaberto at libero.it (luca72) Date: Fri, 4 Dec 2009 13:50:15 -0800 (PST) Subject: subprocess kill Message-ID: <5f755846-e79d-444b-b608-86f5823540e8@j19g2000yqk.googlegroups.com> Hello i'm using subprocess in this way: self.luca = subprocess.Popen(['/usr/bin/ dvbtune'+frase_sint],shell=True, stdout=self.f_s_l,stderr=self.f_s_e ) then i kill: self.luca.Kill() but the process is still active and the file self.f_s_l increase it size because the process is not killed. How i can kill the process? Regards Luca From tyler at monkeypox.org Fri Dec 4 16:51:15 2009 From: tyler at monkeypox.org (tyler at monkeypox.org) Date: Fri, 4 Dec 2009 13:51:15 -0800 Subject: Specifying an API for a straeming parser Message-ID: <20091204215114.GC27030@banana.sharlinx.com> Howdy folks, I'm working on a JSON Python module [1] and I'm struggling with an appropriate syntax for dealing with incrementally parsing streams of data as they come in (off a socket or file object). The underlying C-level parsing library that I'm using (Yajl [2]) already uses a callback system internally for handling such things, but I'm worried about: * Ease of use, simplicity * Python method invocation overhead going from C back into Python One of the ideas I've had is to "iterparse" a la: >>> for k, v in yajl.iterloads(fp): ... print ('key, value', k, v) >>> Effectively building a generator for the JSON string coming off of the `fp` object and when generator.next() is called reading more of the stream object. This has some shortcomings however: * For JSON like: '''{"rc":0,"data":}''' the iterloads() function would block for some time when processing the value of the "data" key. * Presumes the developer has prior knowledge of the kind of JSON strings being passed in I've searched around, following this "iterloads" notion, for a tree-generator and I came up with nothing. Any suggestions on how to accomplish iterloads, or perhaps a suggestion for a more sensible syntax for incrementally parsing objects from the stream and passing them up into Python? Cheers, -R. Tyler Ballance -------------------------------------- Jabber: rtyler at jabber.org GitHub: http://github.com/rtyler Twitter: http://twitter.com/agentdero Blog: http://unethicalblogger.com [1] http://github.com/rtyler/py-yajl [2] http://lloyd.github.com/yajl/ -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 198 bytes Desc: not available URL: From lie.1296 at gmail.com Fri Dec 4 17:05:15 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Sat, 05 Dec 2009 09:05:15 +1100 Subject: Insane Problem In-Reply-To: References: <4dc0cfea0912021218g797f782esa2c174923b6ac492@mail.gmail.com> <4B16D739.5080408@mrabarnett.plus.com> <4dc0cfea0912030307j7556eb06j469ccc4e6a29d1ee@mail.gmail.com> <4dc0cfea0912030502x1532319dy92e6f62868b6ef5e@mail.gmail.com> <00a1d75d$0$26893$c3e8da3@news.astraweb.com> <4dc0cfea0912040205o57897f11u2bc16751784f1d77@mail.gmail.com> Message-ID: <4b198814$1@dnews.tpgi.com.au> On 12/5/2009 8:27 AM, Terry Reedy wrote: > Victor Subervi wrote: >> I'm not rude > > To me, asking for help without providing sufficient information, > especially when requested, is a form of rudeness. > >> Think about that and don't be rude. Why does this sounds familiar? http://groups.google.com/group/comp.lang.python/msg/21e80ac383745d88 From callmeclaudius at gmail.com Fri Dec 4 17:11:00 2009 From: callmeclaudius at gmail.com (Joel Davis) Date: Fri, 4 Dec 2009 14:11:00 -0800 (PST) Subject: Partial list comprehensions References: Message-ID: <7d6c5f0d-1192-4e79-9a17-b05ea35f179c@m16g2000yqc.googlegroups.com> On Dec 4, 3:41?pm, Mensanator wrote: > On Dec 4, 2:22?pm, Joel Davis wrote: > > > Is it possible to run a list comprehension over a certain portion of > > the list? My goals is to be able to run the comprehension on the > > innermost elements of the list, but leaving the outermost intact. > > Something like this? > > >>> a > > [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] > > >>> b = [i for i in a[0:5]] > >>> b > [0, 1, 2, 3, 4] > >>> c = [i for i in a if i%2==0] > >>> c > [0, 2, 4, 6, 8] > > Yes, sort of like that but Hansen's code is actually exactly what I was getting at, not sure why he deleted it: >>> a = range(100) >>> a[2:-2] = [str(x) for x in a[2:-2]] >>> a [0, 1, '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '70', '71', '72', '73', '74', '75', '76', '77', '78', '79', '80', '81', '82', '83', '84', '85', '86', '87', '88', '89', '90', '91', '92', '93', '94', '95', '96', '97', 98, 99] From apt.shansen at gmail.com Fri Dec 4 17:21:03 2009 From: apt.shansen at gmail.com (Stephen Hansen) Date: Fri, 4 Dec 2009 14:21:03 -0800 Subject: Partial list comprehensions In-Reply-To: <7d6c5f0d-1192-4e79-9a17-b05ea35f179c@m16g2000yqc.googlegroups.com> References: <7d6c5f0d-1192-4e79-9a17-b05ea35f179c@m16g2000yqc.googlegroups.com> Message-ID: <7a9c25c20912041421n7eb5b51ch61645be96612cd69@mail.gmail.com> On Fri, Dec 4, 2009 at 2:11 PM, Joel Davis wrote: > Yes, sort of like that but Hansen's code is actually exactly what I > was getting at, not sure why he deleted it: Huh? I deleted it? --S -------------- next part -------------- An HTML attachment was scrubbed... URL: From zephjc at gmail.com Fri Dec 4 17:22:28 2009 From: zephjc at gmail.com (zeph) Date: Fri, 4 Dec 2009 14:22:28 -0800 (PST) Subject: Difference between mutex.mutex and threading.Lock References: Message-ID: The mutex class (and module) should not be used, since it is, as you said, deprecated for 3.0. Like the docs say, it "does not require (or imply) threading or multi-tasking, though it could be useful for those purposes." The mutex class' lock() method takes a function and args and if the mutex is unlocked, calls the function with args immediately, or if locked, adds to a queue and waits for it to be unlocked The threading.Lock object is a lock shared between threads. For example, if you have two threads (thread1 and thread2) and thread1 does lock.acquire() and thread 2 calls lock.acquire(), thread2 will block until thread1 calls lock.release(), then thread2 will get a chance to run its critical code section, then call lock.release(). - zeph From kyosohma at gmail.com Fri Dec 4 17:23:34 2009 From: kyosohma at gmail.com (Mike Driscoll) Date: Fri, 4 Dec 2009 14:23:34 -0800 (PST) Subject: subprocess kill References: <5f755846-e79d-444b-b608-86f5823540e8@j19g2000yqk.googlegroups.com> Message-ID: <68cd2042-cd2a-43a8-97ae-2893f181168c@c3g2000yqd.googlegroups.com> On Dec 4, 3:50?pm, luca72 wrote: > Hello i'm using subprocess in this way: > self.luca = subprocess.Popen(['/usr/bin/ > dvbtune'+frase_sint],shell=True, stdout=self.f_s_l,stderr=self.f_s_e ) > > then i kill: > self.luca.Kill() > > but the process is still active and the file self.f_s_l increase it > size because the process is not killed. > > How i can kill the process? > Regards > > Luca See http://lmgtfy.com/?q=python+kill+subprocess+linux When I do that on my machine, the 2nd result has the answer: http://stackoverflow.com/questions/1064335/in-python-2-5-how-do-i-kill-a-subprocess ------------------- Mike Driscoll Blog: http://blog.pythonlibrary.org From pavlovevidence at gmail.com Fri Dec 4 17:41:16 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 4 Dec 2009 14:41:16 -0800 (PST) Subject: python bijection References: <4B17A960.1090700@egenix.com> <4B17FBFE.8070903@egenix.com> <4B18F685.8050102@egenix.com> <4B193610.6050700@mrabarnett.plus.com> <4b196d1f$1@dnews.tpgi.com.au> Message-ID: <5ac80cf9-d0fc-450e-b8bb-ffef91e81f0a@d10g2000yqh.googlegroups.com> On Dec 4, 12:46?pm, geremy condra wrote: more common than full-blown graph package). > Sure, its a tree, which is also a graph. In this case it looks to > me more like a directed acyclic graph than anything, but its > pretty much just semantics since the interface is functionally > equivalent. I'd have to agree with Lie, yes a tree is a graph, but it's simply not an argument that Python community is grasping for graph structures. It's like arguing that the Python community could benefit from a quaternion type, because quaternions are actually heavily used in Python, because a scalar number is a quarternion. Carl Banks (Would be +1 on a good graph implementation... just not because of ElementTree.) From lie.1296 at gmail.com Fri Dec 4 17:53:41 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Sat, 05 Dec 2009 09:53:41 +1100 Subject: question about subprocess and shells In-Reply-To: References: Message-ID: <4b19936e$1@dnews.tpgi.com.au> On 12/5/2009 8:38 AM, Ross Boylan wrote: > If one uses subprocess.Popen(args, ..., shell=True, ...) > > When args finishes execution, does the shell terminate? Either way > seems problematic. > > If it does not terminate, then it seems as if calls like wait and > communicate would never return. It also seems the subprocess would > never die, and that most of the examples with the shell True would leave > processes lying around. No, p.wait() will immediately return, and p.communicate() discards everything new coming. > If it does terminate, then how can you stuff new commands down the pipe > to the subprocesses stdin? start a new shell, of course. > Does this module contemplate receiving multiple commands for the shell > to execute? yes, use several subprocess.Popen() or call a batch/shell script. From tuomas.vesterinen at iki.fi Fri Dec 4 17:57:46 2009 From: tuomas.vesterinen at iki.fi (Tuomas Vesterinen) Date: Sat, 05 Dec 2009 00:57:46 +0200 Subject: Connecting to the users preferred email client In-Reply-To: <5ad6194e-a7b5-4bce-8f82-177447da6649@v30g2000yqm.googlegroups.com> References: <4b18f265$0$26369$9b536df3@news.fv.fi> <5ad6194e-a7b5-4bce-8f82-177447da6649@v30g2000yqm.googlegroups.com> Message-ID: <4b1993e9$0$6279$9b536df3@news.fv.fi> Mike Driscoll wrote: > On Dec 4, 5:28 am, Tuomas Vesterinen wrote: >> If I want to open a html-page from Python code I can say: >> >> >>> import webbrowser >> >>> webbrowser.open('index.html') >> >> Is there a standard way to init an email in users preferred email client >> like Thubderbird, Evolution etc.? >> >> Tuomas Vesterinen > > Check this thread out: > > http://www.megasolutions.net/python/invoke-users-standard-mail-client-64348.aspx > > Basically, the idea is to pass the mailto url to webbrowser. > OK, that's where we are. Thanks. Tuomas Vesterinen > ------------------- > Mike Driscoll > > Blog: http://blog.pythonlibrary.org From lucaberto at libero.it Fri Dec 4 18:03:12 2009 From: lucaberto at libero.it (luca72) Date: Fri, 4 Dec 2009 15:03:12 -0800 (PST) Subject: subprocess kill References: <5f755846-e79d-444b-b608-86f5823540e8@j19g2000yqk.googlegroups.com> <68cd2042-cd2a-43a8-97ae-2893f181168c@c3g2000yqd.googlegroups.com> Message-ID: <011ae123-d777-438c-83b6-f6600c1dfde1@m25g2000yqc.googlegroups.com> On 4 Dic, 23:23, Mike Driscoll wrote: > On Dec 4, 3:50?pm, luca72 wrote: > > > Hello i'm using subprocess in this way: > > self.luca = subprocess.Popen(['/usr/bin/ > > dvbtune'+frase_sint],shell=True, stdout=self.f_s_l,stderr=self.f_s_e ) > > > then i kill: > > self.luca.Kill() > > > but the process is still active and the file self.f_s_l increase it > > size because the process is not killed. > > > How i can kill the process? > > Regards > > > Luca > > Seehttp://lmgtfy.com/?q=python+kill+subprocess+linux > > When I do that on my machine, the 2nd result has the answer: > > http://stackoverflow.com/questions/1064335/in-python-2-5-how-do-i-kil... > > ------------------- > Mike Driscoll > > Blog: ?http://blog.pythonlibrary.org Hello Mike i have also test but they never kill the process the file (stdout=self.f_s_l) increase it's size, haveyou some idea. also if i close the program the process is still active. Regards Luca From fsenkel at lynx.neu.edu Fri Dec 4 18:10:49 2009 From: fsenkel at lynx.neu.edu (monkeyboy) Date: Fri, 4 Dec 2009 15:10:49 -0800 (PST) Subject: Question on class module import Message-ID: <628c7ffa-74b4-439e-bed9-331c6354f280@j24g2000yqa.googlegroups.com> Hello, I want to write a wrapper class around a windows dll. If I put the class in a module "Refprop.py" then import the class where I want to use it, does the whole module get read by the interpreter or just the class code?... For example if I say the following in "Refprop.py" does the code above the class statement get run on an import or should the loadLibrary call be made in the constructor...the code below appears to work OK, I just want to be sure I understand what happens on an import call.... from ctypes import * rp = windll.LoadLibrary("refprop.dll") class refprop(): ''' REFPORP class ''' nc = c_long(1) ierr = c_long(0) ...... From lucaberto at libero.it Fri Dec 4 18:14:26 2009 From: lucaberto at libero.it (luca72) Date: Fri, 4 Dec 2009 15:14:26 -0800 (PST) Subject: subprocess kill References: <5f755846-e79d-444b-b608-86f5823540e8@j19g2000yqk.googlegroups.com> <68cd2042-cd2a-43a8-97ae-2893f181168c@c3g2000yqd.googlegroups.com> <011ae123-d777-438c-83b6-f6600c1dfde1@m25g2000yqc.googlegroups.com> Message-ID: <786e4fb7-1f03-45d5-9be0-55926387283f@s20g2000yqd.googlegroups.com> On 5 Dic, 00:03, luca72 wrote: > On 4 Dic, 23:23, Mike Driscoll wrote: > > > > > On Dec 4, 3:50?pm, luca72 wrote: > > > > Hello i'm using subprocess in this way: > > > self.luca = subprocess.Popen(['/usr/bin/ > > > dvbtune'+frase_sint],shell=True, stdout=self.f_s_l,stderr=self.f_s_e ) > > > > then i kill: > > > self.luca.Kill() > > > > but the process is still active and the file self.f_s_l increase it > > > size because the process is not killed. > > > > How i can kill the process? > > > Regards > > > > Luca > > > Seehttp://lmgtfy.com/?q=python+kill+subprocess+linux > > > When I do that on my machine, the 2nd result has the answer: > > >http://stackoverflow.com/questions/1064335/in-python-2-5-how-do-i-kil... > > > ------------------- > > Mike Driscoll > > > Blog: ?http://blog.pythonlibrary.org > > Hello Mike i have also test but they never kill the process the file > (stdout=self.f_s_l) increase it's size, haveyou some idea. > also if i close the program the process is still active. > > Regards > > Luca i'm able only to kill via shell like kill -9 process pid, Why? From roy at panix.com Fri Dec 4 18:30:03 2009 From: roy at panix.com (Roy Smith) Date: Fri, 04 Dec 2009 18:30:03 -0500 Subject: Difference between mutex.mutex and threading.Lock References: Message-ID: In article , zeph wrote: > The mutex class (and module) should not be used, since it is, as you > said, deprecated for 3.0. Like the docs say, it "does not require (or > imply) threading or multi-tasking, though it could be useful for those > purposes." Over the years, many things about Python have surprised, amused, and on occasion confused, me. I must admit, having a mutex which isn't thread-safe is pretty high up on the list of "does not fit my brain" items :-) From candide at free.invalid Fri Dec 4 18:31:38 2009 From: candide at free.invalid (candide) Date: Sat, 05 Dec 2009 00:31:38 +0100 Subject: Redirecting stdin to a file Message-ID: <4b199bdb$0$24787$426a74cc@news.free.fr> How do I redirect stdin to a text file ? In C, this can be done with the freopen() standard function, for instance FILE *foo = freopen("in.txt", "r", stdin); redirects stdin to the in.txt text file. Does anyone know a freopen() Python equivalent ? Notice that I'm not referring to shell redirection as the following command line shows : $ python myCode.py < in.txt I need to hardcode the redirection inside the python source file. From lucaberto at libero.it Fri Dec 4 18:44:45 2009 From: lucaberto at libero.it (luca72) Date: Fri, 4 Dec 2009 15:44:45 -0800 (PST) Subject: subprocess kill References: <5f755846-e79d-444b-b608-86f5823540e8@j19g2000yqk.googlegroups.com> <68cd2042-cd2a-43a8-97ae-2893f181168c@c3g2000yqd.googlegroups.com> <011ae123-d777-438c-83b6-f6600c1dfde1@m25g2000yqc.googlegroups.com> <786e4fb7-1f03-45d5-9be0-55926387283f@s20g2000yqd.googlegroups.com> Message-ID: On 5 Dic, 00:14, luca72 wrote: > On 5 Dic, 00:03, luca72 wrote: > > > > > On 4 Dic, 23:23, Mike Driscoll wrote: > > > > On Dec 4, 3:50?pm, luca72 wrote: > > > > > Hello i'm using subprocess in this way: > > > > self.luca = subprocess.Popen(['/usr/bin/ > > > > dvbtune'+frase_sint],shell=True, stdout=self.f_s_l,stderr=self.f_s_e ) > > > > > then i kill: > > > > self.luca.Kill() > > > > > but the process is still active and the file self.f_s_l increase it > > > > size because the process is not killed. > > > > > How i can kill the process? > > > > Regards > > > > > Luca > > > > Seehttp://lmgtfy.com/?q=python+kill+subprocess+linux > > > > When I do that on my machine, the 2nd result has the answer: > > > >http://stackoverflow.com/questions/1064335/in-python-2-5-how-do-i-kil... > > > > ------------------- > > > Mike Driscoll > > > > Blog: ?http://blog.pythonlibrary.org > > > Hello Mike i have also test but they never kill the process the file > > (stdout=self.f_s_l) increase it's size, haveyou some idea. > > also if i close the program the process is still active. > > > Regards > > > Luca > > i'm able only to kill via shell like kill -9 process pid, Why? Now the only way to solve the problem is to call a c program that kill the process via subprocess in other case i can't close it, i have also try with subprocess.Popen(['kill -9 dvbtune'] shell=True), but the process is still active Regards Luca From shearichard at gmail.com Fri Dec 4 18:52:52 2009 From: shearichard at gmail.com (northof40) Date: Fri, 4 Dec 2009 15:52:52 -0800 (PST) Subject: How to timeout when waiting for raw_input from user ? Message-ID: <55b6b337-fb8f-46b9-a665-108dd19e1dd8@w19g2000pre.googlegroups.com> Hi - I'm writing a *very* simple program for my kids. It asks the user to give it the answer to a maths question and says "right" or "wrong" They now want a timed version where they would only get so long to respond to the question. I'm thinking of some logic where a raw_input call is executed and then if more than X seconds elapses before the prompt is replied to the process writes a message "Sorry too slow" (or similar). I can't see the wood for the trees here - what's the best way to do this given the rather simple environment it's needed within. Regards richard. From python at mrabarnett.plus.com Fri Dec 4 18:53:42 2009 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 04 Dec 2009 23:53:42 +0000 Subject: Question on class module import In-Reply-To: <628c7ffa-74b4-439e-bed9-331c6354f280@j24g2000yqa.googlegroups.com> References: <628c7ffa-74b4-439e-bed9-331c6354f280@j24g2000yqa.googlegroups.com> Message-ID: <4B19A106.6050606@mrabarnett.plus.com> monkeyboy wrote: > Hello, > > I want to write a wrapper class around a windows dll. If I put the > class in a module "Refprop.py" then import the class where I want to > use it, does the whole module get read by the interpreter or just the > class code?... > [snip] The whole module will be run. In Python 'def' and 'class' aren't declarations, but statements, which have the side-effect of creating the function or class and binding it to a name in the enclosing namespace. If a module contains: print "The start" class Foo(): pass print "The finished" and then you import it, it'll print "The Start", then create a class called "Foo" within the module's namespace, then print "The end". From steve at REMOVE-THIS-cybersource.com.au Fri Dec 4 18:55:23 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 04 Dec 2009 23:55:23 GMT Subject: Question on class module import References: <628c7ffa-74b4-439e-bed9-331c6354f280@j24g2000yqa.googlegroups.com> Message-ID: <00a325f3$0$15659$c3e8da3@news.astraweb.com> On Fri, 04 Dec 2009 15:10:49 -0800, monkeyboy wrote: > Hello, > > I want to write a wrapper class around a windows dll. If I put the class > in a module "Refprop.py" then import the class where I want to use it, > does the whole module get read by the interpreter or just the class > code?... Every import always involves a module. You can't import a class in isolation. Even if you use the form "from module import object", the entire module gets loaded first, in order to access the object. > For example if I say the following in "Refprop.py" does the code above > the class statement get run on an import Only the first time you import it. After that, the module is cached. > or should the loadLibrary call > be made in the constructor... Do you want to call loadLibrary every time you create an instance? Then put it in the constructor. Do you want to call loadLibrary only once? Then leave it were it is. > the code below appears to work OK, I just > want to be sure I understand what happens on an import call.... Python looks in sys.modules to see if the module has already been loaded. If it has, it returns the module. If not, it searches for the module. If it finds it, then it executes the code in the module, caches the module object in sys.modules, and returns. -- Steven From shearichard at gmail.com Fri Dec 4 18:55:30 2009 From: shearichard at gmail.com (northof40) Date: Fri, 4 Dec 2009 15:55:30 -0800 (PST) Subject: How to timeout when waiting for raw_input from user ? References: <55b6b337-fb8f-46b9-a665-108dd19e1dd8@w19g2000pre.googlegroups.com> Message-ID: <06f853b9-275f-4e5f-b040-c8ae3109b0ca@m33g2000pri.googlegroups.com> On Dec 5, 12:52?pm, northof40 wrote: > Hi - I'm writing a *very* simple program for my kids. It asks the user > to give it the answer to a maths question and says "right" or "wrong" > > They now want a timed version where they would only get so long to > respond to the question. > > I'm thinking of some logic where a raw_input call is executed and then > if more than X seconds elapses before the prompt is replied to the > process writes a message "Sorry too slow" (or similar). > > I can't see the wood for the trees here - what's the best way to do > this given the rather simple environment it's needed within. > > Regards > > richard. Sorry I should said that based upon other answers I've seen to similar questions this needs to run on a windows machine (other answers suggest this is more difficult than running on *nix) From lie.1296 at gmail.com Fri Dec 4 18:57:07 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Sat, 05 Dec 2009 10:57:07 +1100 Subject: Redirecting stdin to a file In-Reply-To: <4b199bdb$0$24787$426a74cc@news.free.fr> References: <4b199bdb$0$24787$426a74cc@news.free.fr> Message-ID: <4b19a24c@dnews.tpgi.com.au> On 12/5/2009 10:31 AM, candide wrote: > How do I redirect stdin to a text file ? In C, this can be done with the > freopen() standard function, for instance > > FILE *foo = freopen("in.txt", "r", stdin); > > > redirects stdin to the in.txt text file. Does anyone know a freopen() > Python equivalent ? > > Notice that I'm not referring to shell redirection as the following > command line shows : > > $ python myCode.py< in.txt > > I need to hardcode the redirection inside the python source file. I'm not sure how freopen() works in C, but perhaps you're looking for redirecting sys.stdin: import sys old_stdin = sys.stdin # save it, in case we need to restore it sys.stdin = open('myfile') you can also restore stdin using sys.__stdin__ instead of saving the old one, but in the case you or someone else is redirecting the stdin twice... From python at mrabarnett.plus.com Fri Dec 4 18:59:17 2009 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 04 Dec 2009 23:59:17 +0000 Subject: Redirecting stdin to a file In-Reply-To: <4b199bdb$0$24787$426a74cc@news.free.fr> References: <4b199bdb$0$24787$426a74cc@news.free.fr> Message-ID: <4B19A255.7090109@mrabarnett.plus.com> candide wrote: > How do I redirect stdin to a text file ? In C, this can be done with > the freopen() standard function, for instance > > FILE *foo = freopen("in.txt", "r", stdin); > > > redirects stdin to the in.txt text file. Does anyone know a freopen() > Python equivalent ? > > Notice that I'm not referring to shell redirection as the following > command line shows : > > $ python myCode.py < in.txt > > I need to hardcode the redirection inside the python source file. The standard input is sys.stdin and the standard output is sys.stdout. sys.stdin.close() sys.stdin = open("in.txt", "r") From candide at free.invalid Fri Dec 4 19:29:05 2009 From: candide at free.invalid (candide) Date: Sat, 05 Dec 2009 01:29:05 +0100 Subject: Redirecting stdin to a file In-Reply-To: <4b199bdb$0$24787$426a74cc@news.free.fr> References: <4b199bdb$0$24787$426a74cc@news.free.fr> Message-ID: <4b19a952$0$17825$426a74cc@news.free.fr> @MRAB @Lie Ryan Thanks, it works fine ! From Nikolaus at rath.org Fri Dec 4 19:34:28 2009 From: Nikolaus at rath.org (Nikolaus Rath) Date: Fri, 04 Dec 2009 19:34:28 -0500 Subject: [distutils] Install script under a different name Message-ID: <878wdi5kdn.fsf@vostro.rath.org> Hello, All my Python files have extension .py. However, I would like to install scripts that are meant to be called by the user without the suffix, i.e. the file scripts/doit.py should end up as /usr/bin/doit. Apparently the scripts= option of the setup() function does not support this directly. Is there a clever way to get what I want? Best, -Nikolaus -- ?Time flies like an arrow, fruit flies like a Banana.? PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6 02CF A9AD B7F8 AE4E 425C From lie.1296 at gmail.com Fri Dec 4 19:42:15 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Sat, 05 Dec 2009 11:42:15 +1100 Subject: python bijection In-Reply-To: <5ac80cf9-d0fc-450e-b8bb-ffef91e81f0a@d10g2000yqh.googlegroups.com> References: <4B17A960.1090700@egenix.com> <4B17FBFE.8070903@egenix.com> <4B18F685.8050102@egenix.com> <4B193610.6050700@mrabarnett.plus.com> <4b196d1f$1@dnews.tpgi.com.au> <5ac80cf9-d0fc-450e-b8bb-ffef91e81f0a@d10g2000yqh.googlegroups.com> Message-ID: <4b19ace0$1@dnews.tpgi.com.au> On 12/5/2009 9:41 AM, Carl Banks wrote: > On Dec 4, 12:46 pm, geremy condra wrote: > more common than full-blown graph package). >> Sure, its a tree, which is also a graph. In this case it looks to >> me more like a directed acyclic graph than anything, but its >> pretty much just semantics since the interface is functionally >> equivalent. > > I'd have to agree with Lie, yes a tree is a graph, but it's simply not > an argument that Python community is grasping for graph structures. > It's like arguing that the Python community could benefit from a > quaternion type, because quaternions are actually heavily used in > Python, because a scalar number is a quarternion. > > Carl Banks > > (Would be +1 on a good graph implementation... just not because of > ElementTree.) I think this could be an interpretation of the Zen: Simple is better than complex. Complex is better than complicated. can be read as: List is better than Tree Tree is better than Graph not having Tree and Graph package in the standard library force most people to find List-based solution. And people that know they need graphs will find them in 3rd party modules. I have needed Trees a few times in python, but very rarely a Graph (except for playing around). YMDWV (your mileage definitely will vary). From miki.tebeka at gmail.com Fri Dec 4 20:19:26 2009 From: miki.tebeka at gmail.com (Miki) Date: Fri, 4 Dec 2009 17:19:26 -0800 (PST) Subject: package_data question Message-ID: <525eecc5-000a-4ab4-a4f1-a6048bc8394d@d9g2000prh.googlegroups.com> Hello All, I'm trying to add package_data from outside the package directory. The current project looks like: . |-- __init__.py |-- a | `-- src | `-- py | `-- __init__.py |-- b | `-- src | `-- py | `-- __init__.py |-- c | `-- src | `-- py | `-- __init__.py |-- dlls | `-- c.dll `-- setup.py I'd like to get c.dll inside the p.c directory, so I wrotefrom setuptools import setup setup( name='p', package_dir={ 'p' : '.', 'p.a' : 'a/src/py', 'p.b' : 'b/src/py', 'p.c' : 'c/src/py', }, packages=['p', 'p.a', 'p.b', 'p.c'], include_package_data=True, package_data = { 'p.c' : [ 'dlls/c.dll' ] } ) However c.dll is not copied. build/lib.linux-x86_64-2.6 `-- p |-- __init__.py |-- a | `-- __init__.py |-- b | `-- __init__.py `-- c `-- __init__.py Any idea how to fix this? (Changing the directory structure is not possible - not my project). Thanks, -- Miki From debatem1 at gmail.com Fri Dec 4 20:26:17 2009 From: debatem1 at gmail.com (geremy condra) Date: Fri, 4 Dec 2009 20:26:17 -0500 Subject: python bijection In-Reply-To: <5ac80cf9-d0fc-450e-b8bb-ffef91e81f0a@d10g2000yqh.googlegroups.com> References: <4B17FBFE.8070903@egenix.com> <4B18F685.8050102@egenix.com> <4B193610.6050700@mrabarnett.plus.com> <4b196d1f$1@dnews.tpgi.com.au> <5ac80cf9-d0fc-450e-b8bb-ffef91e81f0a@d10g2000yqh.googlegroups.com> Message-ID: On Fri, Dec 4, 2009 at 5:41 PM, Carl Banks wrote: > On Dec 4, 12:46?pm, geremy condra wrote: > more common than full-blown graph package). >> Sure, its a tree, which is also a graph. In this case it looks to >> me more like a directed acyclic graph than anything, but its >> pretty much just semantics since the interface is functionally >> equivalent. > > I'd have to agree with Lie, yes a tree is a graph, but it's simply not > an argument that Python community is grasping for graph structures. > It's like arguing that the Python community could benefit from a > quaternion type, because quaternions are actually heavily used in > Python, because a scalar number is a quarternion. Fair enough. I suspect that other examples could be provided easily enough that I'm not going to fight over that one. > Carl Banks > > (Would be +1 on a good graph implementation... just not because of > ElementTree.) I'd love it if you'd take a look at Graphine and see whether it would meet the standard for a good graph implementation. Geremy Condra From pavlovevidence at gmail.com Fri Dec 4 20:38:09 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 4 Dec 2009 17:38:09 -0800 (PST) Subject: python bijection References: <4B17A960.1090700@egenix.com> <4B17FBFE.8070903@egenix.com> <4B18F685.8050102@egenix.com> <4B193610.6050700@mrabarnett.plus.com> <4b196d1f$1@dnews.tpgi.com.au> <5ac80cf9-d0fc-450e-b8bb-ffef91e81f0a@d10g2000yqh.googlegroups.com> <4b19ace0$1@dnews.tpgi.com.au> Message-ID: On Dec 4, 4:42?pm, Lie Ryan wrote: > On 12/5/2009 9:41 AM, Carl Banks wrote: > > > > > > > On Dec 4, 12:46 pm, geremy condra ?wrote: > > more common than full-blown graph package). > >> Sure, its a tree, which is also a graph. In this case it looks to > >> me more like a directed acyclic graph than anything, but its > >> pretty much just semantics since the interface is functionally > >> equivalent. > > > I'd have to agree with Lie, yes a tree is a graph, but it's simply not > > an argument that Python community is grasping for graph structures. > > It's like arguing that the Python community could benefit from a > > quaternion type, because quaternions are actually heavily used in > > Python, because a scalar number is a quarternion. > > > Carl Banks > > > (Would be +1 on a good graph implementation... just not because of > > ElementTree.) > > I think this could be an interpretation of the Zen: > > Simple is better than complex. > Complex is better than complicated. > > can be read as: > List is better than Tree > Tree is better than Graph > > not having Tree and Graph package in the standard library force most > people to find List-based solution. And people that know they need > graphs will find them in 3rd party modules. I have needed Trees a few > times in python, but very rarely a Graph (except for playing around). > YMDWV (your mileage definitely will vary). If you want a better example, consider various database schemas that have one-to-one, one-to-many, many-to-one, and many-to-many relationships. I daresay these are very common. All of these can be represented by a non-directed graph. Another common use of directed graphs is for dependency relationships. In practice, a lot of times running things in order of dependency is done by assigning everything a scalar priotity, and executing in order of priority. This can work ok, but it's fragile. If there's a graph type in Python maybe people will be encouraged to handle dependencies explicitly. Carl Banks From debatem1 at gmail.com Fri Dec 4 20:38:33 2009 From: debatem1 at gmail.com (geremy condra) Date: Fri, 4 Dec 2009 20:38:33 -0500 Subject: python bijection In-Reply-To: <4b19ace0$1@dnews.tpgi.com.au> References: <4B18F685.8050102@egenix.com> <4B193610.6050700@mrabarnett.plus.com> <4b196d1f$1@dnews.tpgi.com.au> <5ac80cf9-d0fc-450e-b8bb-ffef91e81f0a@d10g2000yqh.googlegroups.com> <4b19ace0$1@dnews.tpgi.com.au> Message-ID: On Fri, Dec 4, 2009 at 7:42 PM, Lie Ryan wrote: > On 12/5/2009 9:41 AM, Carl Banks wrote: >> >> On Dec 4, 12:46 pm, geremy condra ?wrote: >> more common than full-blown graph package). >>> >>> Sure, its a tree, which is also a graph. In this case it looks to >>> me more like a directed acyclic graph than anything, but its >>> pretty much just semantics since the interface is functionally >>> equivalent. >> >> I'd have to agree with Lie, yes a tree is a graph, but it's simply not >> an argument that Python community is grasping for graph structures. >> It's like arguing that the Python community could benefit from a >> quaternion type, because quaternions are actually heavily used in >> Python, because a scalar number is a quarternion. > >> >> >> Carl Banks >> >> (Would be +1 on a good graph implementation... just not because of >> ElementTree.) > > I think this could be an interpretation of the Zen: > > Simple is better than complex. > Complex is better than complicated. > > can be read as: > List is better than Tree > Tree is better than Graph > > not having Tree and Graph package in the standard library force most people > to find List-based solution. And people that know they need graphs will find > them in 3rd party modules. I have needed Trees a few times in python, but > very rarely a Graph (except for playing around). YMDWV (your mileage > definitely will vary). Where a list will do, use a list- duh. But when you need a graph, you shouldn't have to homebrew an implementation any more than you should have to homebrew an odict or named tuple, both of which are substantially easier to get right than a graph is. Geremy Condra From mkhitrov at gmail.com Fri Dec 4 20:44:45 2009 From: mkhitrov at gmail.com (Maxim Khitrov) Date: Fri, 4 Dec 2009 20:44:45 -0500 Subject: How to timeout when waiting for raw_input from user ? In-Reply-To: <06f853b9-275f-4e5f-b040-c8ae3109b0ca@m33g2000pri.googlegroups.com> References: <55b6b337-fb8f-46b9-a665-108dd19e1dd8@w19g2000pre.googlegroups.com> <06f853b9-275f-4e5f-b040-c8ae3109b0ca@m33g2000pri.googlegroups.com> Message-ID: <26ddd1750912041744j9b8d1b9s5b3716e25fa2d91c@mail.gmail.com> On Fri, Dec 4, 2009 at 6:55 PM, northof40 wrote: > On Dec 5, 12:52?pm, northof40 wrote: >> Hi - I'm writing a *very* simple program for my kids. It asks the user >> to give it the answer to a maths question and says "right" or "wrong" >> >> They now want a timed version where they would only get so long to >> respond to the question. >> >> I'm thinking of some logic where a raw_input call is executed and then >> if more than X seconds elapses before the prompt is replied to the >> process writes a message "Sorry too slow" (or similar). >> >> I can't see the wood for the trees here - what's the best way to do >> this given the rather simple environment it's needed within. >> >> Regards >> >> richard. > > Sorry I should said that based upon other answers I've seen to similar > questions this needs to run on a windows machine (other answers > suggest this is more difficult than running on *nix) > Simplest solution I could come up with. This is indeed much easier on *nix (just use select.select on sys.stdin with a timeout). --- from msvcrt import getch, kbhit, putch from time import sleep, time ans = '' end = time() + 5 print('2 + 2 = ?') while True: while time() < end: if kbhit(): break else: sleep(0.001) else: ans = None break char = getch() if char == '\r': print('') break ans += char putch(char) if ans is None: print('\nSorry too slow') else: try: print('right' if int(ans) == 4 else 'wrong') except: print('not a number') --- - Max From lie.1296 at gmail.com Fri Dec 4 20:47:39 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Sat, 05 Dec 2009 12:47:39 +1100 Subject: python bijection In-Reply-To: References: <4B18F685.8050102@egenix.com> <4B193610.6050700@mrabarnett.plus.com> <4b196d1f$1@dnews.tpgi.com.au> <5ac80cf9-d0fc-450e-b8bb-ffef91e81f0a@d10g2000yqh.googlegroups.com> <4b19ace0$1@dnews.tpgi.com.au> Message-ID: <4b19bc34$1@dnews.tpgi.com.au> On 12/5/2009 12:38 PM, geremy condra wrote: > > Where a list will do, use a list- duh. But when you need a graph, you > shouldn't have to homebrew an implementation any more than you > should have to homebrew an odict or named tuple, both of which > are substantially easier to get right than a graph is. That's what I was trying to say, though I can't find a good way to. The comparison with the Zen was to meant that if List is sufficient (if Simple is sufficient) don't use Tree (don't design a Complex). I wasn't implying to reduce all problem into a list at whatever costs, sorry if my wording appears to imply so... From lie.1296 at gmail.com Fri Dec 4 20:52:21 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Sat, 05 Dec 2009 12:52:21 +1100 Subject: [distutils] Install script under a different name In-Reply-To: <878wdi5kdn.fsf@vostro.rath.org> References: <878wdi5kdn.fsf@vostro.rath.org> Message-ID: <4b19bd4e$1@dnews.tpgi.com.au> On 12/5/2009 11:34 AM, Nikolaus Rath wrote: > Hello, > > All my Python files have extension .py. However, I would like to install > scripts that are meant to be called by the user without the suffix, i.e. > the file scripts/doit.py should end up as /usr/bin/doit. > > Apparently the scripts= option of the setup() function does not support > this directly. Is there a clever way to get what I want? if this is on windows, you should add ".py" to the PATHEXT environment variable. on linux/unix, you need to add the proper #! line to the top of any executable scripts and of course set the executable bit permission (chmod +x scriptname). In linux/unix there is no need to have the .py extension for a file to be recognized as python script (i.e. just remove it). From pavlovevidence at gmail.com Fri Dec 4 21:06:23 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 4 Dec 2009 18:06:23 -0800 (PST) Subject: subprocess kill References: <5f755846-e79d-444b-b608-86f5823540e8@j19g2000yqk.googlegroups.com> <68cd2042-cd2a-43a8-97ae-2893f181168c@c3g2000yqd.googlegroups.com> <011ae123-d777-438c-83b6-f6600c1dfde1@m25g2000yqc.googlegroups.com> <786e4fb7-1f03-45d5-9be0-55926387283f@s20g2000yqd.googlegroups.com> Message-ID: On Dec 4, 3:44?pm, luca72 wrote: > On 5 Dic, 00:14, luca72 wrote: > > > > > > > On 5 Dic, 00:03, luca72 wrote: > > > > On 4 Dic, 23:23, Mike Driscoll wrote: > > > > > On Dec 4, 3:50?pm, luca72 wrote: > > > > > > Hello i'm using subprocess in this way: > > > > > self.luca = subprocess.Popen(['/usr/bin/ > > > > > dvbtune'+frase_sint],shell=True, stdout=self.f_s_l,stderr=self.f_s_e ) > > > > > > then i kill: > > > > > self.luca.Kill() > > > > > > but the process is still active and the file self.f_s_l increase it > > > > > size because the process is not killed. > > > > > > How i can kill the process? > > > > > Regards > > > > > > Luca > > > > > Seehttp://lmgtfy.com/?q=python+kill+subprocess+linux > > > > > When I do that on my machine, the 2nd result has the answer: > > > > >http://stackoverflow.com/questions/1064335/in-python-2-5-how-do-i-kil... > > > > > ------------------- > > > > Mike Driscoll > > > > > Blog: ?http://blog.pythonlibrary.org > > > > Hello Mike i have also test but they never kill the process the file > > > (stdout=self.f_s_l) increase it's size, haveyou some idea. > > > also if i close the program the process is still active. > > > > Regards > > > > Luca > > > i'm able only to kill via shell like kill -9 process pid, Why? > > Now the only way to solve the problem is to call a c program that kill > the process via subprocess in other case i can't close it, i have also > try with > > subprocess.Popen(['kill -9 dvbtune'] shell=True), but the process is > still active This is not working because the kill command does not accept the name of a program. You have to give it a process id. As for your general question, we really can't answer it. There a lot of reasons a process might not die when you try to kill it: it could be trapping and ignoring signals (which is rude but it happens), it could be stuck in a critical section, the program might be threaded and not handling signals well, the program might have forked itself and the original process id has disappeared, etc. We can't read your mind or divine what's running on your computer, so we can't answer your question. We can only suggest things that might be wrong. It's up to you to investigate and/or dig deeper. Carl Banks From mudit.tuli at gmail.com Fri Dec 4 21:39:25 2009 From: mudit.tuli at gmail.com (mudit tuli) Date: Sat, 5 Dec 2009 08:09:25 +0530 Subject: Got a single octet from socket, what to do ? Message-ID: <3d4c0f160912041839q385d0609n67c965d55d7878e2@mail.gmail.com> I am very new to Python and started getting to know socket programming recently. Made a socket server, which receives a "Single Octet"(treated as a single 8-bit integer field) from a client. But I am not sure what to do with this "Single Octet" and how to decode it into a long integer, so that I can make use of it . Any Ideas ? -------------- next part -------------- An HTML attachment was scrubbed... URL: From apt.shansen at gmail.com Fri Dec 4 21:47:55 2009 From: apt.shansen at gmail.com (Stephen Hansen) Date: Fri, 4 Dec 2009 18:47:55 -0800 Subject: Got a single octet from socket, what to do ? In-Reply-To: <3d4c0f160912041839q385d0609n67c965d55d7878e2@mail.gmail.com> References: <3d4c0f160912041839q385d0609n67c965d55d7878e2@mail.gmail.com> Message-ID: <7a9c25c20912041847v6725d7beg5e16dc2041850115@mail.gmail.com> On Fri, Dec 4, 2009 at 6:39 PM, mudit tuli wrote: > I am very new to Python and started getting to know socket programming > recently. > Made a socket server, which receives a "Single Octet"(treated as a single > 8-bit integer field) from a client. > But I am not sure what to do with this "Single Octet" and how to decode it > into a long integer, so that I can make use of it . > Any Ideas ? > > Check out the "struct" module for low-level byte-stream protocols. >>> my_byte = '\x0c' >>> print struct.unpack(" From michaelmossey at yahoo.com Fri Dec 4 22:12:32 2009 From: michaelmossey at yahoo.com (Michael) Date: Fri, 4 Dec 2009 19:12:32 -0800 (PST) Subject: good code to study Message-ID: I want to improve my knowledge of Python (note: I'm still on 2.5 or 2.6) by studying good existing code, especially GUI programs. Any suggestions? I'm looking at the eric source code now, for starters. Thanks, Mike From gnarlodious at gmail.com Fri Dec 4 22:41:06 2009 From: gnarlodious at gmail.com (Gnarlodious) Date: Fri, 4 Dec 2009 19:41:06 -0800 (PST) Subject: Can't print Chinese to HTTP References: <4b13c039$0$7478$9b622d9e@news.freenet.de> <8810fcc1-3e2d-42ce-839c-d03774e02ea1@l13g2000yqb.googlegroups.com> Message-ID: <4e2c0af4-7ef7-43a2-9066-9db5673713e1@p35g2000yqh.googlegroups.com> On Dec 2, 11:58?pm, Dennis Lee Bieber wrote: > ? ? ? ? Have you tried > > ? ? ? ? sys.stdout.write("Content-type:text/plain;charset=utf-8\r\n\r\n") Yes I tried that when it was suggested, to no avail. All I get is "Internal server error". All I can imagine is that there is no "sys.stdout.write" in my Python. No idea why. -- Gnarlie K5ZN From debatem1 at gmail.com Fri Dec 4 22:45:14 2009 From: debatem1 at gmail.com (geremy condra) Date: Fri, 4 Dec 2009 22:45:14 -0500 Subject: python bijection In-Reply-To: References: <4B18F685.8050102@egenix.com> <4B193610.6050700@mrabarnett.plus.com> <4b196d1f$1@dnews.tpgi.com.au> <5ac80cf9-d0fc-450e-b8bb-ffef91e81f0a@d10g2000yqh.googlegroups.com> <4b19ace0$1@dnews.tpgi.com.au> Message-ID: On Fri, Dec 4, 2009 at 8:38 PM, Carl Banks wrote: > On Dec 4, 4:42?pm, Lie Ryan wrote: >> On 12/5/2009 9:41 AM, Carl Banks wrote: >> >> >> >> >> >> > On Dec 4, 12:46 pm, geremy condra ?wrote: >> > more common than full-blown graph package). >> >> Sure, its a tree, which is also a graph. In this case it looks to >> >> me more like a directed acyclic graph than anything, but its >> >> pretty much just semantics since the interface is functionally >> >> equivalent. >> >> > I'd have to agree with Lie, yes a tree is a graph, but it's simply not >> > an argument that Python community is grasping for graph structures. >> > It's like arguing that the Python community could benefit from a >> > quaternion type, because quaternions are actually heavily used in >> > Python, because a scalar number is a quarternion. >> >> > Carl Banks >> >> > (Would be +1 on a good graph implementation... just not because of >> > ElementTree.) >> >> I think this could be an interpretation of the Zen: >> >> Simple is better than complex. >> Complex is better than complicated. >> >> can be read as: >> List is better than Tree >> Tree is better than Graph >> >> not having Tree and Graph package in the standard library force most >> people to find List-based solution. And people that know they need >> graphs will find them in 3rd party modules. I have needed Trees a few >> times in python, but very rarely a Graph (except for playing around). >> YMDWV (your mileage definitely will vary). > > If you want a better example, consider various database schemas that > have one-to-one, one-to-many, many-to-one, and many-to-many > relationships. ?I daresay these are very common. ?All of these can be > represented by a non-directed graph. > > Another common use of directed graphs is for dependency > relationships. ?In practice, a lot of times running things in order of > dependency is done by assigning everything a scalar priotity, and > executing in order of priority. ?This can work ok, but it's fragile. > If there's a graph type in Python maybe people will be encouraged to > handle dependencies explicitly. I actually considered using dependencies as an example on the "graphine for pythonistas"[1] article, but decided to do the maze run instead. In any event, the uses of graphs in general computing are well enough established that I don't really think that's where the majority of the difficulty in coming up with something for the standard library will be- deciding how it should look and behave, especially in terms of scope and target audience, that's going to be the difficult part. Geremy Condra [1]: http://gitorious.org/graphine/pages/GraphineForPythonistas From mudit.tuli at gmail.com Fri Dec 4 22:47:13 2009 From: mudit.tuli at gmail.com (mudit tuli) Date: Sat, 5 Dec 2009 09:17:13 +0530 Subject: Got a single octet from socket, what to do ? In-Reply-To: <7a9c25c20912041847v6725d7beg5e16dc2041850115@mail.gmail.com> References: <3d4c0f160912041839q385d0609n67c965d55d7878e2@mail.gmail.com> <7a9c25c20912041847v6725d7beg5e16dc2041850115@mail.gmail.com> Message-ID: <3d4c0f160912041947i5fdd2171ia365a79e35d6fba7@mail.gmail.com> Stephen, thanks a lot for the reply. This worked for me. I had a look at the struct module earlier but ignored it due to lack of examples, I'll look more into it. Mudit On Sat, Dec 5, 2009 at 8:17 AM, Stephen Hansen wrote: > On Fri, Dec 4, 2009 at 6:39 PM, mudit tuli wrote: > >> I am very new to Python and started getting to know socket programming >> recently. >> Made a socket server, which receives a "Single Octet"(treated as a single >> 8-bit integer field) from a client. >> But I am not sure what to do with this "Single Octet" and how to decode it >> into a long integer, so that I can make use of it . >> Any Ideas ? >> >> > Check out the "struct" module for low-level byte-stream protocols. > > >>> my_byte = '\x0c' > >>> print struct.unpack(" (12, ) > > That would convert the byte string "my_byte" containing a single byte into > a tuple according to the format string passed.. In this case, < specifies > network/big-endian byte order, and "B" specifies that the the message > contains a single unsigned byte as a number. The tuple will thus contain a > 12. > > There's some other more direct ways you can approach the problem, but > struct is really IMHO best and using it early in your protocol is the best > practice. > > --S > -------------- next part -------------- An HTML attachment was scrubbed... URL: From gnarlodious at gmail.com Fri Dec 4 22:57:54 2009 From: gnarlodious at gmail.com (Gnarlodious) Date: Fri, 4 Dec 2009 19:57:54 -0800 (PST) Subject: Can't print Chinese to HTTP References: <4b13c039$0$7478$9b622d9e@news.freenet.de> <8810fcc1-3e2d-42ce-839c-d03774e02ea1@l13g2000yqb.googlegroups.com> <4b153863@dnews.tpgi.com.au> Message-ID: On Dec 1, 3:06?pm, Terry Reedy wrote: > def print(s): return sys.stdout.buffer.write(s.encode('utf-8')) Here is a better solution that lets me send any string to the function: def print(html): return sys.stdout.buffer.write(("Content-type:text/ plain;charset=utf-8\n\n"+html).encode('utf-8')) Why this changed in Python 3 I do not know, nor why it was nowhere to be found on the internet. Can anyone explain it? Anyway, I hope others with this problem can find this solution. -- Gnarlie From michaelmossey at yahoo.com Fri Dec 4 23:04:16 2009 From: michaelmossey at yahoo.com (Michael) Date: Fri, 4 Dec 2009 20:04:16 -0800 (PST) Subject: good code to study Message-ID: <55477b4a-2095-4e52-9f1c-8337d421cc40@j9g2000prh.googlegroups.com> I want to improve my knowledge of Python (note: I'm still on 2.5 or 2.6) by studying good existing code, especially GUI programs. Any suggestions? I'm looking at the eric source code now, for starters. Thanks, Mike From steve at REMOVE-THIS-cybersource.com.au Sat Dec 5 00:18:09 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 05 Dec 2009 05:18:09 GMT Subject: python bijection References: <4B17A960.1090700@egenix.com> <4B17FBFE.8070903@egenix.com> <4B18F685.8050102@egenix.com> <4B193610.6050700@mrabarnett.plus.com> <4b196d1f$1@dnews.tpgi.com.au> <5ac80cf9-d0fc-450e-b8bb-ffef91e81f0a@d10g2000yqh.googlegroups.com> <4b19ace0$1@dnews.tpgi.com.au> Message-ID: <00a37199$0$15659$c3e8da3@news.astraweb.com> On Sat, 05 Dec 2009 11:42:15 +1100, Lie Ryan wrote: > I think this could be an interpretation of the Zen: > > Simple is better than complex. > Complex is better than complicated. > > can be read as: > List is better than Tree Because O(N) searches are better than O(log N) searches. Not. How about "The right tool for the right job"? > Tree is better than Graph > > not having Tree and Graph package in the standard library force most > people to find List-based solution. If you have to be *forced* to use a list-based solution, that's a good sign that a list is *not* the right tool for the job. -- Steven From no.email at nospam.invalid Sat Dec 5 00:23:23 2009 From: no.email at nospam.invalid (Paul Rubin) Date: Fri, 04 Dec 2009 21:23:23 -0800 Subject: How to timeout when waiting for raw_input from user ? References: <55b6b337-fb8f-46b9-a665-108dd19e1dd8@w19g2000pre.googlegroups.com> Message-ID: <7xhbs6xad0.fsf@ruckus.brouhaha.com> northof40 writes: > I'm thinking of some logic where a raw_input call is executed and then > if more than X seconds elapses before the prompt is replied to the > process writes a message "Sorry too slow" (or similar). The simplest way to do this is with the alarm function and a signal handler. See the docs for the signal module. From sivaits4u at gmail.com Sat Dec 5 00:37:48 2009 From: sivaits4u at gmail.com (Siva B) Date: Sat, 5 Dec 2009 11:07:48 +0530 Subject: read from standard input Message-ID: <581ce2790912042137m259a4ad3q4cf8a7a08294fccf@mail.gmail.com> Hi all, I wrote a program to read some data through standard input and write in a file. the following code works fine in linux. but its giving ArgumentError in windows. Code: import sys orig_source = sys.stdin.read() file=open('data.txt','w') file.write(orig_source) file.close() please post some solution . and what is the command in windows for EOF (like Cntrl D in linux) thanks in advance Siva -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Sat Dec 5 01:24:29 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Fri, 4 Dec 2009 22:24:29 -0800 Subject: read from standard input In-Reply-To: <581ce2790912042137m259a4ad3q4cf8a7a08294fccf@mail.gmail.com> References: <581ce2790912042137m259a4ad3q4cf8a7a08294fccf@mail.gmail.com> Message-ID: <50697b2c0912042224v71d05d26rc50c7b86e5f374b3@mail.gmail.com> On Fri, Dec 4, 2009 at 9:37 PM, Siva B wrote: > Hi all, > > I wrote a program to read some data through standard input and write in a > file. > the following code works fine in linux. > but its giving ArgumentError in windows. There's no such error in Python; you're thinking of Ruby. Unless you give the /actual/ error (with message) and full traceback, there's not much we can do to help you besides just guess. > file=open('data.txt','w') Don't use `file` as a variable name, you're shadowing the built-in type. > and what is the command in windows for EOF (like Cntrl D in linux) http://tinyurl.com/yggsby3 The *very first result* has the answer in its 6th sentence. Cheers, Chris -- http://blog.rebertia.com From sivaits4u at gmail.com Sat Dec 5 02:13:24 2009 From: sivaits4u at gmail.com (Siva B) Date: Sat, 5 Dec 2009 12:43:24 +0530 Subject: read from standard input In-Reply-To: <50697b2c0912042224v71d05d26rc50c7b86e5f374b3@mail.gmail.com> References: <581ce2790912042137m259a4ad3q4cf8a7a08294fccf@mail.gmail.com> <50697b2c0912042224v71d05d26rc50c7b86e5f374b3@mail.gmail.com> Message-ID: <581ce2790912042313k5bf48810j836784c99d802fac@mail.gmail.com> Hi Chris, Thanks for you reply. The error log is here for my above program in windows: Traceback (most recent call last): File "C:\Documents and Settings\user\Desktop\t1.py", line 3, in orig_source = sys.stdin.read() AttributeError: read Regards, Siva On Sat, Dec 5, 2009 at 11:54 AM, Chris Rebert wrote: > On Fri, Dec 4, 2009 at 9:37 PM, Siva B wrote: > > Hi all, > > > > I wrote a program to read some data through standard input and write in a > > file. > > the following code works fine in linux. > > but its giving ArgumentError in windows. > > There's no such error in Python; you're thinking of Ruby. > Unless you give the /actual/ error (with message) and full traceback, > there's not much we can do to help you besides just guess. > > > > file=open('data.txt','w') > > Don't use `file` as a variable name, you're shadowing the built-in type. > > > and what is the command in windows for EOF (like Cntrl D in linux) > > http://tinyurl.com/yggsby3 > The *very first result* has the answer in its 6th sentence. > > Cheers, > Chris > -- > http://blog.rebertia.com > -------------- next part -------------- An HTML attachment was scrubbed... URL: From sivaits4u at gmail.com Sat Dec 5 02:19:41 2009 From: sivaits4u at gmail.com (Siva B) Date: Sat, 5 Dec 2009 12:49:41 +0530 Subject: editor with autocompletion In-Reply-To: References: <581ce2790912032209m2f060e9agb2a7ada6dfb1f8c9@mail.gmail.com> Message-ID: <581ce2790912042319nfaa4b88oaeaa0a70cc50fef9@mail.gmail.com> Hi All, Thanks for your reply. What I want is An Editor which can support Dynamic Languages with Autocomplete. I have my own language with some file extension (for ex: *.fs ) I can add few keywords to editor, it should support autocomplte. thats what my idea. plz send me pointers (good if it is open source.) I have seen Komodo edit but it looks too big any help plz. Regards, Siva On Fri, Dec 4, 2009 at 8:04 PM, Gerhard H?ring wrote: > Siva B wrote: > > Hi friends, > > > > I am writing a new language. > > So I want an editor with auto complete. > > I there any such tool in Python ?(not only in python any other) > > I want it for my new lang > > IDLE, the Integrated Development Environment included with your Python > installation nowadays has autocompletion (I just check with the one > included in Python 2.6). > > -- Gerhard > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Sat Dec 5 02:27:10 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Fri, 4 Dec 2009 23:27:10 -0800 Subject: read from standard input In-Reply-To: <581ce2790912042313k5bf48810j836784c99d802fac@mail.gmail.com> References: <581ce2790912042137m259a4ad3q4cf8a7a08294fccf@mail.gmail.com> <50697b2c0912042224v71d05d26rc50c7b86e5f374b3@mail.gmail.com> <581ce2790912042313k5bf48810j836784c99d802fac@mail.gmail.com> Message-ID: <50697b2c0912042327m4f2330fdr2101cf4d8ae29479@mail.gmail.com> > On Sat, Dec 5, 2009 at 11:54 AM, Chris Rebert wrote: >> >> On Fri, Dec 4, 2009 at 9:37 PM, Siva B wrote: >> > Hi all, >> > >> > I wrote a program to read some data through standard input and write in >> > a >> > file. >> > the following code works fine in linux. >> > but its giving ArgumentError in windows. >> >> There's no such error in Python; you're thinking of Ruby. >> Unless you give the /actual/ error (with message) and full traceback, >> there's not much we can do to help you besides just guess. >> >> >> > file=open('data.txt','w') >> >> Don't use `file` as a variable name, you're shadowing the built-in type. >> >> > and what is the command in windows for EOF (like Cntrl D in linux) >> >> http://tinyurl.com/yggsby3 >> The *very first result* has the answer in its 6th sentence. On Fri, Dec 4, 2009 at 11:13 PM, Siva B wrote: > Hi Chris, > Thanks for you reply. > The error log is here for my above program in windows: > > Traceback (most recent call last): > File "C:\Documents and Settings\user\Desktop\t1.py", line 3, in > orig_source = sys.stdin.read() > AttributeError: read Okay, that Shouldn't Be Happening (tm). Add the following before line 3 and post the output: print type(sys.stdin), sys.stdin And while we're at it, what version of Python are your running? Cheers, Chris -- http://blog.rebertia.com From python at rcn.com Sat Dec 5 03:32:25 2009 From: python at rcn.com (Raymond Hettinger) Date: Sat, 5 Dec 2009 00:32:25 -0800 (PST) Subject: python bijection References: <5a99def7-e182-4782-9054-f1035affa34d@x5g2000prf.googlegroups.com> <7n39ojF3jj6iuU1@mid.individual.net> <12c55890-118d-4655-b6c0-c908c9734a17@a32g2000yqm.googlegroups.com> <85100df7-a8b0-47e9-a854-ba8a8a2f3b98@r31g2000vbi.googlegroups.com> <39a95e47-3851-42ae-892c-82b07e0dc25b@u7g2000yqm.googlegroups.com> Message-ID: <465be7ec-9dbe-4eaa-8af5-6501c93ecd47@b25g2000prb.googlegroups.com> [Me] > > * we've already got one (actually two). > > ? The two dictionary approach... [Francis Carr] > Solutions such as bidict just automate the two-dict approach. They do so at the expense of implementing a new API to support it and at the expense with having non-obvious behaviors (i.e. how it handles collapsing two records into one, which exceptions can be raised, how the bijection invariants are maintained, which of the two symmetric accessors is the primary, etc). This is not a cost-free choice of simply "automating something". IMO, "just automating" something that is already clear is not necessarily a net win. Each new class has a learning curve and it is sometimes simpler to use the basic dictionary API instead of inventing a new one. I would *much* rather debug code written by someone using two dictionaries than code using any of the APIs discussed so far -- all of those hide important design decisions behind a layer of abstraction. The API must be easy to learn and remember (including all of it quirks); otherwise, it is a net mental tax on the programmer and code reviewers. Also, I've presented examples of usability problems with APIs that do not require the user to specify names for the two directions. It is too easy to make mistakes that are hard to see. Which is correct, phonelist['raymond'] or phonelist[raymonds_phonenumber]? There is no way to tell without looking back at the bijection specification. The API must be self-documenting. An API that is error-prone is worse than having no bijection class at all. Further, the API needs to be consistent with the rest of the language (no abusing syntax with the likes of phonelist[:number]). Unfortunately, Mark Lemburg has thrown gas on this fire, so the conversation will likely continue for a while. If so, it would be helpful if the conversation centered around real-world examples of code that would be improved with a bijection class. In my experience, there are examples where bijections arise in programs but it doesn't happen often enough to warrant a new class for it. In cases where it does arise, people should try-out the proposed APIs to see if in-fact the code is made more clear or whether simple work is just being hidden behind a layer of abstraction. For grins, insert an error into the code (conflating the primary key with the secondary key) and see if the error is self-evident or whether it is hidden by the new API. Also, test the API for flexibility (how well can it adapt to injections and surjections, can it handle use cases with default values, is there a meaningful interpretation of dict.fromkeys() in a bijection, can a user specify how to handle violations of the bijection invariants by raising exceptions, supplying default values, collapsing records, etc.) Even if a proposed API passes those smell tests, demonstrates the required flexibility, is easy to learn and use, is not error-prone, and actually improves real-world use cases, it is my opinion that a recipe for it will not garner a fan club and that it will have limited uptake. ISTM that it is more fun to write classes like this than it is to actually use them. Raymond P.S. It also makes sense to look at other mature languages to see whether they ever find a need to include a bijection class in their standard library or builtin collections. If Smalltalk, Java, Forth, Go, Io, Haskell and C++ couldn't be sold on it, perhaps the buyer should beware. If some language is found that did include a bijection class, then do a Google code search to see how it fared in the real- world. My bet is that it either wasn't used much or that it actually make code worse by making errors harder to spot. From pavlovevidence at gmail.com Sat Dec 5 04:13:37 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 5 Dec 2009 01:13:37 -0800 (PST) Subject: ctypes pointer from offset into array? Message-ID: Is there a way to get the pointer to an array offset in ctypes. Example, say I define an array like so: xfer = (c_char*bufsize)() How would I get a pointer to then nth byte (equivalient of &xfer[n])? I guess I would have expected xfer+n to work, but it doesn't. Carl Banks From python at rcn.com Sat Dec 5 04:14:55 2009 From: python at rcn.com (Raymond Hettinger) Date: Sat, 5 Dec 2009 01:14:55 -0800 (PST) Subject: python bijection References: <5a99def7-e182-4782-9054-f1035affa34d@x5g2000prf.googlegroups.com> <7n39ojF3jj6iuU1@mid.individual.net> <12c55890-118d-4655-b6c0-c908c9734a17@a32g2000yqm.googlegroups.com> <85100df7-a8b0-47e9-a854-ba8a8a2f3b98@r31g2000vbi.googlegroups.com> <39a95e47-3851-42ae-892c-82b07e0dc25b@u7g2000yqm.googlegroups.com> Message-ID: <776992be-575e-41bc-aca8-df9c4df0ae22@y10g2000prg.googlegroups.com> > > ? ...sqlite3 provides another way... > > In many many cases, using a dB (even a lightweight such as sqlite3) is > swatting the fly with a sledgehammer :-) I'm sure it seems that way, but look at the generic description of the problem: "I have a list of n-ary tuples with named fields and would like to be able to retrieve a tuple using any of m-fields as a lookup key (where 2 <= m <= n). Also, I would like to enforce the constraint that those m-fields are all unique keys." That pretty much sounds like a typical database problem featuring a single table with multiple indexes. One can wish-away the complexity of a database but you will end-up re-inventing an in-memory, one-table version of database. =============== phonelist =============== name idnumber ---- -------- ray 1234 josh 5423 carl 8674 tery 5409 greg 3402 mark 2108 tasks ----- list names list idnumbers find idnumber=2108 find name=greg del name=tery update idnumber=4321 where name=ray list sorted by name list sorted by idnumber reversed is name=john in phonelist Now, extend the table to make it a trijection (three unique keys), perhaps a social security number. Now, extend the table to add a field that isn't unique (not a key field), perhaps a person's favorite language. Oh wait, you can't do that with a bijection API. Now, forget the in-memory part and make it persistent on disk. Now, relate the entries to another dictionary of tuples (i.e. another table with foreign-key). Too bad a DB wasn't used to solve a DB problem. Raymond From sivaits4u at gmail.com Sat Dec 5 04:20:12 2009 From: sivaits4u at gmail.com (Siva B) Date: Sat, 5 Dec 2009 14:50:12 +0530 Subject: read from standard input In-Reply-To: <50697b2c0912042327m4f2330fdr2101cf4d8ae29479@mail.gmail.com> References: <581ce2790912042137m259a4ad3q4cf8a7a08294fccf@mail.gmail.com> <50697b2c0912042224v71d05d26rc50c7b86e5f374b3@mail.gmail.com> <581ce2790912042313k5bf48810j836784c99d802fac@mail.gmail.com> <50697b2c0912042327m4f2330fdr2101cf4d8ae29479@mail.gmail.com> Message-ID: <581ce2790912050120v694b4acdw63742240498b4e93@mail.gmail.com> for the line of code you given, print type(sys.stdin), sys.stdin the output is: there is no change. I have tried it in python2.6 on windows platform. Thanks, Siva On Sat, Dec 5, 2009 at 12:57 PM, Chris Rebert wrote: > > On Sat, Dec 5, 2009 at 11:54 AM, Chris Rebert wrote: > >> > >> On Fri, Dec 4, 2009 at 9:37 PM, Siva B wrote: > >> > Hi all, > >> > > >> > I wrote a program to read some data through standard input and write > in > >> > a > >> > file. > >> > the following code works fine in linux. > >> > but its giving ArgumentError in windows. > >> > >> There's no such error in Python; you're thinking of Ruby. > >> Unless you give the /actual/ error (with message) and full traceback, > >> there's not much we can do to help you besides just guess. > >> > >> > >> > file=open('data.txt','w') > >> > >> Don't use `file` as a variable name, you're shadowing the built-in type. > >> > >> > and what is the command in windows for EOF (like Cntrl D in linux) > >> > >> http://tinyurl.com/yggsby3 > >> The *very first result* has the answer in its 6th sentence. > > On Fri, Dec 4, 2009 at 11:13 PM, Siva B wrote: > > Hi Chris, > > Thanks for you reply. > > The error log is here for my above program in windows: > > > > Traceback (most recent call last): > > File "C:\Documents and Settings\user\Desktop\t1.py", line 3, in > > > orig_source = sys.stdin.read() > > AttributeError: read > > Okay, that Shouldn't Be Happening (tm). Add the following before line > 3 and post the output: > > print type(sys.stdin), sys.stdin > > And while we're at it, what version of Python are your running? > > Cheers, > Chris > -- > http://blog.rebertia.com > -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at rcn.com Sat Dec 5 04:42:55 2009 From: python at rcn.com (Raymond Hettinger) Date: Sat, 5 Dec 2009 01:42:55 -0800 (PST) Subject: Are routine objects guaranteed mutable & with dictionary? References: Message-ID: <4a2a7fdf-99d4-4219-a56c-7cd9146b3c85@f20g2000prn.googlegroups.com> On Dec 4, 2:03?am, "Alf P. Steinbach" wrote: > Is this guaranteed to work in Python 3.x? > > ?>>> def foo(): pass > ... > ?>>> foo.blah = 222 > ?>>> foo.blah > 222 Yes, function attributes are guaranteed to be writable: http://www.python.org/dev/peps/pep-0232/ Raymond From floris.bruynooghe at gmail.com Sat Dec 5 04:52:40 2009 From: floris.bruynooghe at gmail.com (Floris Bruynooghe) Date: Sat, 5 Dec 2009 01:52:40 -0800 (PST) Subject: Install script under a different name References: <878wdi5kdn.fsf@vostro.rath.org> <4b19bd4e$1@dnews.tpgi.com.au> Message-ID: <79c29649-28a6-4b8e-b467-5edb6c785b90@m16g2000yqc.googlegroups.com> On Dec 5, 1:52?am, Lie Ryan wrote: > on linux/unix, you need to add the proper #! line to the top of any > executable scripts and of course set the executable bit permission > (chmod +x scriptname). In linux/unix there is no need to have the .py > extension for a file to be recognized as python script (i.e. just remove > it). The #! line will even get replaced by the interpreter used during installation, so you can safely write "#!/usr/bin/env python" in your development copy and get "#!/usr/bin/python" when users install it. From shearichard at gmail.com Sat Dec 5 05:01:33 2009 From: shearichard at gmail.com (northof40) Date: Sat, 5 Dec 2009 02:01:33 -0800 (PST) Subject: How to timeout when waiting for raw_input from user ? References: <55b6b337-fb8f-46b9-a665-108dd19e1dd8@w19g2000pre.googlegroups.com> <06f853b9-275f-4e5f-b040-c8ae3109b0ca@m33g2000pri.googlegroups.com> Message-ID: On Dec 5, 2:44?pm, Maxim Khitrov wrote: > On Fri, Dec 4, 2009 at 6:55 PM, northof40 wrote: > > On Dec 5, 12:52?pm, northof40 wrote: > >> Hi - I'm writing a *very* simple program for my kids. It asks the user > >> to give it the answer to a maths question and says "right" or "wrong" > > >> They now want a timed version where they would only get so long to > >> respond to the question. > > >> I'm thinking of some logic where a raw_input call is executed and then > >> if more than X seconds elapses before the prompt is replied to the > >> process writes a message "Sorry too slow" (or similar). > > >> I can't see the wood for the trees here - what's the best way to do > >> this given the rather simple environment it's needed within. > > >> Regards > > >> richard. > > > Sorry I should said that based upon other answers I've seen to similar > > questions this needs to run on a windows machine (other answers > > suggest this is more difficult than running on *nix) > > Simplest solution I could come up with. This is indeed much easier on > *nix (just use select.select on sys.stdin with a timeout). > > --- > from msvcrt import getch, kbhit, putch > from time import sleep, time > > ans = '' > end = time() + 5 > > print('2 + 2 = ?') > > while True: > ? ? ? ? while time() < end: > ? ? ? ? ? ? ? ? if kbhit(): > ? ? ? ? ? ? ? ? ? ? ? ? break > ? ? ? ? ? ? ? ? else: > ? ? ? ? ? ? ? ? ? ? ? ? sleep(0.001) > ? ? ? ? else: > ? ? ? ? ? ? ? ? ans = None > ? ? ? ? ? ? ? ? break > > ? ? ? ? char = getch() > ? ? ? ? if char == '\r': > ? ? ? ? ? ? ? ? print('') > ? ? ? ? ? ? ? ? break > ? ? ? ? ans += char > ? ? ? ? putch(char) > > if ans is None: > ? ? ? ? print('\nSorry too slow') > else: > ? ? ? ? try: > ? ? ? ? ? ? ? ? print('right' if int(ans) == 4 else 'wrong') > ? ? ? ? except: > ? ? ? ? ? ? ? ? print('not a number') > --- > > - Max That's really great - thanks. I've never looked at the whole msvcrt module before - it looks like it could be useful ... at least for windows programmes. Thanks again. R. From shearichard at gmail.com Sat Dec 5 05:04:13 2009 From: shearichard at gmail.com (northof40) Date: Sat, 5 Dec 2009 02:04:13 -0800 (PST) Subject: How to timeout when waiting for raw_input from user ? References: <55b6b337-fb8f-46b9-a665-108dd19e1dd8@w19g2000pre.googlegroups.com> <7xhbs6xad0.fsf@ruckus.brouhaha.com> Message-ID: <465b7ba8-d2cd-4962-ad17-e22a75383e21@x25g2000prf.googlegroups.com> On Dec 5, 6:23?pm, Paul Rubin wrote: > northof40 writes: > > I'm thinking of some logic where a raw_input call is executed and then > > if more than X seconds elapses before the prompt is replied to the > > process writes a message "Sorry too slow" (or similar). > > The simplest way to do this is with the alarm function and a signal > handler. ?See the docs for the signal module. Hi Paul - Thanks for your reply. Unfortunately it seems like the bit of the signal module I would need for this is not implemented for windows (AttributeError: 'module' object has no attribute 'SIGALRM'). Still no matter when I asked the question I couldn't even figure out what module might provide this functionality for any platform so it was useful knowledge for the future. Thanks again. regards Richard. From floris.bruynooghe at gmail.com Sat Dec 5 05:09:58 2009 From: floris.bruynooghe at gmail.com (Floris Bruynooghe) Date: Sat, 5 Dec 2009 02:09:58 -0800 (PST) Subject: question about subprocess and shells References: Message-ID: <3de61866-a00b-4453-afb6-1f285af83e9a@b2g2000yqi.googlegroups.com> On Dec 4, 9:38?pm, Ross Boylan wrote: > If one uses subprocess.Popen(args, ..., shell=True, ...) > > When args finishes execution, does the shell terminate? ?Either way > seems problematic. Essentially this is executing "/bin/sh args" so if you're unsure as to the behaviour just try it on your command line. Basically once the pipeline in "args" had finished the shell has nothing more to do and will return itself (and the return code for the shell depends on the return code of the pipeline executed which is normally the return code of the last process executed). Of course when I say "pipeline" it could also be a single command or a list or any valid shell. Regards Floris From lucaberto at libero.it Sat Dec 5 05:13:41 2009 From: lucaberto at libero.it (luca72) Date: Sat, 5 Dec 2009 02:13:41 -0800 (PST) Subject: subprocess kill References: <5f755846-e79d-444b-b608-86f5823540e8@j19g2000yqk.googlegroups.com> <68cd2042-cd2a-43a8-97ae-2893f181168c@c3g2000yqd.googlegroups.com> <011ae123-d777-438c-83b6-f6600c1dfde1@m25g2000yqc.googlegroups.com> <786e4fb7-1f03-45d5-9be0-55926387283f@s20g2000yqd.googlegroups.com> Message-ID: On 5 Dic, 03:06, Carl Banks wrote: > On Dec 4, 3:44?pm, luca72 wrote: > > > > > On 5 Dic, 00:14, luca72 wrote: > > > > On 5 Dic, 00:03, luca72 wrote: > > > > > On 4 Dic, 23:23, Mike Driscoll wrote: > > > > > > On Dec 4, 3:50?pm, luca72 wrote: > > > > > > > Hello i'm using subprocess in this way: > > > > > > self.luca = subprocess.Popen(['/usr/bin/ > > > > > > dvbtune'+frase_sint],shell=True, stdout=self.f_s_l,stderr=self.f_s_e ) > > > > > > > then i kill: > > > > > > self.luca.Kill() > > > > > > > but the process is still active and the file self.f_s_l increase it > > > > > > size because the process is not killed. > > > > > > > How i can kill the process? > > > > > > Regards > > > > > > > Luca > > > > > > Seehttp://lmgtfy.com/?q=python+kill+subprocess+linux > > > > > > When I do that on my machine, the 2nd result has the answer: > > > > > >http://stackoverflow.com/questions/1064335/in-python-2-5-how-do-i-kil... > > > > > > ------------------- > > > > > Mike Driscoll > > > > > > Blog: ?http://blog.pythonlibrary.org > > > > > Hello Mike i have also test but they never kill the process the file > > > > (stdout=self.f_s_l) increase it's size, haveyou some idea. > > > > also if i close the program the process is still active. > > > > > Regards > > > > > Luca > > > > i'm able only to kill via shell like kill -9 process pid, Why? > > > Now the only way to solve the problem is to call a c program that kill > > the process via subprocess in other case i can't close it, i have also > > try with > > > subprocess.Popen(['kill -9 dvbtune'] shell=True), but the process is > > still active > > This is not working because the kill command does not accept the name > of a program. ?You have to give it a process id. > > As for your general question, we really can't answer it. ?There a lot > of reasons a process might not die when you try to kill it: it could > be trapping and ignoring signals (which is rude but it happens), it > could be stuck in a critical section, the program might be threaded > and not handling signals well, the program might have forked itself > and the original process id has disappeared, etc. ?We can't read your > mind or divine what's running on your computer, so we can't answer > your question. ?We can only suggest things that might be wrong. ?It's > up to you to investigate and/or dig deeper. > > Carl Banks The firs thing that i have tested is with the process id get by Popen.pid ,but it don't works. Thanks From rami.chowdhury at gmail.com Sat Dec 5 05:14:09 2009 From: rami.chowdhury at gmail.com (Rami Chowdhury) Date: Sat, 5 Dec 2009 02:14:09 -0800 Subject: read from standard input In-Reply-To: <581ce2790912050120v694b4acdw63742240498b4e93@mail.gmail.com> References: <581ce2790912042137m259a4ad3q4cf8a7a08294fccf@mail.gmail.com> <50697b2c0912042327m4f2330fdr2101cf4d8ae29479@mail.gmail.com> <581ce2790912050120v694b4acdw63742240498b4e93@mail.gmail.com> Message-ID: <200912050214.09673.rami.chowdhury@gmail.com> On Saturday 05 December 2009 01:20:12 Siva B wrote: > for the line of code you given, > > print type(sys.stdin), sys.stdin > > the output is: > 0x00BE8090> > > there is no change. > I have tried it in python2.6 on windows platform. > > Thanks, > Siva > How did you run this on Linux? How did you run it on Windows? It looks like you're running it from within IDLE. I don't know IDLE at all, and don't know how to pass data to its standard input -- can you let us know what arguments you're using? I've tried sys.stdin.read() from inside IDLE on Linux, and it gives me the same error. ---- Rami Chowdhury "Any sufficiently advanced incompetence is indistinguishable from malice." -- Grey's Law 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) From alfps at start.no Sat Dec 5 05:26:34 2009 From: alfps at start.no (Alf P. Steinbach) Date: Sat, 05 Dec 2009 11:26:34 +0100 Subject: Are routine objects guaranteed mutable & with dictionary? In-Reply-To: <4a2a7fdf-99d4-4219-a56c-7cd9146b3c85@f20g2000prn.googlegroups.com> References: <4a2a7fdf-99d4-4219-a56c-7cd9146b3c85@f20g2000prn.googlegroups.com> Message-ID: * Raymond Hettinger: > On Dec 4, 2:03 am, "Alf P. Steinbach" wrote: >> Is this guaranteed to work in Python 3.x? >> >> >>> def foo(): pass >> ... >> >>> foo.blah = 222 >> >>> foo.blah >> 222 > > Yes, function attributes are guaranteed to be writable: > http://www.python.org/dev/peps/pep-0232/ Thanks to all, especially you and Terry. To quote a suspected bot once rampaging the Microsoft groups, "my question has been answered!" :-) Thread morphing: Regarding my terminology, "routine" instead "function" that everybody except you remarked on, it is of course intentional. After all, my main language is C++. And nobody (well, very few) would accuse me of not knowing my C++. :-) I use the term "routine" because I think the terminology influences what we can easily think of and what we therefore tend to use and/or discuss. In that respect I think people need to be educated to use more language independent, or Eiffel-like, or just historically original, terminology, because * "function" is misleading in itself (due to the hijacking of this term in mathematics), and * it gets worse when you can't reasonably talk about "co-functions" or "function-like functions". :-) The devolution of terminology has been so severe that now even the Wikipedia article on this subject confounds the general concept of "routine" with the far more specialized term "sub-routine", which is just one kind of routine. It is of course OK with me that there is a default meaning, and that there are several different context dependendent meanings. I'm just mentioning this as an example that the terminology effectively constrains one's thinking, to the degree that even a moderately long encyclopedia article on the subject fails to mention or focus on the important aspects. Perhaps modern programmers should be forced to study Donald Knuth's TAOCP. Or something. Cheers, - Alf From michaelmossey at yahoo.com Sat Dec 5 05:27:54 2009 From: michaelmossey at yahoo.com (Michael) Date: Sat, 5 Dec 2009 02:27:54 -0800 (PST) Subject: can someone explain 'super' to me? Message-ID: >From the docs about the built-in function super: ---------------------------- super( type[, object-or-type]) Return the superclass of type. If the second argument is omitted the super object returned is unbound. If the second argument is an object, isinstance(obj, type) must be true. If the second argument is a type, issubclass(type2, type) must be true. super() only works for new-style classes. A typical use for calling a cooperative superclass method is: class C(B): def meth(self, arg): super(C, self).meth(arg) Note that super is implemented as part of the binding process for explicit dotted attribute lookups such as "super(C, self).__getitem__ (name)". Accordingly, super is undefined for implicit lookups using statements or operators such as "super(C, self)[name]". New in version 2.2. -------------------------------- It seems like it can return either a class or an instance of a class. Like super( C, self) is like casting self as superclass C. However if you omit the second argument entirely you get a class. The former is considered a "bound" object. I'm really not clear on the idea of "binding" in Python. any pointers appreciated. -Mike From lie.1296 at gmail.com Sat Dec 5 05:54:51 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Sat, 05 Dec 2009 21:54:51 +1100 Subject: Can't print Chinese to HTTP In-Reply-To: References: <4b13c039$0$7478$9b622d9e@news.freenet.de> <8810fcc1-3e2d-42ce-839c-d03774e02ea1@l13g2000yqb.googlegroups.com> <4b153863@dnews.tpgi.com.au> Message-ID: <4b1a3c7a@dnews.tpgi.com.au> On 12/5/2009 2:57 PM, Gnarlodious wrote: > On Dec 1, 3:06 pm, Terry Reedy wrote: >> def print(s): return sys.stdout.buffer.write(s.encode('utf-8')) > > Here is a better solution that lets me send any string to the > function: > > def print(html): return sys.stdout.buffer.write(("Content-type:text/ > plain;charset=utf-8\n\n"+html).encode('utf-8')) No, that's wrong. You're serving HTML with Content-type:text/plain, it should've been text/html or application/xhtml+xml (though technically correct some older browsers have problems with the latter). > Why this changed in Python 3 I do not know, nor why it was nowhere to > be found on the internet. > > Can anyone explain it? Python 3's str() is what was Python 2's unicode(). Python 2's str() turned into Python 3's bytes(). Python 3's print() now takes a unicode string, which is the regular string. Because of the switch to unicode str, a simple print('?') should've worked flawlessly if your terminal can accept the character, but the problem is your terminal does not. The correct fix is to fix your terminal's encoding. In Windows, due to the prompt's poor support for Unicode, the only real solution is to switch to a better terminal. Another workaround is to use a real file: import sys f = open('afile.html', 'w', encoding='utf-8') print("?", file=f) sys.stdout = f print("?") or slightly better is to rewrap the buffer with io.TextIOWrapper: import sys, io sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8") print("?") From wolftracks at invalid.com Sat Dec 5 05:57:46 2009 From: wolftracks at invalid.com (W. eWatson) Date: Sat, 05 Dec 2009 02:57:46 -0800 Subject: Why Can't I Delete a File I Created with Win XP? Message-ID: I'm trying to store analytic data in a folder called Analysis. If the user doesn't have the folder, I make one for him, and then write a txt file into it. In this case a histogram of values, x and frequency. However, it appears that I made a mistake somewhere and cannot delete it using the Win XP delete. Here's the code that determines if Analysis exists, and whether to create it. print "Path for Histogram", self.current_path s = self.current_path s = "Analysis" s = os.path.join("Analysis",s) print "s joined ",s <------------- debug print if not os.path.exists("Analysis"): os.mkdir("Analysis") f = file( s, "wb") if not f: self.LogError( "Histogram file creation error 1" ) return False In writing the code to handle all of this, I forgot to write the txt folder to the file, nor did I close it. It was someone else's code, and I got caught up in the creation of Analysis. Here's what XP tells me when I try to delete the folder. Very funny. I just tried it to get the content of the msg, and XP deleted it. Let me recreate it and try again. OK, here it is: Error Deleting Folder or File. Cannot delete Analysis: It is being used by another person or program. Close programs that might be using it and try again. There is no file created, just the folders Analysis\Analysis. One too many. The second Analysis shows as an icon for a file of size 0KB. I printed with the debug print above: Path for Histogram Events\v20070206_055012.06.dat s joined Analysis\Analysis Analysis\Analysis should only be Analysis. From lie.1296 at gmail.com Sat Dec 5 06:10:28 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Sat, 05 Dec 2009 22:10:28 +1100 Subject: can someone explain 'super' to me? In-Reply-To: References: Message-ID: <4b1a401f$1@dnews.tpgi.com.au> On 12/5/2009 9:27 PM, Michael wrote: > It seems like it can return either a class or an instance of a class. > Like > super( C, self) > is like casting self as superclass C. > However if you omit the second argument entirely you get a class. Inside a class C: these are all equivalent: super().method(arg) # python 3 super(C, self).method(arg) super(C).method(self, arg) it is similar to how you can call class C(object): def method(self, arg): pass inst = C() # these are equivalent inst.method(arg) C.method(inst, arg) python 2.x restricts the first argument of an unbound method to instance of the class; python 3.x does not have such restriction. Thus, it is possible in python 3.x to have: >>> class A(object): ... pass ... >>> class B(object): ... def anom(self): ... print(self) ... >>> a = A() >>> B.anom(a) <__main__.A object at 0x0165C630> the same thing in python 2 would be an error. > The former is considered a "bound" object. I'm really not clear on the > idea of "binding" in Python. The first argument of a bound method (the argument self) is automatically redirected to the instance. Notice when you called a method: class A(object): # this declaration have 3 arguments def foo(self, a, b): pass a = A() # called by only 2 arguments a.foo(1, 2) because a.foo binds method A.foo() and `a`; and `a` is passed implicitly as the first argument to A.foo(a, 1, 2). From alfps at start.no Sat Dec 5 06:30:31 2009 From: alfps at start.no (Alf P. Steinbach) Date: Sat, 05 Dec 2009 12:30:31 +0100 Subject: Can't print Chinese to HTTP In-Reply-To: <4b1a3c7a@dnews.tpgi.com.au> References: <4b13c039$0$7478$9b622d9e@news.freenet.de> <8810fcc1-3e2d-42ce-839c-d03774e02ea1@l13g2000yqb.googlegroups.com> <4b153863@dnews.tpgi.com.au> <4b1a3c7a@dnews.tpgi.com.au> Message-ID: * Lie Ryan: > On 12/5/2009 2:57 PM, Gnarlodious wrote: >> On Dec 1, 3:06 pm, Terry Reedy wrote: >>> def print(s): return sys.stdout.buffer.write(s.encode('utf-8')) >> >> Here is a better solution that lets me send any string to the >> function: >> >> def print(html): return sys.stdout.buffer.write(("Content-type:text/ >> plain;charset=utf-8\n\n"+html).encode('utf-8')) > > No, that's wrong. You're serving HTML with Content-type:text/plain, it > should've been text/html or application/xhtml+xml (though technically > correct some older browsers have problems with the latter). > >> Why this changed in Python 3 I do not know, nor why it was nowhere to >> be found on the internet. >> >> Can anyone explain it? > > Python 3's str() is what was Python 2's unicode(). > Python 2's str() turned into Python 3's bytes(). > > Python 3's print() now takes a unicode string, which is the regular string. > > Because of the switch to unicode str, a simple print('?') should've > worked flawlessly if your terminal can accept the character, but the > problem is your terminal does not. > > The correct fix is to fix your terminal's encoding. > > In Windows, due to the prompt's poor support for Unicode, the only real > solution is to switch to a better terminal. A bit off-topic perhaps, but that last is a misconception. Windows' [cmd.exe] does have poor support for UTF-8, in short it Does Not Work in Windows XP, and probably does not work in Vista or Windows7 either. However, Windows console windows have full support for the Basic Multilingual Plane of Unicode: they're pure Unicode beasts. Thus, the problem is an interaction between two systems that Do Not Work: the [cmd.exe] program's practically non-existing support for UTF-8 (codepage 65001), and the very unfortunate confusion of stream i/o and interactive i/o in *nix, which has ended up as a "feature" (it's more like a design bug) in a lot of programming languages stemming from *nix origins, and that includes Python. Windows' "terminal", its console window support, is INNOCENT... :-) In Windows, as opposed to *nix, interactive character i/o is separated at the API level. There is integration with stream i/o, but the interactive i/o can be accessed separately. This is the "console function" API. So for interactive console i/o one solution could be some Python module for interactive console i/o, on Windows internally using the Windows console function API, which is fully Unicode (based on UCS-2, i.e. the BMP). Cheers, - Alf > Another workaround is to use a real file: > > import sys > f = open('afile.html', 'w', encoding='utf-8') > print("?", file=f) > sys.stdout = f > print("?") > > or slightly better is to rewrap the buffer with io.TextIOWrapper: > import sys, io > sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8") > print("?") From wentland at cl.uni-heidelberg.de Sat Dec 5 06:37:40 2009 From: wentland at cl.uni-heidelberg.de (Wolodja Wentland) Date: Sat, 5 Dec 2009 12:37:40 +0100 Subject: [distutils] Install script under a different name In-Reply-To: <878wdi5kdn.fsf@vostro.rath.org> References: <878wdi5kdn.fsf@vostro.rath.org> Message-ID: <20091205113740.GN3430@kinakuta.local> On Fri, Dec 04, 2009 at 19:34 -0500, Nikolaus Rath wrote: > All my Python files have extension .py. However, I would like to install > scripts that are meant to be called by the user without the suffix, i.e. > the file scripts/doit.py should end up as /usr/bin/doit. > Apparently the scripts= option of the setup() function does not support > this directly. Is there a clever way to get what I want? Just name the file you want to install 'doit' and not 'doit.py'. That would be the easiest way. You might run into problems on Windows though, which IIRC (it's been a while) heavily relies on file suffixes and not on their content. That might have changed in the last 10 years though, so better check that first. You can also use entry points to create the executable at install time. Have a look at [1] which explains how this is done. This requires using Distribute/setuptools though, ... [1] http://packages.python.org/distribute/setuptools.html#automatic-script-creation -- .''`. Wolodja Wentland : :' : `. `'` 4096R/CAF14EFC `- 081C B7CD FF04 2BA9 94EA 36B2 8B7F 7D30 CAF1 4EFC -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 836 bytes Desc: Digital signature URL: From sivaits4u at gmail.com Sat Dec 5 06:40:16 2009 From: sivaits4u at gmail.com (Bujji) Date: Sat, 5 Dec 2009 17:10:16 +0530 Subject: read from standard input In-Reply-To: <200912050214.09673.rami.chowdhury@gmail.com> References: <581ce2790912042137m259a4ad3q4cf8a7a08294fccf@mail.gmail.com> <50697b2c0912042327m4f2330fdr2101cf4d8ae29479@mail.gmail.com> <581ce2790912050120v694b4acdw63742240498b4e93@mail.gmail.com> <200912050214.09673.rami.chowdhury@gmail.com> Message-ID: <581ce2790912050340p509996c3hd647b5deb883cac6@mail.gmail.com> what is the problem you faced in running it on Linux or windows we'll use IDLE only on linux platform like this also you can run see below ubuntu at siva:~/Desktop$ python Python 2.6.2 (r262:71600, Oct 7 2009, 11:27:27) [GCC 4.2.4 (Ubuntu 4.2.4-1ubuntu4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> data=sys.stdin.read() hello world this is a test (give Cntrl D to exit) >>> print data hello world this is a test >>> (I can put data into some other file as well) This is working very well on my PC It should work same on the windows too. but I don't know why its is failing, and thats what i want to know. If any other solution is there let know to get it work on windows ( python IDLE) welcome Thanks, Siva On Sat, Dec 5, 2009 at 3:44 PM, Rami Chowdhury wrote: > On Saturday 05 December 2009 01:20:12 Siva B wrote: > > for the line of code you given, > > > > print type(sys.stdin), sys.stdin > > > > the output is: > > > 0x00BE8090> > > > > there is no change. > > I have tried it in python2.6 on windows platform. > > > > Thanks, > > Siva > > > > How did you run this on Linux? How did you run it on Windows? It looks > like you're running it from within IDLE. I don't know IDLE at all, and > don't know how to pass data to its standard input -- can you let us know > what arguments you're using? > > I've tried sys.stdin.read() from inside IDLE on Linux, and it gives me > the same error. > > > ---- > Rami Chowdhury > "Any sufficiently advanced incompetence is indistinguishable from > malice." -- Grey's Law > 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) > -------------- next part -------------- An HTML attachment was scrubbed... URL: From sjmachin at lexicon.net Sat Dec 5 06:48:41 2009 From: sjmachin at lexicon.net (John Machin) Date: Sat, 5 Dec 2009 03:48:41 -0800 (PST) Subject: Why Can't I Delete a File I Created with Win XP? References: Message-ID: On Dec 5, 9:57?pm, "W. eWatson" wrote: [snip] > ? ? ? ? ?s = self.current_path s referred to something ... > ? ? ? ? ?s = "Analysis" but now s refers to "Analysis" ... at best, there is redundant & confusing code; at worst, the source of your problem. > ? ? ? ? ?s = os.path.join("Analysis",s) and now s refers to r"Analysis\Analysis" (on your platform) > ? ? ? ? ?print "s joined ",s ? ?<------------- debug print [snip] > There is no file created, just the folders Analysis\Analysis. One too > many. The second Analysis shows as an icon for a file of size 0KB. > > I printed with the debug print above: > ? ?Path for Histogram Events\v20070206_055012.06.dat > ? ?s joined ? > Analysis\Analysis should only be Analysis. Huh?? s = os.path.join("fubar", "fubar") should produce r"fubar \fubar" (as documented) ... If you don't want s to refer to r"Analysis \Analysis", then quite simply don't do that! From usenot at geekmail.INVALID Sat Dec 5 06:55:01 2009 From: usenot at geekmail.INVALID (Andreas Waldenburger) Date: Sat, 5 Dec 2009 12:55:01 +0100 Subject: Are routine objects guaranteed mutable & with dictionary? References: <4a2a7fdf-99d4-4219-a56c-7cd9146b3c85@f20g2000prn.googlegroups.com> Message-ID: <20091205125501.4932481d@geekmail.INVALID> On Sat, 05 Dec 2009 11:26:34 +0100 "Alf P. Steinbach" wrote: > * "function" is misleading in itself (due to the hijacking of this > term in mathematics), [...] Can you please elaborate? To me, a function is something that transforms some input to some output [1]. Which is exactly what Python functions do, without fail. [1] I was going to write "maps" instead of "transforms" but that seemed odd to me (in the context of Python). So I think I sort of see where you're going with this. But I'm still curious about the details. /W -- INVALID? DE! From lie.1296 at gmail.com Sat Dec 5 07:06:15 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Sat, 05 Dec 2009 23:06:15 +1100 Subject: python bijection In-Reply-To: <00a37199$0$15659$c3e8da3@news.astraweb.com> References: <4B17A960.1090700@egenix.com> <4B17FBFE.8070903@egenix.com> <4B18F685.8050102@egenix.com> <4B193610.6050700@mrabarnett.plus.com> <4b196d1f$1@dnews.tpgi.com.au> <5ac80cf9-d0fc-450e-b8bb-ffef91e81f0a@d10g2000yqh.googlegroups.com> <4b19ace0$1@dnews.tpgi.com.au> <00a37199$0$15659$c3e8da3@news.astraweb.com> Message-ID: <4b1a4d33$1@dnews.tpgi.com.au> On 12/5/2009 4:18 PM, Steven D'Aprano wrote: >> Tree is better than Graph >> >> not having Tree and Graph package in the standard library force most >> people to find List-based solution. > > If you have to be *forced* to use a list-based solution, that's a good > sign that a list is *not* the right tool for the job. Sorry for putting too much emphasis on the "forced", that wasn't my intention. I was mentioning that often simple problems appeared more complex because the person was thinking in a higher level data structure than is necessary. "forced" in that sentence means to let people to think a little bit harder with list/dict before deciding that they are unsuitable and moving to a tree or a graph. From fabiofz at gmail.com Sat Dec 5 07:15:33 2009 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Sat, 5 Dec 2009 10:15:33 -0200 Subject: editor with autocompletion In-Reply-To: <581ce2790912042319nfaa4b88oaeaa0a70cc50fef9@mail.gmail.com> References: <581ce2790912032209m2f060e9agb2a7ada6dfb1f8c9@mail.gmail.com> <581ce2790912042319nfaa4b88oaeaa0a70cc50fef9@mail.gmail.com> Message-ID: On Sat, Dec 5, 2009 at 5:19 AM, Siva B wrote: > Hi All, > Thanks for your reply. > > What I want is An Editor which can support Dynamic Languages with > Autocomplete. > > I have my own language with some file extension (for ex: *.fs ) > I can add few keywords to editor, it should support autocomplte. > thats what my idea. > > plz send me pointers (good if it is open source.) > I have seen Komodo edit but it looks too big > > any help plz. > I'd recommend notepad++ (for windows): should be easy to add simple completions. See: http://notepad-plus.sourceforge.net/uk/auto-completion-HOWTO.php If you know java and would like more options for your support (i.e.: IDE features) Eclipse could be an option (basic support for a language should be easy to add -- only when you want more advanced features the learning curve to add them becomes steeper, although that road will certainly be more work than adding support in notepad++ ). Cheers, Fabio From anand.ibmgsi at gmail.com Sat Dec 5 08:25:06 2009 From: anand.ibmgsi at gmail.com (anand jeyahar) Date: Sat, 5 Dec 2009 18:55:06 +0530 Subject: Why Can't I Delete a File I Created with Win XP? In-Reply-To: References: Message-ID: <1a3a139e0912050525y70adb3a0w26a43573a4db3758@mail.gmail.com> simple.... when the python program ended, the file handle created by it was still open... so windows will not allow you to delete it.... (the standard behaviour, when a parent process dies, with a sub-process running is to keep the child running.) try logging off and back on.....it will solve the problem.. ============================== ================ Anand J http://sites.google.com/a/cbcs.ac.in/students/anand ============================================== The man who is really serious, with the urge to find out what truth is, has no style at all. He lives only in what is. ~Bruce Lee Love is a trade with lousy accounting policies. ~Aang Jie - Show quoted text - ============================================== Anand J http://sites.google.com/a/cbcs.ac.in/students/anand ============================================== The man who is really serious, with the urge to find out what truth is, has no style at all. He lives only in what is. ~Bruce Lee Love is a trade with lousy accounting policies. ~Aang Jie -------------- next part -------------- An HTML attachment was scrubbed... URL: From fordhaivat at gmail.com Sat Dec 5 08:49:24 2009 From: fordhaivat at gmail.com (Someone Something) Date: Sat, 5 Dec 2009 08:49:24 -0500 Subject: editor with autocompletion In-Reply-To: References: <581ce2790912032209m2f060e9agb2a7ada6dfb1f8c9@mail.gmail.com> <581ce2790912042319nfaa4b88oaeaa0a70cc50fef9@mail.gmail.com> Message-ID: If you're actually going to release this, you shouldn't bundle it with a preexisting text editor (IMHO) in case it goes out of development and then you'll end up like DSL (damn small linux) did. In other words either you get a text editor that's basically never going out of development (emacs, not vim since its not that well grounded) and write extensions for it, OR, write your own text editor. Second option is very highly time consuming. On 12/5/09, Fabio Zadrozny wrote: > On Sat, Dec 5, 2009 at 5:19 AM, Siva B wrote: >> Hi All, >> Thanks for your reply. >> >> What I want is An Editor which can support Dynamic Languages with >> Autocomplete. >> >> I have my own language with some file extension (for ex: *.fs ) >> I can add few keywords to editor, it should support autocomplte. >> thats what my idea. >> >> plz send me pointers (good if it is open source.) >> I have seen Komodo edit but it looks too big >> >> any help plz. >> > > I'd recommend notepad++ (for windows): should be easy to add simple > completions. See: > http://notepad-plus.sourceforge.net/uk/auto-completion-HOWTO.php > > If you know java and would like more options for your support (i.e.: > IDE features) Eclipse could be an option (basic support for a language > should be easy to add -- only when you want more advanced features the > learning curve to add them becomes steeper, although that road will > certainly be more work than adding support in notepad++ ). > > Cheers, > > Fabio > -- > http://mail.python.org/mailman/listinfo/python-list > From rune.strand at gmail.com Sat Dec 5 09:01:38 2009 From: rune.strand at gmail.com (Rune Strand) Date: Sat, 5 Dec 2009 06:01:38 -0800 (PST) Subject: How to timeout when waiting for raw_input from user ? References: <55b6b337-fb8f-46b9-a665-108dd19e1dd8@w19g2000pre.googlegroups.com> <7xhbs6xad0.fsf@ruckus.brouhaha.com> <465b7ba8-d2cd-4962-ad17-e22a75383e21@x25g2000prf.googlegroups.com> Message-ID: The easiest wasy is to use the Timer object in the threading module. from threading import Timer From mkhitrov at gmail.com Sat Dec 5 09:07:32 2009 From: mkhitrov at gmail.com (Maxim Khitrov) Date: Sat, 5 Dec 2009 09:07:32 -0500 Subject: How to timeout when waiting for raw_input from user ? In-Reply-To: References: <55b6b337-fb8f-46b9-a665-108dd19e1dd8@w19g2000pre.googlegroups.com> <7xhbs6xad0.fsf@ruckus.brouhaha.com> <465b7ba8-d2cd-4962-ad17-e22a75383e21@x25g2000prf.googlegroups.com> Message-ID: <26ddd1750912050607g4f33b1b9x615b97a5813dc7b4@mail.gmail.com> On Sat, Dec 5, 2009 at 9:01 AM, Rune Strand wrote: > The easiest wasy is to use the Timer object in the threading module. > > > from threading import Timer Doesn't work on Windows. - Max From rune.strand at gmail.com Sat Dec 5 09:11:58 2009 From: rune.strand at gmail.com (Rune Strand) Date: Sat, 5 Dec 2009 06:11:58 -0800 (PST) Subject: How to timeout when waiting for raw_input from user ? References: <55b6b337-fb8f-46b9-a665-108dd19e1dd8@w19g2000pre.googlegroups.com> <7xhbs6xad0.fsf@ruckus.brouhaha.com> <465b7ba8-d2cd-4962-ad17-e22a75383e21@x25g2000prf.googlegroups.com> Message-ID: On Dec 5, 3:07?pm, Maxim Khitrov wrote: > > Doesn't work on Windows. > > - Max Yes, it does. I've used it a lot, also in Py2Exe apps. Try the documentation example yourself def hello(): print "hello, world" t = Timer(30.0, hello) t.start() # after 30 seconds, "hello, world" will be printed From mkhitrov at gmail.com Sat Dec 5 09:42:07 2009 From: mkhitrov at gmail.com (Maxim Khitrov) Date: Sat, 5 Dec 2009 09:42:07 -0500 Subject: How to timeout when waiting for raw_input from user ? In-Reply-To: References: <55b6b337-fb8f-46b9-a665-108dd19e1dd8@w19g2000pre.googlegroups.com> <7xhbs6xad0.fsf@ruckus.brouhaha.com> <465b7ba8-d2cd-4962-ad17-e22a75383e21@x25g2000prf.googlegroups.com> Message-ID: <26ddd1750912050642n4e515582ga23299babec5405b@mail.gmail.com> On Sat, Dec 5, 2009 at 9:11 AM, Rune Strand wrote: > On Dec 5, 3:07?pm, Maxim Khitrov wrote: >> >> Doesn't work on Windows. >> >> - Max > > Yes, it does. I've used it a lot, also in Py2Exe apps. ?Try the > documentation example yourself > > def hello(): > ? ?print "hello, world" > > t = Timer(30.0, hello) > t.start() # after 30 seconds, "hello, world" will be printed I'm not talking about the Timer, I'm talking about the original question. There's nothing (that I know of) you can do with a Timer on Windows to interrupt a raw_input call. - Max From gerenuk81 at googlemail.com Sat Dec 5 10:37:17 2009 From: gerenuk81 at googlemail.com (Anton81) Date: Sat, 5 Dec 2009 07:37:17 -0800 (PST) Subject: Float precision and float equality Message-ID: I'd like to do calculations with floats and at some point equality of two number will be checked. What is the best way to make sure that equality of floats will be detected, where I assume that mismatches beyond a certain point are due to truncation errors? From wolftracks at invalid.com Sat Dec 5 10:46:38 2009 From: wolftracks at invalid.com (W. eWatson) Date: Sat, 05 Dec 2009 07:46:38 -0800 Subject: Why Can't I Delete a File I Created with Win XP? In-Reply-To: References: Message-ID: The program code is not mine, but I wanted to modify it to produce an Analysis folder when the user wants histogram file, basically, a txt file to appear in Analysis. Elsewhere in the program this is done for another type of data that is directed to an Events folder. I figured I could copy the code from there and use it here. Here's other code for Events. # He's building a time stamp for the file name. # I'll use this with a slight modification to the name in # my code millisecs = int((event_time - int(event_time))*100) s = "v%4d%02d%02d_%02d%02d%02d.%02d.dat" % ( t.tm_year, t.tm_mon, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec, millisecs ) #OK, he's got the file name assembled s = os.path.join("Events",s) if not os.path.exists("Events"): os.mkdir("Events") f = file( s, "wb" ) if not f: self.LogError( "File creation error 1" ) return False I caused the redundancy by just changing the meaning of s with a new statement below it. I should have commented the first one out. Yeah, I probably screwed up here and should have and,for purposes of debugging, just used another file name like s="ADATAFILE2009_mmdd.txt", which does not exist at this point of the coding stage. So I should have produced Analysis\ADATAFILE2009_mmdd.txt. If I had done that then I would have ended up with an empty file in the Analysis folder. However, even at that, why can't I delete this empty file called Analysis? When I said I was able to get rid of the "file", it's probably because I had rebooted at some time after I puzzled over the problem, and now OS somehow released it's grip, that is, whatever process was trying to use the "file" too. John Machin wrote: > On Dec 5, 9:57 pm, "W. eWatson" wrote: > [snip] >> s = self.current_path > s referred to something ... >> s = "Analysis" > but now s refers to "Analysis" ... at best, there is redundant & > confusing code; at worst, the source of your problem. > >> s = os.path.join("Analysis",s) > and now s refers to r"Analysis\Analysis" (on your platform) >> print "s joined ",s <------------- debug print > > [snip] > >> There is no file created, just the folders Analysis\Analysis. One too >> many. The second Analysis shows as an icon for a file of size 0KB. >> >> I printed with the debug print above: >> Path for Histogram Events\v20070206_055012.06.dat >> s joined >> Analysis\Analysis should only be Analysis. > > Huh?? s = os.path.join("fubar", "fubar") should produce r"fubar > \fubar" (as documented) ... If you don't want s to refer to r"Analysis > \Analysis", then quite simply don't do that! > From victorsubervi at gmail.com Sat Dec 5 10:52:10 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Sat, 5 Dec 2009 10:52:10 -0500 Subject: Nested Dicts Message-ID: <4dc0cfea0912050752m53125a73g6a72cd8f9a48f06c@mail.gmail.com> Hi; I have the following error: /var/www/html/angrynates.com/cart/catTree.py in getChildren(levelDict={'cat3': {}}, level=0) 23 if level > MAXLEVEL: 24 return #possibly the data has a cycle/loop 25 for (nm, dt) in levelDict: ### ERROR HERE 26 cursor.execute('''select c.name from categories as c 27 inner join relationship as r nm undefined, dt undefined, levelDict = {'cat3': {}} ValueError: too many values to unpack args = ('too many values to unpack',) However... >>> d = {'cat': {'one':'two'}} >>> for a, b in d: ... File "", line 2 ^ IndentationError: expected an indented block >>> d = {'cat': {}} >>> for a, b in d: ... File "", line 2 ^ IndentationError: expected an indented block >>> So apparently, if either the nested dict is populated or not doesn't seem to throw any errors in the interpreter. What, then, is the nature of this error? TIA, Victor -------------- next part -------------- An HTML attachment was scrubbed... URL: From Nikolaus at rath.org Sat Dec 5 11:08:01 2009 From: Nikolaus at rath.org (Nikolaus Rath) Date: Sat, 05 Dec 2009 11:08:01 -0500 Subject: [distutils] Install script under a different name References: <878wdi5kdn.fsf@vostro.rath.org> <4b19bd4e$1@dnews.tpgi.com.au> Message-ID: <87fx7pbdzy.fsf@vostro.rath.org> Lie Ryan writes: > On 12/5/2009 11:34 AM, Nikolaus Rath wrote: >> Hello, >> >> All my Python files have extension .py. However, I would like to install >> scripts that are meant to be called by the user without the suffix, i.e. >> the file scripts/doit.py should end up as /usr/bin/doit. >> >> Apparently the scripts= option of the setup() function does not support >> this directly. Is there a clever way to get what I want? > > if this is on windows, you should add ".py" to the PATHEXT environment > variable. > > on linux/unix, you need to add the proper #! line to the top of any > executable scripts and of course set the executable bit permission > (chmod +x scriptname). In linux/unix there is no need to have the .py > extension for a file to be recognized as python script (i.e. just > remove it). Sorry, but I think this is totally unrelated to my question. I want to rename files during the setup process. This is not going to happen by adding/changing any #! lines or the permissions of the file. I know that there is no need to have the .py extension, that's why I want to install the scripts without this suffix. But in my source distribution I want to keep the suffix for various reasons. Best, -Nikolaus -- ?Time flies like an arrow, fruit flies like a Banana.? PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6 02CF A9AD B7F8 AE4E 425C From Nikolaus at rath.org Sat Dec 5 11:12:14 2009 From: Nikolaus at rath.org (Nikolaus Rath) Date: Sat, 05 Dec 2009 11:12:14 -0500 Subject: [distutils] Install script under a different name References: <878wdi5kdn.fsf@vostro.rath.org> Message-ID: <87d42tbdsx.fsf@vostro.rath.org> Wolodja Wentland writes: > On Fri, Dec 04, 2009 at 19:34 -0500, Nikolaus Rath wrote: >> All my Python files have extension .py. However, I would like to install >> scripts that are meant to be called by the user without the suffix, i.e. >> the file scripts/doit.py should end up as /usr/bin/doit. > >> Apparently the scripts= option of the setup() function does not support >> this directly. Is there a clever way to get what I want? > > You can also use entry points to create the executable at install time. > Have a look at [1] which explains how this is done. This requires using > Distribute/setuptools though, ... > > [1] http://packages.python.org/distribute/setuptools.html#automatic-script-creation That looks perfect, thanks! Best, -Nikolaus -- ?Time flies like an arrow, fruit flies like a Banana.? PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6 02CF A9AD B7F8 AE4E 425C From nobody at nowhere.com Sat Dec 5 11:20:08 2009 From: nobody at nowhere.com (Nobody) Date: Sat, 05 Dec 2009 16:20:08 +0000 Subject: UnicodeDecodeError? Argh! Nothing works! I'm tired and hurting and... References: <031bc732$0$1336$c3e8da3@news.astraweb.com> <3jvlu6-0g4.ln1@nb2.stroeder.com> <00a1dd7b$0$26893$c3e8da3@news.astraweb.com> Message-ID: On Fri, 04 Dec 2009 00:33:57 +0000, Steven D'Aprano wrote: >>> Just to be contrary, I *like* mbox. >> >> Me too. :-) Me too. > Why? What features or benefits of mbox do you see that make up for it's > disadvantages? Simplicity and performance. Maildir isn't simple when you add in the filesystem or archive format (leaving aside the fact that maildir cannot be processed using nothing but ANSI C). Nor is it particularly quick if you want to grep for a message in a decade's worth of archives (even on Linux; and NTFS is *much* worse for dealing with many small files). From darcy at druid.net Sat Dec 5 11:24:40 2009 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Sat, 5 Dec 2009 11:24:40 -0500 Subject: Nested Dicts In-Reply-To: <4dc0cfea0912050752m53125a73g6a72cd8f9a48f06c@mail.gmail.com> References: <4dc0cfea0912050752m53125a73g6a72cd8f9a48f06c@mail.gmail.com> Message-ID: <20091205112440.b64535c5.darcy@druid.net> On Sat, 5 Dec 2009 10:52:10 -0500 Victor Subervi wrote: > Hi; > I have the following error: > > /var/www/html/angrynates.com/cart/catTree.py in > getChildren(levelDict={'cat3': {}}, level=0) > 23 if level > MAXLEVEL: > 24 return #possibly the data has a cycle/loop > 25 for (nm, dt) in levelDict: ### ERROR HERE Yes, you are tring to assign to two variabels but levelDict is a single object, a dictionary with a single element which is another dictionary. If, as I assume, nm and dt (very poor variable names, especially when you are asking others to help you debug) refer to name and data by which you mean key and value from the dictionary then perhaps you really want this. for key, val in levelDict.items(): ... -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From python at mrabarnett.plus.com Sat Dec 5 11:25:03 2009 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 05 Dec 2009 16:25:03 +0000 Subject: Nested Dicts In-Reply-To: <4dc0cfea0912050752m53125a73g6a72cd8f9a48f06c@mail.gmail.com> References: <4dc0cfea0912050752m53125a73g6a72cd8f9a48f06c@mail.gmail.com> Message-ID: <4B1A895F.9040402@mrabarnett.plus.com> Victor Subervi wrote: > Hi; > I have the following error: > > /var/www/html/angrynates.com/cart/catTree.py > in > getChildren(levelDict={'cat3': {}}, level=0) > 23 if level > MAXLEVEL: > 24 return #possibly the data has a cycle/loop > 25 for (nm, dt) in levelDict: ### ERROR HERE > 26 cursor.execute('''select c.name from > categories as c > 27 inner join relationship as r > nm undefined, dt undefined, levelDict = {'cat3': {}} > > ValueError: too many values to unpack > args = ('too many values to unpack',) > > However... > > >>> d = {'cat': {'one':'two'}} > >>> for a, b in d: > ... > File "", line 2 > > ^ > IndentationError: expected an indented block > >>> d = {'cat': {}} > >>> for a, b in d: > ... > File "", line 2 > > ^ > IndentationError: expected an indented block > >>> > > So apparently, if either the nested dict is populated or not doesn't > seem to throw any errors in the interpreter. What, then, is the nature > of this error? > When you iterate through a dict, it yields the keys. It's all in the documentation. From dickinsm at gmail.com Sat Dec 5 11:46:55 2009 From: dickinsm at gmail.com (Mark Dickinson) Date: Sat, 5 Dec 2009 08:46:55 -0800 (PST) Subject: Float precision and float equality References: Message-ID: <3abf9dfb-fa01-4f71-9214-a06d8b847ebf@e20g2000vbb.googlegroups.com> On Dec 5, 3:37?pm, Anton81 wrote: > I'd like to do calculations with floats and at some point equality of > two number will be checked. > What is the best way to make sure that equality of floats will be > detected, where I assume that mismatches beyond a certain point are > due to truncation errors? Well, it depends a lot on the details of the application, but a good general scheme is to allow both a fixed relative error and an absolute error, and to assert that your two values are 'nearly equal' if they're within *either* the relative error *or* the absolute error. Something like, for example: def almostEqual(expected, actual, rel_err=1e-7, abs_err = 1e-20): absolute_error = abs(actual-expected) return absolute_error <= max(abs_err, rel_err * abs(expected)) Then choose the values of rel_err and abs_err to suit your application. What sort of calculations are you doing? -- Mark From sturlamolden at yahoo.no Sat Dec 5 11:47:08 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Sat, 5 Dec 2009 08:47:08 -0800 (PST) Subject: ctypes pointer from offset into array? References: Message-ID: On 5 Des, 10:13, Carl Banks wrote: > Is there a way to get the pointer to an array offset in ctypes. > Example, say I define an array like so: > > xfer = (c_char*bufsize)() > > How would I get a pointer to then nth byte (equivalient of &xfer[n])? > I guess I would have expected xfer+n to work, but it doesn't. See: http://bugs.python.org/issue6259 For now, we can still work with char* by casting them to an integer: >>> from ctypes import * >>> bufsize = 1024 >>> xfer = (c_char*bufsize)() # cast to pointer >>> ptr = cast(xfer, POINTER(c_char)) # obtain address >>> addressof(xfer) 36279232 >>> addressof(ptr) 45151576 >>> addressof(ptr.contents) 36279232 # add offset to pointer >>> cast(addressof(ptr.contents)+10,POINTER(c_char)) >>> cast(addressof(xfer)+10,POINTER(c_char)) # byref also takes an offset >>> byref(xfer,0) >>> byref(xfer,10) From sturlamolden at yahoo.no Sat Dec 5 11:49:19 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Sat, 5 Dec 2009 08:49:19 -0800 (PST) Subject: ctypes pointer from offset into array? References: Message-ID: On 5 Des, 10:13, Carl Banks wrote: > Is there a way to get the pointer to an array offset in ctypes. Could also mention that Cython has pointer arithmetics. Cython can be easier to use than ctypes, but is not a standard module. From carsten.haese at gmail.com Sat Dec 5 12:01:59 2009 From: carsten.haese at gmail.com (Carsten Haese) Date: Sat, 05 Dec 2009 12:01:59 -0500 Subject: Nested Dicts In-Reply-To: <4dc0cfea0912050752m53125a73g6a72cd8f9a48f06c@mail.gmail.com> References: <4dc0cfea0912050752m53125a73g6a72cd8f9a48f06c@mail.gmail.com> Message-ID: Victor Subervi wrote: >>>> d = {'cat': {'one':'two'}} >>>> for a, b in d: > ... > File "", line 2 > > ^ > IndentationError: expected an indented block >>>> d = {'cat': {}} >>>> for a, b in d: > ... > File "", line 2 > > ^ > IndentationError: expected an indented block >>>> > > So apparently, if either the nested dict is populated or not doesn't > seem to throw any errors in the interpreter. What do you mean by "doesn't seem to throw any errors in the interpreter?" Can't you see the IndentationErrors above?!? IndentationErrors *are* errors! A for-loop needs to have at least one statement inside the suite after the colon. You're not putting any statements after the colon, and that's why Python is throwing the same error in either case. Because you're not entering syntactically correct code, the interpreter session never even gets around to iterating over the dictionary, so your session dies before it gets a chance to reproduce the error you're looking for. If you put a dummy "pass" statement into the loop, you'll reproduce the ValueError you're trying to troubleshoot: >>> d = {'cat': {'one':'two'}} >>> for a, b in d: ... pass ... Traceback (most recent call last): File "", line 1, in ValueError: too many values to unpack As far as what's causing this error, I already explained that two weeks ago: http://groups.google.com/group/comp.lang.python/msg/b9e02a9a9b550ad3 The fact that you're still struggling with this error is deeply disturbing to me. -- Carsten Haese http://informixdb.sourceforge.net From victorsubervi at gmail.com Sat Dec 5 12:14:33 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Sat, 5 Dec 2009 12:14:33 -0500 Subject: Nested Dicts In-Reply-To: References: <4dc0cfea0912050752m53125a73g6a72cd8f9a48f06c@mail.gmail.com> Message-ID: <4dc0cfea0912050914h4ecc663dnfa7de33cfe48baa2@mail.gmail.com> On Sat, Dec 5, 2009 at 12:01 PM, Carsten Haese wrote: > Victor Subervi wrote: > >>>> d = {'cat': {'one':'two'}} > >>>> for a, b in d: > > ... > > File "", line 2 > > > > ^ > > IndentationError: expected an indented block > >>>> d = {'cat': {}} > >>>> for a, b in d: > > ... > > File "", line 2 > > > > ^ > > IndentationError: expected an indented block > >>>> > > > > So apparently, if either the nested dict is populated or not doesn't > > seem to throw any errors in the interpreter. > > What do you mean by "doesn't seem to throw any errors in the > interpreter?" Can't you see the IndentationErrors above?!? > IndentationErrors *are* errors! > > A for-loop needs to have at least one statement inside the suite after > the colon. You're not putting any statements after the colon, and that's > why Python is throwing the same error in either case. > > Because you're not entering syntactically correct code, the interpreter > session never even gets around to iterating over the dictionary, so your > session dies before it gets a chance to reproduce the error you're > looking for. If you put a dummy "pass" statement into the loop, you'll > reproduce the ValueError you're trying to troubleshoot: > > >>> d = {'cat': {'one':'two'}} > >>> for a, b in d: > ... pass > ... > Traceback (most recent call last): > File "", line 1, in > ValueError: too many values to unpack > > As far as what's causing this error, I already explained that two weeks > ago: http://groups.google.com/group/comp.lang.python/msg/b9e02a9a9b550ad3 > > The fact that you're still struggling with this error is deeply > disturbing to me. > Relax, Carsten. Of course I knew about those indentation errors, etc. I was testing to see if it would even take the line I entered. I wasn't interested in supplying anything beyond that. The others who answered this post hit the issue squarely. This "pseudo-code" was actually supplied to me by one of you python "gurus" who has all my respect, so I didn't review it as closely as I should have. My apologies. Thanks, V -------------- next part -------------- An HTML attachment was scrubbed... URL: From nobody at nowhere.com Sat Dec 5 12:14:38 2009 From: nobody at nowhere.com (Nobody) Date: Sat, 05 Dec 2009 17:14:38 +0000 Subject: question about subprocess and shells References: Message-ID: On Fri, 04 Dec 2009 13:38:11 -0800, Ross Boylan wrote: > If one uses subprocess.Popen(args, ..., shell=True, ...) > > When args finishes execution, does the shell terminate? Either way > seems problematic. That depends upon what "args" is. On Unix, if args ends with a "&", the shell will terminate as soon as it has started the command. Typically, the shell will terminate once it has executed the last command, where "executed" means fork()+exec() for a background command and fork()+exec()+wait() for a non-background command. > If it does not terminate, then it seems as if calls like wait and > communicate would never return. It also seems the subprocess would > never die, and that most of the examples with the shell True would leave > processes lying around. That would be the case if the shell didn't terminate. > If it does terminate, then how can you stuff new commands down the pipe > to the subprocesses stdin? You don't. shell=True executes ["/bin/sh", "-c", args], not an interactive shell reading commands from stdin (unless you explicitly run an interactive shell with e.g. Popen(args = "sh", ...)). > Does this module contemplate receiving multiple commands for the shell > to execute? No. It behaves like an extended version of the Unix popen() function, i.e. like system() but you get to provide pipes for the standard handles. > I'm also unsure of the semantics of the pipes for the processes standard > file handles. Do they need to be closed (judging from the examples, > no)? If args is a command which reads from stdin, then you will need to close stdin, otherwise it will never terminate. Otherwise, there's no need. > When reads/writes to them return, and what state is the stream in > at the time? Any streams created when std{in,out,err}= are specified as PIPE or as a descriptor number are unbuffered by default, but this can be changed by the bufsize parameter to the Popen() constructor. For an unbuffered stream, read() and write() will return when the underlying system calls return. write() to stdin will return once the data has been written to the pipe (not necessarily when the child has consumed it), while read() from stdout/stderr will return once the requested amount of data has been read from the pipe (or EOF is reached). From aahz at pythoncraft.com Sat Dec 5 12:24:43 2009 From: aahz at pythoncraft.com (Aahz) Date: 5 Dec 2009 09:24:43 -0800 Subject: TDD with nose or py.test References: <2519ffb0-fd49-4340-857b-62fca5c71421@33g2000vbe.googlegroups.com> Message-ID: In article <2519ffb0-fd49-4340-857b-62fca5c71421 at 33g2000vbe.googlegroups.com>, Lacrima wrote: > >I am learning TDD with Python and there is not much information about >this topic. Python is shipped with unittest module. That is fine, but >I also discovered other libraries: nose and py.test. They promise to >make life yet easier for a developer. But I still can't figure out, >which combination I should use them in. My company decided to use py.test because it offered better support for cross-platform and multi-machine testing (at least as of a couple of months ago when we made the decision). Otherwise, the two seem pretty comparable and nose seems to be easier to use. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ The best way to get information on Usenet is not to ask a question, but to post the wrong information. From carsten.haese at gmail.com Sat Dec 5 12:39:17 2009 From: carsten.haese at gmail.com (Carsten Haese) Date: Sat, 05 Dec 2009 12:39:17 -0500 Subject: Nested Dicts In-Reply-To: <4dc0cfea0912050914h4ecc663dnfa7de33cfe48baa2@mail.gmail.com> References: <4dc0cfea0912050752m53125a73g6a72cd8f9a48f06c@mail.gmail.com> <4dc0cfea0912050914h4ecc663dnfa7de33cfe48baa2@mail.gmail.com> Message-ID: Victor Subervi wrote: > Of course I knew about those indentation errors That may be so, but you cleverly disguised this fact by saying the exact opposite. -- Carsten Haese http://informixdb.sourceforge.net From mrjean1 at gmail.com Sat Dec 5 12:45:25 2009 From: mrjean1 at gmail.com (MrJean1) Date: Sat, 5 Dec 2009 09:45:25 -0800 (PST) Subject: How to timeout when waiting for raw_input from user ? References: <55b6b337-fb8f-46b9-a665-108dd19e1dd8@w19g2000pre.googlegroups.com> Message-ID: <52cc49c8-b847-40de-b1ef-1afd2c1ea74c@z7g2000vbl.googlegroups.com> Try using the function timelimited from this recipe An (untested) example with a 60 second timeout would be: try: r = timelimited(60, raw_input, 'enter right or wrong: ') except TimeLimitExpired: .... except KeyboardInterrupt: .... /Jean On Dec 4, 3:52?pm, northof40 wrote: > Hi - I'm writing a *very* simple program for my kids. It asks the user > to give it the answer to a maths question and says "right" or "wrong" > > They now want a timed version where they would only get so long to > respond to the question. > > I'm thinking of some logic where a raw_input call is executed and then > if more than X seconds elapses before the prompt is replied to the > process writes a message "Sorry too slow" (or similar). > > I can't see the wood for the trees here - what's the best way to do > this given the rather simple environment it's needed within. > > Regards > > richard. From fsenkel at lynx.neu.edu Sat Dec 5 13:09:15 2009 From: fsenkel at lynx.neu.edu (monkeyboy) Date: Sat, 5 Dec 2009 10:09:15 -0800 (PST) Subject: Question on class module import References: <628c7ffa-74b4-439e-bed9-331c6354f280@j24g2000yqa.googlegroups.com> Message-ID: Thank you, that clears it for me From aahz at pythoncraft.com Sat Dec 5 13:09:45 2009 From: aahz at pythoncraft.com (Aahz) Date: 5 Dec 2009 10:09:45 -0800 Subject: os.remove() permission problem References: <4dc0cfea0911301121u50efa2aat807e245c2ef05f59@mail.gmail.com> <4dc0cfea0912010505s121d6951xa580feeca05ce2f8@mail.gmail.com> Message-ID: In article , Christian Heimes wrote: > >You have to set the write and execute permssion on *directory*, not on >the file. unlink (aka remove) requires write permission on the directory >in order to remove the file. > >It's like in the real world. You may be allowed to modify a document (w >permission on the file) but you may not be allowed to remove it from its >cabinet (w permission on the directory). Note that this applies to Unix/Mac; on Windows, you can't delete read-only files. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ The best way to get information on Usenet is not to ask a question, but to post the wrong information. From victorsubervi at gmail.com Sat Dec 5 13:20:06 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Sat, 5 Dec 2009 13:20:06 -0500 Subject: Nested Dicts In-Reply-To: References: <4dc0cfea0912050752m53125a73g6a72cd8f9a48f06c@mail.gmail.com> <4dc0cfea0912050914h4ecc663dnfa7de33cfe48baa2@mail.gmail.com> Message-ID: <4dc0cfea0912051020i64ee19dbp3037dcfec366bd07@mail.gmail.com> On Sat, Dec 5, 2009 at 12:39 PM, Carsten Haese wrote: > Victor Subervi wrote: > > Of course I knew about those indentation errors > > That may be so, but you cleverly disguised this fact by saying the exact > opposite. > I will try not to make such assumptions in the future. Forgive me for leading you astray in your attempt to be of service to me. Thank you, Victor -------------- next part -------------- An HTML attachment was scrubbed... URL: From nobody at nowhere.com Sat Dec 5 13:28:29 2009 From: nobody at nowhere.com (Nobody) Date: Sat, 05 Dec 2009 18:28:29 +0000 Subject: Specifying an API for a straeming parser References: Message-ID: On Fri, 04 Dec 2009 13:51:15 -0800, tyler wrote: > Howdy folks, I'm working on a JSON Python module [1] and I'm struggling with > an appropriate syntax for dealing with incrementally parsing streams of data > as they come in (off a socket or file object). > > The underlying C-level parsing library that I'm using (Yajl [2]) already uses > a callback system internally for handling such things, but I'm worried about: > * Ease of use, simplicity > * Python method invocation overhead going from C back into Python > > One of the ideas I've had is to "iterparse" a la: > > >>> for k, v in yajl.iterloads(fp): > ... print ('key, value', k, v) > >>> > > Effectively building a generator for the JSON string coming off of the `fp` > object and when generator.next() is called reading more of the stream object. > This has some shortcomings however: > * For JSON like: '''{"rc":0,"data":}''' the iterloads() > function would block for some time when processing the value of the "data" > key. > * Presumes the developer has prior knowledge of the kind of JSON strings > being passed in > > I've searched around, following this "iterloads" notion, for a tree-generator > and I came up with nothing. > > Any suggestions on how to accomplish iterloads, or perhaps a suggestion for a > more sensible syntax for incrementally parsing objects from the stream and > passing them up into Python? One option is to return values as opaque objects with .type() and .data() methods. The opaque object can be returned as soon as the parser starts to parse the value. If the user calls the .data() method for an atomic object (string, number, boolean, null) before parsing is complete, the call will block. For composite objects (array, object), the call will return an iterator immediately. If the user never calls the data() method, there's no need to convert the element to a Python value. If the object's refcount reaches zero while parsing is still ongoing, the parser can discard any existing data and discard further data as it is read. E.g. a program to read JSON data from stdin and print the data back to stdout in (approximately) JSON format would look like: def print_json(f, node): if node.type() == json.NULL: f.write("null") elif node.type() == json.BOOL: f.write("true" if node.data() else "false") elif node.type() == json.NUMBER: f.write(node.data()) elif node.type() == json.STRING: f.write('"' + node.data() + '"') elif node.type() == json.ARRAY: f.write('[') for i, v in enumerate(node.data()): if i > 0: f.write(',') print_json(f, v) f.write(']') elif node.type() == json.OBJECT: f.write('{') for i, (k, v) in enumerate(node.data()): if i > 0: f.write(',') print_json(f, k) f.write(": ") print_json(f, v) f.write('}') root = json.parse(sys.stdin) print_json(sys.stdout, root) For greater pythonicity, you could make the composite types implement the iterator interface directly, so the data() method becomes redundant (if called, it would just return "self"), and use distinct classes for the distinct types (so that you can use type() or isinstance()), i.e.: def print_json(f, node): if isinstance(node, json.Null): f.write("null") elif isinstance(node, json.Bool): f.write("true" if node.data() else "false") elif isinstance(node, json.Number): f.write(node.data()) elif isinstance(node, json.String): f.write('"' + node.data() + '"') elif isinstance(node, json.Array): f.write('[') for i, v in enumerate(node): if i > 0: f.write(',') print_json(f, v) f.write(']') elif isinstance(node, json.Object): f.write('{') for i, (k, v) in enumerate(node): if i > 0: f.write(',') print_json(f, k) f.write(": ") print_json(f, v) f.write('}') root = json.parse(sys.stdin) print_json(sys.stdout, root) If you think that some of the individual strings may be large, you could make the String class implement the iterator interface (or even the file interface with .read() etc), to allow the data to be read incrementally: elif isinstance(node, json.String): f.write('"') for s in node: f.write(s) f.write('"') The main point is to allow the node object to be returned as soon as the type is known, without having to wait until the data has been fully parsed, and to require a separate step (for which there may be various choices) in order to actually retrieve the data. From debatem1 at gmail.com Sat Dec 5 13:37:19 2009 From: debatem1 at gmail.com (geremy condra) Date: Sat, 5 Dec 2009 13:37:19 -0500 Subject: python bijection In-Reply-To: <4b1a4d33$1@dnews.tpgi.com.au> References: <4B193610.6050700@mrabarnett.plus.com> <4b196d1f$1@dnews.tpgi.com.au> <5ac80cf9-d0fc-450e-b8bb-ffef91e81f0a@d10g2000yqh.googlegroups.com> <4b19ace0$1@dnews.tpgi.com.au> <00a37199$0$15659$c3e8da3@news.astraweb.com> <4b1a4d33$1@dnews.tpgi.com.au> Message-ID: On Sat, Dec 5, 2009 at 7:06 AM, Lie Ryan wrote: > On 12/5/2009 4:18 PM, Steven D'Aprano wrote: >>> >>> Tree is better than Graph >>> >>> not having Tree and Graph package in the standard library force most >>> people to find List-based solution. >> >> If you have to be *forced* to use a list-based solution, that's a good >> sign that a list is *not* the right tool for the job. > > Sorry for putting too much emphasis on the "forced", that wasn't my > intention. I was mentioning that often simple problems appeared more complex > because the person was thinking in a higher level data structure than is > necessary. "forced" in that sentence means to let people to think a little > bit harder with list/dict before deciding that they are unsuitable and > moving to a tree or a graph. In any event, I think we can agree that for some tasks (I would say many) a graph or tree is the most suitable data structure. To me, that says that we need to be having a discussion about whether to include those tools in the standard library, and how best to do so if that's the decision. Would you agree? Geremy Condra From holger at merlinux.eu Sat Dec 5 13:37:41 2009 From: holger at merlinux.eu (holger krekel) Date: Sat, 5 Dec 2009 19:37:41 +0100 Subject: execnet-1.0.1: more robust and rapid python deployment Message-ID: <20091205183741.GA13842@trillke.net> Hi everybody, Just uploaded execnet-1.0.1 featuring a new motto: execnet is about rapid-python deployment, be it for multiple CPUs, different platforms or python versions. This release brings a bunch of refinements and most importantly more robust termination, handling of CTRL-C and automatically tested documentation:: http://codespeak.net/execnet have fun, holger 1.0.1 -------------------------------- - revamp and better structure documentation - new method: gateway.hasreceiver() returns True if the gateway is still receive-active. remote_status now only carries information about remote execution status. - new: execnet.MultiChannel provides basic iteration/contain interface - new: execnet.Group can be indexed by integer - new: group.makegateway() uses group.default_spec if no spec is given and the execnet.default_group uses ``popen`` as a default spec. - have popen-gateways use imports instead of source-strings, also improves debugging/tracebacks, as a side effect popen-gateway startup can be substantially faster (>30%) - refine internal gateway exit/termination procedure and introduce group.terminate(timeout) which will attempt to kill all subprocesses that did not terminate within time. - EOFError on channel.receive/waitclose if the other side unexpectedly went away. When a gateway exits it now internally sends an explicit termination message instead of abruptly closing. - introduce a timeout parameter to channel.receive() and default to periodically internally wake up to let KeyboardInterrupts pass through. - EXECNET_DEBUG=2 will cause tracing to go to stderr, which with popen slave gateways will relay back tracing to the instantiator process. 1.0.0 -------------------------------- * introduce execnet.Group for managing gateway creation and termination. Introduce execnet.default_group through which all "global" calls are routed. cleanup gateway termination. All Gateways get an id through which they can be retrieved from a group object. * deprecate execnet.XYZGateway in favour of direct makegateway() calls. * refine socketserver-examples, experimentally introduce a way to indirectly setup a socket server ("installvia") through a gateway url. * refine and automatically test documentation examples 1.0.0b3 -------------------------------- * fix EXECNET_DEBUG to work with win32 * add support for serializing longs, sets and frozensets (thanks Benjamin Peterson) * introduce remote_status() method which on the low level gives information about the remote side of a gateway * disallow explicit close in remote_exec situation * perform some more detailed tracing with EXECNET_DEBUG 1.0.0b2 -------------------------------- * make internal protocols more robust against serialization failures * fix a seralization bug with nested tuples containing empty tuples (thanks to ronny for discovering it) * setting the environment variable EXECNET_DEBUG will generate per process trace-files for debugging 1.0.0b1 ---------------------------- * added new examples for NumPy, Jython, IronPython * improved documentation * include apipkg.py for lazy-importing * integrated new serializer code from Benjamin Peterson * improved support for Jython-2.5.1 1.0.0alpha2 ---------------------------- * improve documentation, new website * use sphinx for documentation, added boilerplate files and setup.py * fixes for standalone usage, adding boilerplate files * imported py/execnet and made it work standalone From benjamin at python.org Sat Dec 5 13:38:31 2009 From: benjamin at python.org (Benjamin Peterson) Date: Sat, 5 Dec 2009 12:38:31 -0600 Subject: [RELEASED] Python 2.7 alpha 1 Message-ID: <1afaf6160912051038r697f3f48r48109624c478d9bc@mail.gmail.com> On behalf of the Python development team, I'm pleased to announce the first alpha release of Python 2.7. Python 2.7 is scheduled to be the last major version in the 2.x series. It includes many features that were first released in Python 3.1. The faster io module, the new nested with statement syntax, improved float repr, and the memoryview object have been backported from 3.1. Other features include an ordered dictionary implementation, unittests improvements, and support for ttk Tile in Tkinter. For a more extensive list of changes in 2.7, see http://doc.python.org/dev/doc/whatsnew/2.7.html or Misc/NEWS in the Python distribution. Please note that this is a development release, intended as a preview of new features for the community, and is thus not suitable for production use. To download Python 2.7 visit: http://www.python.org/download/releases/2.7/ The 2.7 documentation can be found at: http://docs.python.org/2.7 Please consider trying Python 2.7 with your code and reporting any bugs you may notice to: http://bugs.python.org Have fun! -- Benjamin Peterson Release Manager benjamin at python.org (on behalf of the entire python-dev team and 2.7's contributors) From benjamin at python.org Sat Dec 5 13:54:36 2009 From: benjamin at python.org (Benjamin Peterson) Date: Sat, 5 Dec 2009 12:54:36 -0600 Subject: [RELEASED] Python 2.7 alpha 1 In-Reply-To: <1afaf6160912051038r697f3f48r48109624c478d9bc@mail.gmail.com> References: <1afaf6160912051038r697f3f48r48109624c478d9bc@mail.gmail.com> Message-ID: <1afaf6160912051054i3abf3e4fxd17fcfc11d2fde0b@mail.gmail.com> My apologies. The whatsnew link is actually http://docs.python.org/dev/whatsnew/2.7. 2009/12/5 Benjamin Peterson : > On behalf of the Python development team, I'm pleased to announce the first > alpha release of Python 2.7. -- Regards, Benjamin From yair99 at gmail.com Sat Dec 5 14:03:16 2009 From: yair99 at gmail.com (yair reshef) Date: Sat, 5 Dec 2009 21:03:16 +0200 Subject: pywin32 question Message-ID: <1b1605c20912051103r5f17107o9d3a3c5a84559f41@mail.gmail.com> i', looking to create a script that will log all data i drag, click or highlight. i dont think its very chalnging, just a matter of finding the right functions. how/can i detect highlighted text mouse events -------------- next part -------------- An HTML attachment was scrubbed... URL: From aioe.org at technicalbloke.com Sat Dec 5 15:16:41 2009 From: aioe.org at technicalbloke.com (r0g) Date: Sat, 05 Dec 2009 20:16:41 +0000 Subject: How to tell if you're running on windows? References: <96d32eda-e021-4caa-a414-5f25b04b991d@o10g2000yqa.googlegroups.com> Message-ID: Roy Smith wrote: > I'm using 2.5.1. How can I tell if I'm running on windows? The > obvious answer, platform.system(), gets complicated. On the python > that comes with cygwin, it returns 'CYGWIN_NT-5.2-WOW64', but I've got > a native windows build of python where it returns 'Microsoft'. > > The real problem I'm trying to solve is whether to build a LIBPATH > environment variable with ';' or ':' delimiting the entries. On the > cygwin build, os.pathsep returns ':', which isn't really correct. If > you use that, you end up building paths that look like c:foo:c:bar. > It should be c:foo;c:bar Hi, Never used cygwin so I have no idea if this will work for you but I have been using the following... if getattr(sys, "getwindowsversion", None) is None: print "Not on Windows, Whoop! :)" else: print "Oh dear :-/" Roger. From python at rcn.com Sat Dec 5 15:25:48 2009 From: python at rcn.com (Raymond Hettinger) Date: Sat, 5 Dec 2009 12:25:48 -0800 (PST) Subject: Float precision and float equality References: Message-ID: <2f0dee67-6fda-47c0-8266-d2d6b02ed655@e4g2000prn.googlegroups.com> On Dec 5, 7:37?am, Anton81 wrote: > I'd like to do calculations with floats and at some point equality of > two number will be checked. > What is the best way to make sure that equality of floats will be > detected, where I assume that mismatches beyond a certain point are > due to truncation errors? Short answer: use round(). Less short answer: use Decimal with a high precision and then round() or quantize. Long answer: the amount of error depends on the calculation and the scale of the inputs; some calculations potentially propagate tiny errors to the point where they become large enough to overpower the signal in your data (e.g. the Lorentz equation or some other chaotic sequence). Raymond From aioe.org at technicalbloke.com Sat Dec 5 15:35:02 2009 From: aioe.org at technicalbloke.com (r0g) Date: Sat, 05 Dec 2009 20:35:02 +0000 Subject: Question on Python as career References: <614b8dde-324b-4d54-8e73-7a96e4c0b1cf@a21g2000yqc.googlegroups.com> <6fde3200-984a-4948-9f94-6c0f9ebfcc07@r24g2000prf.googlegroups.com> <79474a9d-2def-49ba-9aa5-d5077ed3e695@m33g2000pri.googlegroups.com> Message-ID: TimmyGee wrote: > On Dec 4, 1:08 pm, r0g wrote: >> TimmyGee wrote: >>> On Dec 4, 2:48 am, Grant Edwards wrote: >>>> On 2009-12-03, r0g wrote: >>>>>>> I have done one MA in Linguistics, did a PhD in Natural >>>>>>> Language Processing and doing a Post Doctoral now. ... >>>>>>> After I complete my Post Doctoral which may be only 2-3 months >>>>>>> away, with this knowledge can I join IT? >>>>> Getting involved in an open source project or two may bolster your CV >>>>> and help you get your foot in the door. >>>> Having some real experience would help offset the liability of >>>> having a PhD. >>>> 1/2 ;) >>>> -- >>>> Grant Edwards grante Yow! Eisenhower!! Your >>>> at mimeograph machine upsets >>>> visi.com my stomach!! >>> www.rentacoder.com? >> Euwww, that's not an experience I'd recommend! >> >> Roger. > > Really? I was considering giving it a go one of these days. Not a good > idea? It's OK if you want to work for nothing (by western standards), not use any open source licensed libs and work to design briefs like "Make copy site fo facebook with videos MAx bid: $100". I suppose it might be worth the trouble if you like writing scrapers, cloning other people's websites and don't really need much income from it. Roger. From dickinsm at gmail.com Sat Dec 5 15:56:38 2009 From: dickinsm at gmail.com (Mark Dickinson) Date: Sat, 5 Dec 2009 12:56:38 -0800 (PST) Subject: Float precision and float equality References: <2f0dee67-6fda-47c0-8266-d2d6b02ed655@e4g2000prn.googlegroups.com> Message-ID: <574bd33c-a38b-4af5-802e-fc081965a230@g23g2000vbr.googlegroups.com> On Dec 5, 8:25?pm, Raymond Hettinger wrote: > On Dec 5, 7:37?am, Anton81 wrote: > > > I'd like to do calculations with floats and at some point equality of > > two number will be checked. > > What is the best way to make sure that equality of floats will be > > detected, where I assume that mismatches beyond a certain point are > > due to truncation errors? > > Short answer: use round(). Can you explain how this would work? I'm imagining a test something like: if round(x, 6) == round(y, 6): ... but that still would end up missing some cases where x and y are equal to within 1ulp, which presumably isn't what's wanted: >>> x, y = 0.1234565, 0.123456500000000004 >>> round(x, 6) == round(y, 6) False -- Mark From python at rcn.com Sat Dec 5 16:37:28 2009 From: python at rcn.com (Raymond Hettinger) Date: Sat, 5 Dec 2009 13:37:28 -0800 (PST) Subject: Float precision and float equality References: <2f0dee67-6fda-47c0-8266-d2d6b02ed655@e4g2000prn.googlegroups.com> <574bd33c-a38b-4af5-802e-fc081965a230@g23g2000vbr.googlegroups.com> Message-ID: <6624fc07-c6d5-40e1-a899-6eb73603a980@u8g2000prd.googlegroups.com> On Dec 5, 12:56?pm, Mark Dickinson wrote: > On Dec 5, 8:25?pm, Raymond Hettinger wrote: > > > On Dec 5, 7:37?am, Anton81 wrote: > > > > I'd like to do calculations with floats and at some point equality of > > > two number will be checked. > > > What is the best way to make sure that equality of floats will be > > > detected, where I assume that mismatches beyond a certain point are > > > due to truncation errors? > > > Short answer: use round(). > > Can you explain how this would work? ?I'm imagining a test > something like: > > if round(x, 6) == round(y, 6): ... > > but that still would end up missing some cases where x and y > are equal to within 1ulp, which presumably isn't what's wanted: if not round(x - y, 6): ... Raymond From python at rcn.com Sat Dec 5 16:39:11 2009 From: python at rcn.com (Raymond Hettinger) Date: Sat, 5 Dec 2009 13:39:11 -0800 (PST) Subject: python bijection References: <4B18F685.8050102@egenix.com> <4B193610.6050700@mrabarnett.plus.com> <4b196d1f$1@dnews.tpgi.com.au> <5ac80cf9-d0fc-450e-b8bb-ffef91e81f0a@d10g2000yqh.googlegroups.com> <4b19ace0$1@dnews.tpgi.com.au> Message-ID: <4ec2e9d8-9756-4d16-a439-6c5eb34eb046@k13g2000prh.googlegroups.com> [geremy condra] > I actually considered using dependencies as an example on the > "graphine for pythonistas"[1] article, but decided to do the maze > run instead. In any event, the uses of graphs in general computing > are well enough established that I don't really think that's where > the majority of the difficulty in coming up with something for the > standard library will be- deciding how it should look and behave, > especially in terms of scope and target audience, that's going to > be the difficult part. Right you are :-) > [1]:http://gitorious.org/graphine/pages/GraphineForPythonistas Do you have many users? Raymond From zephjc at gmail.com Sat Dec 5 17:25:17 2009 From: zephjc at gmail.com (zeph) Date: Sat, 5 Dec 2009 14:25:17 -0800 (PST) Subject: How to timeout when waiting for raw_input from user ? References: <55b6b337-fb8f-46b9-a665-108dd19e1dd8@w19g2000pre.googlegroups.com> <52cc49c8-b847-40de-b1ef-1afd2c1ea74c@z7g2000vbl.googlegroups.com> Message-ID: Here's what I came up with, though it only asks once question then quits depending on the answer or lack thereof. And while, yes, you can't interrupt a raw_input call from a timer, providing for a blank line (user hitting enter) is a way around it: import threading import Timer from random import randrange import sys def multiply_game(): a = randrange(1,10) b = randrange(1,10) answer = raw_input('what is %s * %s?: ' % (a,b)) if not answer: return timer.cancel() if str(answer) == str(a * b): print 'right! :D' else: print 'wrong :(' def tooslow(): print "\ntoo slow :(\nHit ENTER to quit" timer = Timer(30, tooslow) # 30 seconds timer.start() multiply_game() From sjmachin at lexicon.net Sat Dec 5 17:42:33 2009 From: sjmachin at lexicon.net (John Machin) Date: Sat, 5 Dec 2009 14:42:33 -0800 (PST) Subject: Why Can't I Delete a File I Created with Win XP? References: Message-ID: <62dbb389-6e6b-42bc-876d-85389784a408@z10g2000prh.googlegroups.com> On Dec 6, 2:46?am, "W. eWatson" wrote: [snip] > ? ? ? ? ?f = file( s, "wb" ) > ? ? ? ? ?if not f: > ? ? ? ? ? ? ?self.LogError( "File creation error 1" ) > ? ? ? ? ? ? ?return False Either you are shadowing the built-in function file() or you haven't tested this code ... file() aka open() returns a file object (which cannot have a "false" value) or it raises an exception; the self.LogError() call can never be executed. > I caused the redundancy by just changing the meaning of s with a new > statement below it. I should have commented the first one out. Yeah, I > probably screwed up here and should have and,for purposes of debugging, > just used another file name like s="ADATAFILE2009_mmdd.txt", which does > not exist at this point of the coding stage. So I should have produced > Analysis\ADATAFILE2009_mmdd.txt. If I had done that then I would have > ended up with an empty file in the Analysis folder. Ever heard the phrase "need to know"? > However, even at > that, why can't I delete this empty file called Analysis? Are you trying to delete the file from another command window while Python is paused at the interactive prompt? In any case describe how you are trying to delete the file. Fire up another command window, cd to whatever is the current working directory for your script, do a dir command, and copy/paste the RELEVANT parts (including all directory names). Please don't top-post, and before you hit the send button, please delete any text that is more appropriate to your memoirs than a problem description. From roy at panix.com Sat Dec 5 18:00:21 2009 From: roy at panix.com (Roy Smith) Date: Sat, 05 Dec 2009 18:00:21 -0500 Subject: TDD with nose or py.test References: <2519ffb0-fd49-4340-857b-62fca5c71421@33g2000vbe.googlegroups.com> Message-ID: In article <2519ffb0-fd49-4340-857b-62fca5c71421 at 33g2000vbe.googlegroups.com>, Lacrima wrote: > Hello! > > I am learning TDD with Python and there is not much information about > this topic. Python is shipped with unittest module. That is fine, but > I also discovered other libraries: nose and py.test. They promise to > make life yet easier for a developer. But I still can't figure out, > which combination I should use them in. > Nose seems simpler than py.test, but py.test offers more features. And > both py.test and nose say that they do not replace unittest module, > but extend it. > So as I understand my choice should be nose + unittest, or py.test + > unittest. > And now I'd like to hear about best practices in TDD in Python. Maybe > not best practices, but basic approach. > So which tests should I write with unittest, which with nose or > py.test? How should I combine them? You're obsessing over details. Pick one and go with it. I've been using unittest for years and I'm mostly happy with it. I've played with py.test a bit, and while I like some features, I keep finding myself wandering back to unittest. Maybe it's just what I know so I'm comfortable with it. I've glanced at nose, but every time I look at it, I ask myself, "Do I want to learn another testing tool, or do I just want to get on with testing the code I'm writing now?", which inevitably brings me back to just sticking with unittest. I am very much a fan of TDD. Whenever I write a new class, here's the first test I write: class TestFoo(unitest.TestCase): def test_construct(self): foo = Foo() If that passes, it means I've managed to create a new class, register it with my build system (and, most likely, my source control system). In keeping with the "write the very smallest amount of code you need to make your test pass", my class will usually look like this at the point the above test first passes: class Foo: pass After that, it's all about adding features :-) From debatem1 at gmail.com Sat Dec 5 18:22:25 2009 From: debatem1 at gmail.com (geremy condra) Date: Sat, 5 Dec 2009 18:22:25 -0500 Subject: python bijection In-Reply-To: <4ec2e9d8-9756-4d16-a439-6c5eb34eb046@k13g2000prh.googlegroups.com> References: <4b196d1f$1@dnews.tpgi.com.au> <5ac80cf9-d0fc-450e-b8bb-ffef91e81f0a@d10g2000yqh.googlegroups.com> <4b19ace0$1@dnews.tpgi.com.au> <4ec2e9d8-9756-4d16-a439-6c5eb34eb046@k13g2000prh.googlegroups.com> Message-ID: On Sat, Dec 5, 2009 at 4:39 PM, Raymond Hettinger wrote: > [geremy condra] >> I actually considered using dependencies as an example on the >> "graphine for pythonistas"[1] article, but decided to do the maze >> run instead. In any event, the uses of graphs in general computing >> are well enough established that I don't really think that's where >> the majority of the difficulty in coming up with something for the >> standard library will be- deciding how it should look and behave, >> especially in terms of scope and target audience, that's going to >> be the difficult part. > > Right you are :-) > > >> [1]:http://gitorious.org/graphine/pages/GraphineForPythonistas > > Do you have many users? I literally have no idea, but I suspect not, seeing as how its a pure python3 project. I get emails about it often enough that I suspect we have about a hundred or so, though, which I'm not unhappy with for a project that focuses on so basic a data structure. Having said that, we always welcome more- and I'd love to have your input on how to make its api more pythonic. Geremy Condra From debatem1 at gmail.com Sat Dec 5 18:25:56 2009 From: debatem1 at gmail.com (geremy condra) Date: Sat, 5 Dec 2009 18:25:56 -0500 Subject: TDD with nose or py.test In-Reply-To: <2519ffb0-fd49-4340-857b-62fca5c71421@33g2000vbe.googlegroups.com> References: <2519ffb0-fd49-4340-857b-62fca5c71421@33g2000vbe.googlegroups.com> Message-ID: On Mon, Nov 30, 2009 at 8:46 AM, Lacrima wrote: > Hello! > > I am learning TDD with Python and there is not much information about > this topic. Python is shipped with unittest module. That is fine, but > I also discovered other libraries: nose and py.test. They promise to > make life yet easier for a developer. But I still can't figure out, > which combination I should use them in. > Nose seems simpler than py.test, but py.test offers more features. And > both py.test and nose say that they do not replace unittest module, > but extend it. > So as I understand my choice should be nose + unittest, or py.test + > unittest. > And now I'd like to hear about best practices in TDD in Python. Maybe > not best practices, but basic approach. > So which tests should I write with unittest, which with nose or > py.test? How should I combine them? > > I am learning Python and I need your advice. > Thanks in advance. > > Sorry if my English isn't very proper I use unittest, but mostly because its so close to junit and cppunit, which I also use extensively. Having said that, it *is* in the standard library and is a common denominator between all your options. Geremy Condra From no.email at nospam.invalid Sat Dec 5 18:37:42 2009 From: no.email at nospam.invalid (Paul Rubin) Date: Sat, 05 Dec 2009 15:37:42 -0800 Subject: TDD with nose or py.test References: <2519ffb0-fd49-4340-857b-62fca5c71421@33g2000vbe.googlegroups.com> Message-ID: <7xmy1xm1q1.fsf@ruckus.brouhaha.com> geremy condra writes: > I use unittest, but mostly because its so close to junit and cppunit, > which I also use extensively. Having said that, it *is* in the standard > library and is a common denominator between all your options. What happened to doctest? From steve at REMOVE-THIS-cybersource.com.au Sat Dec 5 18:43:57 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 05 Dec 2009 23:43:57 GMT Subject: Are routine objects guaranteed mutable & with dictionary? References: <4a2a7fdf-99d4-4219-a56c-7cd9146b3c85@f20g2000prn.googlegroups.com> Message-ID: <00a474c7$0$15659$c3e8da3@news.astraweb.com> On Sat, 05 Dec 2009 11:26:34 +0100, Alf P. Steinbach wrote: > Regarding my terminology, "routine" instead "function" that everybody > except you remarked on, it is of course intentional. [...] I think you failed to realise that your use of the term was ambiguous. It wasn't clear that you were using "routine" as a noun, it seemed like you were using it as an adjective, that is, "routine objects" meaning "ordinary, common objects one would use routinely". Your second example was: (42).blah = 666 (which of course fails, because ints are immutable and you cannot add attributes to them). It isn't surprising that we failed to realise you were talking about callable objects when exactly 50% of your examples were not callable objects. Given the context, I think we were completely justified in thinking that you meant routine in the sense of commonly used. > I use the term "routine" because I think the terminology influences what > we can easily think of and what we therefore tend to use and/or discuss. > In that respect I think people need to be educated to use more language > independent, or Eiffel-like, or just historically original, terminology, > because > > * "function" is misleading in itself (due to the hijacking of this > term in mathematics), and "Function" in the mathematical sense dates back to Leibniz and Johann Bernoulli in the late seventeenth century. I'm not sure, but I think that may have pre-dated computers by a couple of years *wink* http://www.gap-system.org/~history/HistTopics/Functions.html > * it gets worse when you can't reasonably talk about "co-functions" > or "function-like functions". :-) "Co-function" is specifically a mathematical term, from trigonometry. Sine and cosine are co-functions, because they are related via complementary angles: the sine of an angle is equal to the cosine of the complementary angle. That's the only definition Google has found: http://www.google.co.uk/search?q=define%3Aco-function&ie=UTF-8&oe=UTF-8 Webster's dictionary agrees this is the only definition: http://www.merriam-webster.com/dictionary/Cofunction So I have no idea what you think a co-function (or cofunction) is, or why you can't talk about it. As for "function-like functions", I can't think why you would want to use that term! If something is a function, it's obviously function-like, in the same way that cats are cat-like and chairs are chair-like. If you want to talk about "function-like objects", or "function-like data", or "things that behave like functions but aren't actually functions", that is reasonable. We have names for such things: functor (from C++, different from functors in Haskell), or callable, or (verbosely, in Python) "any object with a __call__ method". But function- like functions? That would just be a function. > The devolution of terminology has been so severe that now even the > Wikipedia article on this subject confounds the general concept of > "routine" with the far more specialized term "sub-routine", which is > just one kind of routine. I'm not sure how to reply to that, since I'm not sure what you think a "routine" is in computing. In my experience (which dates back to the early 80s), "routine" has never been anything but a generic term without any specific technical meaning. That is, one might talk about the "print routines" without caring whether they are external programs (say, printer drivers) or internal sub- routines (functions, procedures, co-routines, methods, or even just a chunk of code you GOTO). > It is of course OK with me that there is a > default meaning, and that there are several different context > dependendent meanings. I'm just mentioning this as an example that the > terminology effectively constrains one's thinking, to the degree that > even a moderately long encyclopedia article on the subject fails to > mention or focus on the important aspects. What do you consider the important aspects of routines? > Perhaps modern programmers > should be forced to study Donald Knuth's TAOCP. Or something. Perhaps. But not every car mechanic needs to be able to re-build an engine from scratch. Besides, if every programmer had read Knuth, what reason would we have to feel superior to the code-monkeys? *wink* I've-skimmed-parts-of-Knuth-and-am-therefore-superior-to-99%-of-coders-ly y'rs, -- Steven From postmaster at 127.0.0.1 Sat Dec 5 19:13:59 2009 From: postmaster at 127.0.0.1 (Dr. Marco) Date: 06 Dec 2009 01:13:59 +0100 Subject: High-performance Python websites References: <7cdd7775-0524-4f10-a347-6e79038c821b@a39g2000pre.googlegroups.com> <06d5bca6-8bf6-4f14-96bc-2f5c32b27a40@15g2000prz.googlegroups.com> Message-ID: <87my1xklh4.fsf@free.fr> On Wed, 25 Nov 2009 21:21:25 -0800 (PST), Nick Mellor wrote : Hi, > I wasn't aware that Google used Python for running their Google groups > servers. Can you confirm that? The only place > I've seen Google explicitly use Python on their web front end is in > the Google Ads tests. > > I am impressed by the responsiveness of lawrence.com, ljworld.com and > others on the Django home page (http://www.djangoproject.com/) I'm running two sites using Django which are certainly infinitely more modest and much less visited than the ones you quote but which nevertheless are extremely responsive compared to other frameworks tested, using a single machine (http://nonlineaire.univ-lille1.fr/SNL/ and http://nonlineaire.univ-lille1.fr/GDR3070/). -- Dr. Marco From sturlamolden at yahoo.no Sat Dec 5 19:15:13 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Sat, 5 Dec 2009 16:15:13 -0800 (PST) Subject: Are routine objects guaranteed mutable & with dictionary? References: <4a2a7fdf-99d4-4219-a56c-7cd9146b3c85@f20g2000prn.googlegroups.com> <20091205125501.4932481d@geekmail.INVALID> Message-ID: On 5 Des, 12:55, Andreas Waldenburger wrote: > Can you please elaborate? To me, a function is something that > transforms some input to some output [1]. Which is exactly what Python > functions do, without fail. A mathematical function cannot have side effects. That is what functional languages strive for. However, without allowing side- effects, how can you control hardware (printer, file i/o, etc.)? A Python callable is never a computer science "routine", as it always returns a value. If no value is explicitely returned, it will silently return None. All Python callables are functions. Also in C, calling a void function "routine" is dubious. Fortran and Basic have a destinction between functions and routines, however. From python at rcn.com Sat Dec 5 19:18:58 2009 From: python at rcn.com (Raymond Hettinger) Date: Sat, 5 Dec 2009 16:18:58 -0800 (PST) Subject: python bijection References: <4b196d1f$1@dnews.tpgi.com.au> <5ac80cf9-d0fc-450e-b8bb-ffef91e81f0a@d10g2000yqh.googlegroups.com> <4b19ace0$1@dnews.tpgi.com.au> <4ec2e9d8-9756-4d16-a439-6c5eb34eb046@k13g2000prh.googlegroups.com> Message-ID: <5c5ef54a-c340-4a35-b3a3-6f7307a2e93f@a10g2000pre.googlegroups.com> On Dec 5, 3:22?pm, geremy condra wrote: > On Sat, Dec 5, 2009 at 4:39 PM, Raymond Hettinger wrote: > > [geremy condra] > >> I actually considered using dependencies as an example on the > >> "graphine for pythonistas"[1] article, but decided to do the maze > >> run instead. In any event, the uses of graphs in general computing > >> are well enough established that I don't really think that's where > >> the majority of the difficulty in coming up with something for the > >> standard library will be- deciding how it should look and behave, > >> especially in terms of scope and target audience, that's going to > >> be the difficult part. > > > Right you are :-) > > >> [1]:http://gitorious.org/graphine/pages/GraphineForPythonistas > > > Do you have many users? > > I literally have no idea, but I suspect not, seeing as how its a > pure python3 project. Google's code search can provide a clue. It is also helpful because it let you see typically use cases and whether the API fits well or whether it is awkward to express common use cases. All of those observations will help you tweak the API. Also, it's useful to make similar studies of competing packages either written in Python or in some other langauge. Raymond From sturlamolden at yahoo.no Sat Dec 5 19:31:05 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Sat, 5 Dec 2009 16:31:05 -0800 (PST) Subject: Float precision and float equality References: Message-ID: On 5 Des, 16:37, Anton81 wrote: > I'd like to do calculations with floats and at some point equality of > two number will be checked. > What is the best way to make sure that equality of floats will be > detected, where I assume that mismatches beyond a certain point are > due to truncation errors? isequal = lambda x,y : abs(x-y) < eps where eps is the truncation error. From debatem1 at gmail.com Sat Dec 5 19:49:58 2009 From: debatem1 at gmail.com (geremy condra) Date: Sat, 5 Dec 2009 19:49:58 -0500 Subject: python bijection In-Reply-To: <5c5ef54a-c340-4a35-b3a3-6f7307a2e93f@a10g2000pre.googlegroups.com> References: <4b196d1f$1@dnews.tpgi.com.au> <5ac80cf9-d0fc-450e-b8bb-ffef91e81f0a@d10g2000yqh.googlegroups.com> <4b19ace0$1@dnews.tpgi.com.au> <4ec2e9d8-9756-4d16-a439-6c5eb34eb046@k13g2000prh.googlegroups.com> <5c5ef54a-c340-4a35-b3a3-6f7307a2e93f@a10g2000pre.googlegroups.com> Message-ID: On Sat, Dec 5, 2009 at 7:18 PM, Raymond Hettinger wrote: > On Dec 5, 3:22?pm, geremy condra wrote: >> On Sat, Dec 5, 2009 at 4:39 PM, Raymond Hettinger wrote: >> > [geremy condra] >> >> I actually considered using dependencies as an example on the >> >> "graphine for pythonistas"[1] article, but decided to do the maze >> >> run instead. In any event, the uses of graphs in general computing >> >> are well enough established that I don't really think that's where >> >> the majority of the difficulty in coming up with something for the >> >> standard library will be- deciding how it should look and behave, >> >> especially in terms of scope and target audience, that's going to >> >> be the difficult part. >> >> > Right you are :-) >> >> >> [1]:http://gitorious.org/graphine/pages/GraphineForPythonistas >> >> > Do you have many users? >> >> I literally have no idea, but I suspect not, seeing as how its a >> pure python3 project. > > Google's code search can provide a clue. > It is also helpful because it let you see > typically use cases and whether the API fits well > or whether it is awkward to express common use cases. > All of those observations will help you tweak the API. Unfortunately, judging from the queries I get most of the people interested in the package are using it to study graphs, rather than to write applications using them. That's one of the reasons why I haven't pushed the idea to date- graphine was developed to be useful to other developers, but seems to be mainly used by academics, while networkx seems to be targeted primarily at academics, and is somewhat widely used. I think the ideal situation would be to take projects like graphine and python-graph and develop a hybrid system specifically for the standard library that borrows the strengths of each, but that would involve a lot of developer time for people already heavily invested in their own projects. Having said that, if enough people from the python community got behind it, I think it would happen. > Also, it's useful to make similar studies of competing > packages either written in Python or in some other langauge. I couldn't agree more. Geremy Condra From alfps at start.no Sat Dec 5 20:04:12 2009 From: alfps at start.no (Alf P. Steinbach) Date: Sun, 06 Dec 2009 02:04:12 +0100 Subject: Are routine objects guaranteed mutable & with dictionary? In-Reply-To: <00a474c7$0$15659$c3e8da3@news.astraweb.com> References: <4a2a7fdf-99d4-4219-a56c-7cd9146b3c85@f20g2000prn.googlegroups.com> <00a474c7$0$15659$c3e8da3@news.astraweb.com> Message-ID: * Steven D'Aprano: > On Sat, 05 Dec 2009 11:26:34 +0100, Alf P. Steinbach wrote: > >> Regarding my terminology, "routine" instead "function" that everybody >> except you remarked on, it is of course intentional. [...] > > I think you failed to realise that your use of the term was ambiguous. It > wasn't clear that you were using "routine" as a noun, it seemed like you > were using it as an adjective, that is, "routine objects" meaning > "ordinary, common objects one would use routinely". > > Your second example was: > > (42).blah = 666 > > (which of course fails, because ints are immutable and you cannot add > attributes to them). It isn't surprising that we failed to realise you > were talking about callable objects when exactly 50% of your examples > were not callable objects. One example and one counter example. I can't think of why anyone should lump these together as examples of the same thing. > Given the context, I think we were completely > justified in thinking that you meant routine in the sense of commonly > used. Bah. >> I use the term "routine" because I think the terminology influences what >> we can easily think of and what we therefore tend to use and/or discuss. >> In that respect I think people need to be educated to use more language >> independent, or Eiffel-like, or just historically original, terminology, >> because >> >> * "function" is misleading in itself (due to the hijacking of this >> term in mathematics), and > > "Function" in the mathematical sense dates back to Leibniz and Johann > Bernoulli in the late seventeenth century. I'm not sure, but I think that > may have pre-dated computers by a couple of years *wink* Yes, that was my point. Wink. > http://www.gap-system.org/~history/HistTopics/Functions.html > > >> * it gets worse when you can't reasonably talk about "co-functions" >> or "function-like functions". :-) > > "Co-function" is specifically a mathematical term, from trigonometry. > Sine and cosine are co-functions, because they are related via > complementary angles: the sine of an angle is equal to the cosine of the > complementary angle. > > That's the only definition Google has found: > http://www.google.co.uk/search?q=define%3Aco-function&ie=UTF-8&oe=UTF-8 > > Webster's dictionary agrees this is the only definition: > http://www.merriam-webster.com/dictionary/Cofunction > > So I have no idea what you think a co-function (or cofunction) is, or why > you can't talk about it. Right. That was my point. Wink. Heh heh. :-) Try substituting "routine". That is, s/function/routine/g. > As for "function-like functions", I can't think why you would want to use > that term! See above. ;-) > If something is a function, it's obviously function-like, in > the same way that cats are cat-like and chairs are chair-like. Right, that was my point. Including that with the C/Python terminology it isn't. > If you want to talk about "function-like objects", or "function-like > data", or "things that behave like functions but aren't actually > functions", that is reasonable. We have names for such things: functor > (from C++, different from functors in Haskell), or callable, or > (verbosely, in Python) "any object with a __call__ method". But function- > like functions? That would just be a function. Right. >> The devolution of terminology has been so severe that now even the >> Wikipedia article on this subject confounds the general concept of >> "routine" with the far more specialized term "sub-routine", which is >> just one kind of routine. > > I'm not sure how to reply to that, since I'm not sure what you think a > "routine" is in computing. See the Wikipedia article and allow for some confusion on the part of the authors. Or, if you have TAOCP handy, look it up there. However, you may disregard Donald Knuth's definition of "reel time" :-), I'm not invoking him as an authority on terminology, just a handy accessible source for the general meaning of "routine" (disclaimer: haven't looked it up for this posting, so I can't guarantee that you'll find it, although as I recall in volume I). > In my experience (which dates back to the early 80s), "routine" has never > been anything but a generic term without any specific technical meaning. > That is, one might talk about the "print routines" without caring whether > they are external programs (say, printer drivers) or internal sub- > routines (functions, procedures, co-routines, methods, or even just a > chunk of code you GOTO). Well, my experience is perhaps a bit longer, but not much. And you're on the right track. It's a more general term, *and* it has context dependent meanings. >> It is of course OK with me that there is a >> default meaning, and that there are several different context >> dependendent meanings. I'm just mentioning this as an example that the >> terminology effectively constrains one's thinking, to the degree that >> even a moderately long encyclopedia article on the subject fails to >> mention or focus on the important aspects. > > What do you consider the important aspects of routines? One of the most important aspects is the invocation model. There are many such. Sub-routines and co-routines are the two most common special cases, but for a little more general way of thinking about how routines are invoked and communicate, if you can find a copy of Patrick Henry Winston's "Artificial Intelligence" nearby, as I recall he discussed some other options in a very clear way (illustrated with Lisp examples). >> Perhaps modern programmers >> should be forced to study Donald Knuth's TAOCP. Or something. > > Perhaps. But not every car mechanic needs to be able to re-build an > engine from scratch. > > Besides, if every programmer had read Knuth, what reason would we have to > feel superior to the code-monkeys? *wink* > > I've-skimmed-parts-of-Knuth-and-am-therefore-superior-to-99%-of-coders-ly > y'rs, He he. :-) Cheers, - Alf From dreadpiratejeff at gmail.com Sat Dec 5 20:32:01 2009 From: dreadpiratejeff at gmail.com (J) Date: Sat, 5 Dec 2009 20:32:01 -0500 Subject: Why Can't I Delete a File I Created with Win XP? In-Reply-To: <62dbb389-6e6b-42bc-876d-85389784a408@z10g2000prh.googlegroups.com> References: <62dbb389-6e6b-42bc-876d-85389784a408@z10g2000prh.googlegroups.com> Message-ID: <36dec4ff0912051732j7ff88bb4u7336a1776ed540cd@mail.gmail.com> On Sat, Dec 5, 2009 at 17:42, John Machin wrote: > On Dec 6, 2:46?am, "W. eWatson" wrote: >> However, even at >> that, why can't I delete this empty file called Analysis? > > Are you trying to delete the file from another command window while > Python is paused at the interactive prompt? In any case describe how > you are trying to delete the file. Fire up another command window, cd > to whatever is the current working directory for your script, do a dir > command, and copy/paste the RELEVANT parts (including all directory > names). Please don't top-post, and before you hit the send button, > please delete any text that is more appropriate to your memoirs than a > problem description. I'm no expert in Python, so YMMV and all that, but sounds like, as was mentioned before, that the file isn't being properly closed. I was under the impression that the interpreter would close any open filehandles as part of garbage collection as the script ends and the interpreter closes out... but it's good practice to explicitly close them in any case instead of just assuming that the interpreter or os will do it for you... applicable to any language, not just python. But that being said, this brings to mind a question about this... in *nix, when I can't do something like delete a file or directory, or unmount a filesystem and cant find the cause, I can do an lsof and grep for references to the file/directory in question, then work from there to close anything that still has a lock. Most all of the development work I've ever done (other than C++ and VB.Net) has been done on Linux systems. And honestly, most of my C++ stuff was written/compiled on Linux systems too... so I'm not that experienced with developing applications on windows. Does Windows (XP or later) have an lsof or lsof type tool to show who/what has a lock on a file or folder? I've not found anything like that so far, but as I said, I'm not much of a windows user anyway. I'm at the point where I can actually write useful code in Python, and not just hack my way through to a solution, so this is somethign that would be useful for me to know. I'm about to start work on writing a test tool in Python 2.6 which is going to have to work with a few filehandles, both for read and write actions, as well as socket connections eventually. So being able to find who has a lock on a given file or directory if the program dies unexpectedly would be useful. Cheers Jeff -- Charles de Gaulle - "The better I get to know men, the more I find myself loving dogs." - http://www.brainyquote.com/quotes/authors/c/charles_de_gaulle.html From dreadpiratejeff at gmail.com Sat Dec 5 20:48:27 2009 From: dreadpiratejeff at gmail.com (J) Date: Sat, 5 Dec 2009 20:48:27 -0500 Subject: Why Can't I Delete a File I Created with Win XP? In-Reply-To: <36dec4ff0912051732j7ff88bb4u7336a1776ed540cd@mail.gmail.com> References: <62dbb389-6e6b-42bc-876d-85389784a408@z10g2000prh.googlegroups.com> <36dec4ff0912051732j7ff88bb4u7336a1776ed540cd@mail.gmail.com> Message-ID: <36dec4ff0912051748y2bfd5640sbd93365e74ded4cd@mail.gmail.com> On Sat, Dec 5, 2009 at 20:32, J wrote: > connections eventually. ?So being able to find who has a lock on a > given file or directory if the program dies unexpectedly would be > useful. Google tells me that the program Process Explorer from SysInternals will provide most of the functionality of lsof... so I'll look into that and see if it will work. Certainly will help once I start opening and writing output files with my python scripts on Windows systems... -- Stephen Leacock - "I detest life-insurance agents: they always argue that I shall some day die, which is not so." - http://www.brainyquote.com/quotes/authors/s/stephen_leacock.html From gnarlodious at gmail.com Sat Dec 5 20:56:32 2009 From: gnarlodious at gmail.com (Gnarlodious) Date: Sat, 5 Dec 2009 17:56:32 -0800 (PST) Subject: Can't print Chinese to HTTP References: <4b13c039$0$7478$9b622d9e@news.freenet.de> <8810fcc1-3e2d-42ce-839c-d03774e02ea1@l13g2000yqb.googlegroups.com> <4b153863@dnews.tpgi.com.au> <4b1a3c7a@dnews.tpgi.com.au> Message-ID: <17862af5-15f6-4bd7-b7cb-dee5f390b4ef@s19g2000vbm.googlegroups.com> On Dec 5, 3:54?am, Lie Ryan wrote: > Because of the switch to unicode str, a simple print('?') should've > worked flawlessly if your terminal can accept the character, but the > problem is your terminal does not. There is nothing wrong with Terminal, Mac OSX supports Unicode from one end to the other. The problem is that your code works normally in Terminal but not in a browser. #!/usr/bin/python import sys, io print("Content-type:text/plain;charset=utf-8\n\n") sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8") print("?") The browser shows "Server error", Apache 2 reports error: [error] [client 127.0.0.1] malformed header from script. Bad header= \xe6\x99\x89: test.py So far every way to print Unicode to a browser looks very un-Pythonic. I am just wondering if I have a bug or am missing the right way entirely. -- Gnarlie From wolftracks at invalid.com Sat Dec 5 21:14:31 2009 From: wolftracks at invalid.com (W. eWatson) Date: Sat, 05 Dec 2009 18:14:31 -0800 Subject: Why Can't I Delete a File I Created with Win XP? In-Reply-To: References: <62dbb389-6e6b-42bc-876d-85389784a408@z10g2000prh.googlegroups.com> <36dec4ff0912051732j7ff88bb4u7336a1776ed540cd@mail.gmail.com> Message-ID: J wrote: > On Sat, Dec 5, 2009 at 20:32, J wrote: > >> connections eventually. So being able to find who has a lock on a >> given file or directory if the program dies unexpectedly would be >> useful. > > Google tells me that the program Process Explorer from SysInternals > will provide most of the functionality of lsof... so I'll look into > that and see if it will work. Certainly will help once I start > opening and writing output files with my python scripts on Windows > systems... > > What I'm trying to do is really simple. In the Win XP NG, I have two suggestions to get rid of the Analysis folder and the empty file in it. One is to use a program like you suggested, and the other is to delete it from DOS. I just tried cmd prompt, but was not successful. My DOS skills are long gone, so I have no idea if there is something I overlooked there. I bored down to Analysis and the into it. DIR showed an unnamed empty file, so I tried DEL *. I seriously doubt it was removed. Well, I'm going to reboot sometime later this evening, and knock it out as I described I was able to do once before after a reboot. Thne I'm going to fix the Python program and write a file correctly. From wolftracks at invalid.com Sat Dec 5 21:20:44 2009 From: wolftracks at invalid.com (W. eWatson) Date: Sat, 05 Dec 2009 18:20:44 -0800 Subject: Why Can't I Delete a File I Created with Win XP? In-Reply-To: <62dbb389-6e6b-42bc-876d-85389784a408@z10g2000prh.googlegroups.com> References: <62dbb389-6e6b-42bc-876d-85389784a408@z10g2000prh.googlegroups.com> Message-ID: The original program and code are not mine. I have no idea if that specific piece of code has ever been tested. Generally the program works quite well, and when needed creates the Events folder without any difficulty. That folder is used heavily by writing new data files to it thousands of times over a month. I'm trying to do a very simple thing. I go to the Analysis folder, and try to use Win XP Pro to delete the empty and unnamed file in it. One just does a right-click on the empty file, and then uses Delete. It won't let me delete it. If I back up to the folder level, it won't let me delete the folder, since it's not empty. See the post I made to J moments ago. From dreadpiratejeff at gmail.com Sat Dec 5 21:44:37 2009 From: dreadpiratejeff at gmail.com (J) Date: Sat, 5 Dec 2009 21:44:37 -0500 Subject: Why Can't I Delete a File I Created with Win XP? In-Reply-To: References: <62dbb389-6e6b-42bc-876d-85389784a408@z10g2000prh.googlegroups.com> <36dec4ff0912051732j7ff88bb4u7336a1776ed540cd@mail.gmail.com> Message-ID: <36dec4ff0912051844j5066616dud320813cc1301d35@mail.gmail.com> On Sat, Dec 5, 2009 at 21:14, W. eWatson wrote: > What I'm trying to do is really simple. In the Win XP NG, I have two > suggestions to get rid of the Analysis folder and the empty file in it. One > is to use a program like you suggested, and the other is to delete it from > DOS. I just tried cmd prompt, but was not successful. My DOS skills are long > gone, so I have no idea if there is something I overlooked there. I bored > down to Analysis and the into it. DIR showed an unnamed empty file, so I > tried DEL *. I seriously doubt it was removed. > > Well, I'm going to reboot sometime later this evening, and knock it out as I > described I was able to do once before after a reboot. Thne I'm going to fix > the Python program and write a file correctly. And those are your only options, really. From what I've been able to see, there is no native ability in Linux to actually see who has a lock on a file that's been opened. And I completely understand your frustration. I've not used the process explorer program, so I really can't say how well it works for this kind of thing. But every post I found searching for this indicates that it will at least tell you what still has a lock on the file and maybe then you can figure out what needs to be closed from there. Rebooting should always work in cases like this. Rebooting the system should clear all file locks and is a last resort for a persistent stale file lock. So yeah, by rebooting, you'll always be able to release the lock on that file and then delete it once the system is back and running. However, that's not something you'd want to do on a production system except as a last resort. At least, that's not something that I'd want to do. So anyway, since you said the code is not yours, does the code actually close the files anywhere? I'm assuming that it does at some point, but if not, that really is something that needs to be added in. As I said in my last post, I am just a novice in the Python stuff, but I've written enough code in my life to know that you never assume that a file will be closed properly by the system once the program is finished running. I'm not saying that YOU specifically are doing this, but just making the suggestion as this is the kind of problem that can happen. Of course, a program that's dying for some reason is a different story... :-) -- Mike Ditka - "If God had wanted man to play soccer, he wouldn't have given us arms." - http://www.brainyquote.com/quotes/authors/m/mike_ditka.html From apt.shansen at gmail.com Sat Dec 5 22:19:00 2009 From: apt.shansen at gmail.com (Stephen Hansen) Date: Sat, 5 Dec 2009 19:19:00 -0800 Subject: Why Can't I Delete a File I Created with Win XP? In-Reply-To: References: <62dbb389-6e6b-42bc-876d-85389784a408@z10g2000prh.googlegroups.com> Message-ID: <7a9c25c20912051919l574378d3oe444d07a18e425e5@mail.gmail.com> On Sat, Dec 5, 2009 at 6:20 PM, W. eWatson wrote: > I'm trying to do a very simple thing. I go to the Analysis folder, and try > to use Win XP Pro to delete the empty and unnamed file in it. One just does > a right-click on the empty file, and then uses Delete. It won't let me > delete it. If I back up to the folder level, it won't let me delete the > folder, since it's not empty. See the post I made to J moments ago. > > As has been said by various people: you have to close the file in the code. You aren't doing so, so you can't go delete the file. There's really nothing at all to this otherwise-- this isn't really even a python thing. In windows, as long as a file is held open, you can't delete a file. When a program closes it almost always ends up automatically closing all the files it had open-- so if you're not seeing that, the program is not being closed (or it launched another program which inherited the file handles). You can go manually use task manager to kill any program which might be holding a handle, or if you don't know which-- log off and log back on will almost certainly get them all. Failing that, reboot. There's really nothing to this. Close the file when you're done using it, and you'll be able to delete it fine. --S -------------- next part -------------- An HTML attachment was scrubbed... URL: From tomslists at netp.org Sat Dec 5 23:13:11 2009 From: tomslists at netp.org (Tom Pacheco) Date: Sat, 05 Dec 2009 23:13:11 -0500 Subject: Why Can't I Delete a File I Created with Win XP? In-Reply-To: References: Message-ID: <4B1B2F57.8080007@netp.org> W. eWatson wrote: > I'm trying to store analytic data in a folder called Analysis. If the > user doesn't have the folder, I make one for him, and then write a txt > file into it. In this case a histogram of values, x and frequency. > However, it appears that I made a mistake somewhere and cannot delete > it using the Win XP delete. Here's the code that determines if > Analysis exists, and whether to create it. > > print "Path for Histogram", self.current_path > s = self.current_path > s = "Analysis" > s = os.path.join("Analysis",s) > print "s joined ",s <------------- debug print > if not os.path.exists("Analysis"): > os.mkdir("Analysis") > f = file( s, "wb") > if not f: > self.LogError( "Histogram file creation error 1" ) > return False > > In writing the code to handle all of this, I forgot to write the txt > folder to the file, nor did I close it. It was someone else's code, > and I got caught up in the creation of Analysis. Here's what XP tells > me when I try to delete the folder. > > Very funny. I just tried it to get the content of the msg, and XP > deleted it. Let me recreate it and try again. OK, here it is: > > Error Deleting Folder or File. > Cannot delete Analysis: It is being used by another person or program. > Close programs that might be using it and try again. > > There is no file created, just the folders Analysis\Analysis. One too > many. The second Analysis shows as an icon for a file of size 0KB. > > I printed with the debug print above: > Path for Histogram Events\v20070206_055012.06.dat > s joined Analysis\Analysis > Analysis\Analysis should only be Analysis. noticed your assigning the same variable twice ------------------------------- s = self.current_path s = "Analysis" ------------------------------- if you are expecting Analysis\Events\v20070206_055012.06.dat delete the second line as others have said if you can not delete the file if must still be open. why are you talking about deleting a file but only show code for opening it? From wolftracks at invalid.com Sat Dec 5 23:17:41 2009 From: wolftracks at invalid.com (W. eWatson) Date: Sat, 05 Dec 2009 20:17:41 -0800 Subject: Why Can't I Delete a File I Created with Win XP? In-Reply-To: References: <62dbb389-6e6b-42bc-876d-85389784a408@z10g2000prh.googlegroups.com> <36dec4ff0912051732j7ff88bb4u7336a1776ed540cd@mail.gmail.com> Message-ID: J wrote: > On Sat, Dec 5, 2009 at 21:14, W. eWatson wrote: > >> What I'm trying to do is really simple. In the Win XP NG, I have two >> suggestions to get rid of the Analysis folder and the empty file in it. One >> is to use a program like you suggested, and the other is to delete it from >> DOS. I just tried cmd prompt, but was not successful. My DOS skills are long >> gone, so I have no idea if there is something I overlooked there. I bored >> down to Analysis and the into it. DIR showed an unnamed empty file, so I >> tried DEL *. I seriously doubt it was removed. >> >> Well, I'm going to reboot sometime later this evening, and knock it out as I >> described I was able to do once before after a reboot. Thne I'm going to fix >> the Python program and write a file correctly. > > And those are your only options, really. From what I've been able to > see, there is no native ability in Linux to actually see who has a > lock on a file that's been opened. And I completely understand your > frustration. > > I've not used the process explorer program, so I really can't say how > well it works for this kind of thing. But every post I found > searching for this indicates that it will at least tell you what still > has a lock on the file and maybe then you can figure out what needs to > be closed from there. > > Rebooting should always work in cases like this. Rebooting the system > should clear all file locks and is a last resort for a persistent > stale file lock. So yeah, by rebooting, you'll always be able to > release the lock on that file and then delete it once the system is > back and running. > > However, that's not something you'd want to do on a production system > except as a last resort. At least, that's not something that I'd want > to do. > > So anyway, since you said the code is not yours, does the code > actually close the files anywhere? I'm assuming that it does at some > point, but if not, that really is something that needs to be added in. > As I said in my last post, I am just a novice in the Python stuff, > but I've written enough code in my life to know that you never assume > that a file will be closed properly by the system once the program is > finished running. I'm not saying that YOU specifically are doing > this, but just making the suggestion as this is the kind of problem > that can happen. > > Of course, a program that's dying for some reason is a different story... :-) Well, I'm pretty well done now. I fixed the program so it would write the file and close it. It did this successfully. I'll worry about getting the oddball file deleted later. From dreadpiratejeff at gmail.com Sat Dec 5 23:43:25 2009 From: dreadpiratejeff at gmail.com (J) Date: Sat, 5 Dec 2009 23:43:25 -0500 Subject: Why Can't I Delete a File I Created with Win XP? In-Reply-To: References: <62dbb389-6e6b-42bc-876d-85389784a408@z10g2000prh.googlegroups.com> <36dec4ff0912051732j7ff88bb4u7336a1776ed540cd@mail.gmail.com> Message-ID: <36dec4ff0912052043w2981e92fu40b395864f3cd3bd@mail.gmail.com> On Sat, Dec 5, 2009 at 23:17, W. eWatson wrote: > J wrote: >> And those are your only options, really. ?From what I've been able to >> see, there is no native ability in Linux to actually see who has a >> lock on a file that's been opened. ?And I completely understand your >> frustration. Crud.. that should have said no native ability in Windows... not Linux... > Well, I'm pretty well done now. I fixed the program so it would write the > file and close it. It did this successfully. I'll worry about getting the > oddball file deleted later. Cool. Glad you got it worked out... good luck! -- Joan Crawford - "I, Joan Crawford, I believe in the dollar. Everything I earn, I spend." - http://www.brainyquote.com/quotes/authors/j/joan_crawford.html From debatem1 at gmail.com Sun Dec 6 00:04:28 2009 From: debatem1 at gmail.com (geremy condra) Date: Sun, 6 Dec 2009 00:04:28 -0500 Subject: TDD with nose or py.test In-Reply-To: <7xmy1xm1q1.fsf@ruckus.brouhaha.com> References: <2519ffb0-fd49-4340-857b-62fca5c71421@33g2000vbe.googlegroups.com> <7xmy1xm1q1.fsf@ruckus.brouhaha.com> Message-ID: On Sat, Dec 5, 2009 at 6:37 PM, Paul Rubin wrote: > geremy condra writes: >> I use unittest, but mostly because its so close to junit and cppunit, >> which I also use extensively. Having said that, it *is* in the standard >> library and is a common denominator between all your options. > > What happened to doctest? Worth mentioning as an option, I suppose, but at least for me unittest fits the TDD workflow better. YMMV, of course. Geremy Condra From wolftracks at invalid.com Sun Dec 6 00:38:25 2009 From: wolftracks at invalid.com (W. eWatson) Date: Sat, 05 Dec 2009 21:38:25 -0800 Subject: Why Doesn't XP Pro Show Size, Time and Date Mod of a Created File? Message-ID: I created a folder, and wrote a file to it. When I look at what files are in it, they are correct. However, The Size, Type, and Date Mod are not shown. Why am I missing those columns? I'm writing files with a suffix of dat, which seem only to match up with video CD movie. From mensanator at aol.com Sun Dec 6 01:07:44 2009 From: mensanator at aol.com (Mensanator) Date: Sat, 5 Dec 2009 22:07:44 -0800 (PST) Subject: Why Doesn't XP Pro Show Size, Time and Date Mod of a Created File? References: Message-ID: <0ceab209-dd73-4c5e-88a4-f550747c13b1@o23g2000vbi.googlegroups.com> On Dec 5, 11:38?pm, "W. eWatson" wrote: > I created a folder, and wrote a file to it. When I look at what files > are in it, they are correct. However, The Size, Type, and Date Mod are > not shown. Why am I missing those columns? I'm writing files with a > suffix of dat, which seem only to match up with video CD movie. Got to the View menu and select Details. Once in the Details view, click on the column headings and select which details to view. From pfeldman at verizon.net Sun Dec 6 02:04:42 2009 From: pfeldman at verizon.net (Dr. Phillip M. Feldman) Date: Sat, 5 Dec 2009 23:04:42 -0800 (PST) Subject: How to create a docstring for a module? Message-ID: <26662729.post@talk.nabble.com> If I create a module xyz.py with a docstring """xyz does everything you could possibly want.""" at the top, the command ?xyz issued at the IPython prompt does not display this docstring. What am I doing wrong? -- View this message in context: http://old.nabble.com/How-to-create-a-docstring-for-a-module--tp26662729p26662729.html Sent from the Python - python-list mailing list archive at Nabble.com. From timr at probo.com Sun Dec 6 02:15:50 2009 From: timr at probo.com (Tim Roberts) Date: Sat, 05 Dec 2009 23:15:50 -0800 Subject: Organization of GUIs References: <424dcb65-735c-4779-ae0a-5c4e662b24ac@b36g2000prf.googlegroups.com> Message-ID: <0ammh5pdn3nj7phjj8m3ghvp56j1k0nvic@4ax.com> Michael Mossey wrote: > >I am now wondering if I should write a GUI so that everything is in a >true hierarchy, rather than a tangle of objects with democratic >relationships---and more specifically, that messages (which may cause >state to be changed in the receiver of the message) should first go up >the hierarchy until they reach the right level, and then down to the >ultimate receiver of the message. This way a parent object in the >hierarchy has complete visibility and control of messages passing >between its children, leading to the possibility of consolidating the >code and documentation about the children's mutability in one place >(the parent). There are practical considerations here that make such a pure arrangement difficult. For example, consider a relatively complicated dialog GUI, with several sub-frames, maybe a splitter, couple of group boxes, containing edit boxes and buttons, etc. Now, consider what happens when a button gets pressed. Usually, you want to take some action that is global to the whole dialog. The button will see the mouse down and mouse up messages, but it doesn't know what ACTION should be taken. It's possible to handle that, but each layer has to know about "notifications", and has to be able to hand "notifications" up the hierarchy tree until it gets to someone who knows what to do about it. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From lie.1296 at gmail.com Sun Dec 6 02:15:58 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Sun, 06 Dec 2009 18:15:58 +1100 Subject: Can't print Chinese to HTTP In-Reply-To: <17862af5-15f6-4bd7-b7cb-dee5f390b4ef@s19g2000vbm.googlegroups.com> References: <4b13c039$0$7478$9b622d9e@news.freenet.de> <8810fcc1-3e2d-42ce-839c-d03774e02ea1@l13g2000yqb.googlegroups.com> <4b153863@dnews.tpgi.com.au> <4b1a3c7a@dnews.tpgi.com.au> <17862af5-15f6-4bd7-b7cb-dee5f390b4ef@s19g2000vbm.googlegroups.com> Message-ID: <4b1b5aac$1@dnews.tpgi.com.au> On 12/6/2009 12:56 PM, Gnarlodious wrote: > On Dec 5, 3:54 am, Lie Ryan wrote: > >> Because of the switch to unicode str, a simple print('?') should've >> worked flawlessly if your terminal can accept the character, but the >> problem is your terminal does not. > > There is nothing wrong with Terminal, Mac OSX supports Unicode from > one end to the other. > The problem is that your code works normally in Terminal but not in a > browser. > > #!/usr/bin/python > import sys, io > print("Content-type:text/plain;charset=utf-8\n\n") > sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8") > print("?") > > The browser shows "Server error", Apache 2 reports error: > > [error] [client 127.0.0.1] malformed header from script. Bad header= > \xe6\x99\x89: test.py I've already posted before for some reason it is not possible to mix writing using print() and sys.stdout.buffer. On my machine, the output got mixed up: -------------------------- ? Content-type:text/plain;charset=utf-8 -------------------------- notice that the chinese character is on top of the header. I guess this is due to the buffering from print. > So far every way to print Unicode to a browser looks very un-Pythonic. > I am just wondering if I have a bug or am missing the right way > entirely. My *guess* is Apache does not request a utf-8 stdout. When run on the Terminal, the Terminal requested utf-8 stdout from python and the script runs correctly. I'm not too familiar with Apache's internal nor how python 3 figured its stdout's encoding, you might want to find Apache's mailing list if they have any similar case. PS: You might also want to look at this: http://stackoverflow.com/questions/984014/python-3-is-using-sys-stdout-buffer-write-good-style it says to try setting your PYTHONIOENCODING environment variable to "utf8" From timr at probo.com Sun Dec 6 02:18:37 2009 From: timr at probo.com (Tim Roberts) Date: Sat, 05 Dec 2009 23:18:37 -0800 Subject: Socket question References: <4B17D0BF.7070000@gmail.com> <20091203152807.2549.1165382253.divmod.xquotient.117@localhost.localdomain> Message-ID: perlsyntax wrote: > >I just want to know could it be done makeing my own socket tool that >connect to two server at the same time.And what link do i need to look at? You can certainly connect to two (or any number) servers at the same time, but you have to create two sockets to do it. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From yinon.me at gmail.com Sun Dec 6 02:21:33 2009 From: yinon.me at gmail.com (Yinon Ehrlich) Date: Sat, 5 Dec 2009 23:21:33 -0800 (PST) Subject: subprocess kill References: <5f755846-e79d-444b-b608-86f5823540e8@j19g2000yqk.googlegroups.com> <68cd2042-cd2a-43a8-97ae-2893f181168c@c3g2000yqd.googlegroups.com> <011ae123-d777-438c-83b6-f6600c1dfde1@m25g2000yqc.googlegroups.com> <786e4fb7-1f03-45d5-9be0-55926387283f@s20g2000yqd.googlegroups.com> Message-ID: On Dec 5, 12:13?pm, luca72 wrote: > On 5 Dic, 03:06, Carl Banks wrote: > > > > > On Dec 4, 3:44?pm, luca72 wrote: > > > > On 5 Dic, 00:14, luca72 wrote: > > > > > On 5 Dic, 00:03, luca72 wrote: > > > > > > On 4 Dic, 23:23, Mike Driscoll wrote: > > > > > > > On Dec 4, 3:50?pm, luca72 wrote: > > > > > > > > Hello i'm using subprocess in this way: > > > > > > > self.luca = subprocess.Popen(['/usr/bin/ > > > > > > > dvbtune'+frase_sint],shell=True, stdout=self.f_s_l,stderr=self.f_s_e ) > > > > > > > > then i kill: > > > > > > > self.luca.Kill() > > > > > > > > but the process is still active and the file self.f_s_l increase it > > > > > > > size because the process is not killed. > > > > > > > > How i can kill the process? > > > > > > > Regards > > > > > > > > Luca > > > > > > > Seehttp://lmgtfy.com/?q=python+kill+subprocess+linux > > > > > > > When I do that on my machine, the 2nd result has the answer: > > > > > > >http://stackoverflow.com/questions/1064335/in-python-2-5-how-do-i-kil... > > > > > > > ------------------- > > > > > > Mike Driscoll > > > > > > > Blog: ?http://blog.pythonlibrary.org > > > > > > Hello Mike i have also test but they never kill the process the file > > > > > (stdout=self.f_s_l) increase it's size, haveyou some idea. > > > > > also if i close the program the process is still active. > > > > > > Regards > > > > > > Luca > > > > > i'm able only to kill via shell like kill -9 process pid, Why? > > > > Now the only way to solve the problem is to call a c program that kill > > > the process via subprocess in other case i can't close it, i have also > > > try with > > > > subprocess.Popen(['kill -9 dvbtune'] shell=True), but the process is > > > still active > > > This is not working because the kill command does not accept the name > > of a program. ?You have to give it a process id. > > > As for your general question, we really can't answer it. ?There a lot > > of reasons a process might not die when you try to kill it: it could > > be trapping and ignoring signals (which is rude but it happens), it > > could be stuck in a critical section, the program might be threaded > > and not handling signals well, the program might have forked itself > > and the original process id has disappeared, etc. ?We can't read your > > mind or divine what's running on your computer, so we can't answer > > your question. ?We can only suggest things that might be wrong. ?It's > > up to you to investigate and/or dig deeper. > > > Carl Banks > > The firs thing that i have tested is with the process id get by > Popen.pid ,but it don't works. > Thanks I guess you run python > 2.6 (Popen.kill is new in Python 2.6) You may try terminate (http://docs.python.org/library/ subprocess.html#subprocess.Popen.terminate) or the following wrapper - good for older pythons too as well as killing group of processes: http://benjamin.smedbergs.us/blog/2006-12-11/killableprocesspy/ -- Yinon From yinon.me at gmail.com Sun Dec 6 02:29:43 2009 From: yinon.me at gmail.com (Yinon Ehrlich) Date: Sat, 5 Dec 2009 23:29:43 -0800 (PST) Subject: how to debug extended module? References: <7nk54jF3m6bppU1@mid.uni-berlin.de> <88d05d38-1879-4cdf-92b5-2edb6192b10e@g26g2000yqe.googlegroups.com> <239d0346-cf19-41a5-ad65-7261149e0634@e4g2000prn.googlegroups.com> Message-ID: <6a074154-b79d-4416-860d-cef9d88f9f60@n31g2000vbt.googlegroups.com> On Dec 3, 8:40 am, junyoung wrote: > On 12?2?, ??9?54?, junyoung wrote: > > > > > On 12?1?, ??6?14?, "Diez B. Roggisch" wrote: > > > > junyoung schrieb: > > > > > Hi, I am a newbie who want to implement a extend module to use native > > > > python language with my own shared library. > > > > If it's a C shared library, don't bother extending it. Use ctypes to > > > wrap it. Much easier, and no need for a compiler. > > > > > to test wrapper library(extend module, name is 'test.so'), I created > > > > some test-cases. > > > > > There are some errors what I couldn't figure our reasons. > > > > > ex) > > > > SystemError: error return without exception set > > > > .... > > > > ... > > > > This indicates that you violated the exception protocol. > > > >http://docs.python.org/c-api/exceptions.html > > > > > so, I ran the ddd with python and then I set test.py as a argument of > > > > it. > > > > > ex) > > > > ddd python > > > > > in ddd > > > > run with arguments : test.py > > > > > but in this situation, I couldn't step in my own shared library > > > > (compiled as the debug mode). > > > > > Is there any clear way to debug my extend module(that it, debug shared > > > > library)?? > > > > I do it like this: > > > > # gdb python > > > gdb $ set args test.py > > > gdb $ run > > > > You can only debug a binary program (test.py isn't one, python is). But > > > trough the args, you get yours script running. > > > > It *might* help to have a python debug build, I personally never needed > > > that. > > > > Diez > > > here is my results. anyway, check this out. > > > (gdb) set args connect.py > > set args connect.py > > (gdb) run > > run > > Starting program: /usr/bin/python connect.py > > (no debugging symbols found) > > (no debugging symbols found) > > (no debugging symbols found) > > [Thread debugging using libthread_db enabled] > > (no debugging symbols found) > > (no debugging symbols found) > > (no debugging symbols found) > > (no debugging symbols found) > > [New Thread 0x7f619747e6e0 (LWP 23683)] > > (no debugging symbols found) > > (no debugging symbols found) > > (no debugging symbols found) > > (no debugging symbols found) > > [New Thread 0x415a9950 (LWP 23686)] > > [Thread 0x415a9950 (LWP 23686) exited] > > [New Thread 0x415a9950 (LWP 23687)] > > [Thread 0x415a9950 (LWP 23687) exited] > > Traceback (most recent call last): > > File "connect.py", line 25, in > > main() > > File "connect.py", line 18, in main > > connection_test() > > File "connect.py", line 15, in connection_test > > cnxn.close() > > SystemError: error return without exception set > > > Program exited with code 01. > > (gdb) > > > as you see, I can't load symbol table information from gdb. > > > now python is defaulted installed as release. > > > my os is ubuntu > > the python is installed in /usr/bin > > the python version is 2.5.1 > > > do i need to re-install python as debug mode? > > after compiling it(python) as debug mode, I could debug it ;( > > I don't still know why I have to compile it as debug mode to step in > my own library. interesting.... BTW: No need to compile, just 'apt-get install python-dbg' From timr at probo.com Sun Dec 6 02:42:28 2009 From: timr at probo.com (Tim Roberts) Date: Sat, 05 Dec 2009 23:42:28 -0800 Subject: Float precision and float equality References: <2f0dee67-6fda-47c0-8266-d2d6b02ed655@e4g2000prn.googlegroups.com> <574bd33c-a38b-4af5-802e-fc081965a230@g23g2000vbr.googlegroups.com> <6624fc07-c6d5-40e1-a899-6eb73603a980@u8g2000prd.googlegroups.com> Message-ID: Raymond Hettinger wrote: > > if not round(x - y, 6): ... That's a dangerous suggestion. It only works if x and y happen to be roughly in the range of integers. For example, here x and y are within roundoff error of each other, but round doesn't know it: >>> x=1e32 >>> y=x+1e16 >>> x-y -18014398509481984.0 >>> round(x-y,6) -18014398509481984.0 It fails in the other direction when the numbers are small: >>> x=.0000000123 >>> y=.0000000234 >>> x-y -1.1100000000000002e-008 >>> round(x-y,6) 0.0 Mark's solution is the generically correct one, which takes into account the rough range of the values. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From zephjc at gmail.com Sun Dec 6 02:50:00 2009 From: zephjc at gmail.com (zeph) Date: Sat, 5 Dec 2009 23:50:00 -0800 (PST) Subject: Organization of GUIs References: <424dcb65-735c-4779-ae0a-5c4e662b24ac@b36g2000prf.googlegroups.com> Message-ID: <6d83fec3-ad8d-43d3-ada6-18ff3d189aed@2g2000prl.googlegroups.com> I highly recommend reading the Cocoa documentation, which has volumes on all sorts of things like this. Here's a link that talks about views in that context, and should give you more ideas about well- designed GUI layouts: http://bit.ly/6b8PYh From python at rcn.com Sun Dec 6 04:12:18 2009 From: python at rcn.com (Raymond Hettinger) Date: Sun, 6 Dec 2009 01:12:18 -0800 (PST) Subject: Float precision and float equality References: <2f0dee67-6fda-47c0-8266-d2d6b02ed655@e4g2000prn.googlegroups.com> <574bd33c-a38b-4af5-802e-fc081965a230@g23g2000vbr.googlegroups.com> <6624fc07-c6d5-40e1-a899-6eb73603a980@u8g2000prd.googlegroups.com> Message-ID: <335cb11d-e862-4daa-aec6-8f96b56bc28a@u1g2000pre.googlegroups.com> On Dec 5, 11:42?pm, Tim Roberts wrote: > Raymond Hettinger wrote: > > > ? if not round(x - y, 6): ... > > That's a dangerous suggestion. ?It only works if x and y happen to be > roughly in the range of integers. Right. Using abs(x-y) < eps is the way to go. Raymond From usenot at geekmail.INVALID Sun Dec 6 04:55:50 2009 From: usenot at geekmail.INVALID (Andreas Waldenburger) Date: Sun, 6 Dec 2009 10:55:50 +0100 Subject: How to create a docstring for a module? References: Message-ID: <20091206105550.16570a30@geekmail.INVALID> On Sat, 5 Dec 2009 23:04:42 -0800 (PST) "Dr. Phillip M. Feldman" wrote: > > If I create a module xyz.py with a docstring """xyz does everything > you could possibly want.""" at the top, the command ?xyz issued at > the IPython prompt does not display this docstring. What am I doing > wrong? Stab in the dark: You have imported the module first, right? Also: Never, EVER, ask a question like this on any technical forum without posting your code (or rather: a minimal version of it that still exhibits the problem). That way, people can help you directly instead of taking wild guesses at what your problem might be. /W -- INVALID? DE! From davea at ieee.org Sun Dec 6 05:22:48 2009 From: davea at ieee.org (Dave Angel) Date: Sun, 06 Dec 2009 05:22:48 -0500 Subject: Can't print Chinese to HTTP In-Reply-To: <17862af5-15f6-4bd7-b7cb-dee5f390b4ef@s19g2000vbm.googlegroups.com> References: <4b13c039$0$7478$9b622d9e@news.freenet.de> <8810fcc1-3e2d-42ce-839c-d03774e02ea1@l13g2000yqb.googlegroups.com> <4b153863@dnews.tpgi.com.au> <4b1a3c7a@dnews.tpgi.com.au> <17862af5-15f6-4bd7-b7cb-dee5f390b4ef@s19g2000vbm.googlegroups.com> Message-ID: <4B1B85F8.90208@ieee.org> Gnarlodious wrote: > On Dec 5, 3:54 am, Lie Ryan wrote: > > >> Because of the switch to unicode str, a simple print('?') should've >> worked flawlessly if your terminal can accept the character, but the >> problem is your terminal does not. >> > > There is nothing wrong with Terminal, Mac OSX supports Unicode from > one end to the other. > The problem is that your code works normally in Terminal but not in a > browser. > > #!/usr/bin/python > import sys, io > print("Content-type:text/plain;charset=f-8\n\n") > sys.stdout =o.TextIOWrapper(sys.stdout.buffer, encoding="utf-8") > print("?") > > The browser shows "Server error", Apache 2 reports error: > > [error] [client 127.0.0.1] malformed header from script. Bad header\xe6\x99\x89: test.py > > So far every way to print Unicode to a browser looks very un-Pythonic. > I am just wondering if I have a bug or am missing the right way > entirely. > > -- Gnarlie > > You change the meaning of sys.stdout without flushing the previous instance. So of course buffering can mess you up. If you want to change the encoding, do it at the beginning of the script. #!/usr/bin/python import sys, io sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8") print("Content-type:text/plain;charset=f-8\n\n") print("?") (You probably could use sys.stdout.flush() before reassigning, but doing it at the beginning is better for several reasons.) DaveA From steve at REMOVE-THIS-cybersource.com.au Sun Dec 6 05:36:34 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 06 Dec 2009 10:36:34 GMT Subject: How to create a docstring for a module? References: <20091206105550.16570a30@geekmail.INVALID> Message-ID: <00a50dbe$0$15659$c3e8da3@news.astraweb.com> On Sun, 06 Dec 2009 10:55:50 +0100, Andreas Waldenburger wrote: > On Sat, 5 Dec 2009 23:04:42 -0800 (PST) "Dr. Phillip M. Feldman" > wrote: > > >> If I create a module xyz.py with a docstring """xyz does everything you >> could possibly want.""" at the top, the command ?xyz issued at the >> IPython prompt does not display this docstring. What am I doing wrong? > > Stab in the dark: You have imported the module first, right? > > Also: Never, EVER, ask a question like this on any technical forum > without posting your code (or rather: a minimal version of it that still > exhibits the problem). That way, people can help you directly instead of > taking wild guesses at what your problem might be. In fairness, Phillip's description of the problem is pretty straight- forward: he has a module xyz.py with a docstring. The minimal version of the code is no code at all, just a docstring: """xyz does everything you could possibly want.""" His problem isn't an error when running the code, but an error with IPython's command ?xyz. What he didn't say is what IPython prints instead of the expected docstring. Over to you Phillip, don't just tell us what IPython doesn't do, tell us what it does do. My guesses are: * He hasn't imported the module, so he gets an error of some sort. * He hasn't actually defined a docstring. Docstrings have to be string literals, you can't do this: """%s does everything you could possibly want.""" % "xyz" Nor can you have anything except comments and whitespace between the top of the module and the string. * He has another module called xyz which is shadowing the module he expects, and so he sees that module's docstring instead. -- Steven From irmen.NOSPAM at xs4all.nl Sun Dec 6 06:34:55 2009 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Sun, 06 Dec 2009 12:34:55 +0100 Subject: Exception classes don't follow pickle protocol, problems unpickling Message-ID: <4b1b96e2$0$22938$e4fe514c@news.xs4all.nl> Hi, I am puzzled why Python's exception classes don't seem to follow the pickle protocol. To be more specific: an instance of a user defined exception, subclassed from Exception, cannot be pickled/unpickled correctly in the expected way. The pickle protocol says that: __getinitargs__ is used if you want __init__ to be called for old-style classes __getnewargs__ is used if you want to pass params to __new__ for new-style classes __getstate__ is used to determine what to pickle instead of the objects __dict__ None of these are used when pickling Exception objects! I've pasted some test code at the end of this message that creates a normal object and an object derived from Exception, and pickles them both. Then it unpickles them. The output is: creating MyObj myobj init: bla creating MyEx myex init: foutje pickle myobj myobj getnewargs # <-- great, newargs is used because of new style class myobj getstate # getstate as well pickle myex unpickling MyObj # <-- huh?? where are getnewargs/getinitargs/getstate? unpickled MyObj: [MyObj 'bla'] unpickling MyEx Traceback (most recent call last): File "ex.py", line 49, in o=pickle.loads(p_myex) TypeError: ('__init__() takes exactly 2 arguments (1 given)', , ()) So there are 2 problems: the pickle protocol isn't used when exception objects (or instances of classes derived from Exception) are pickled, and during unpickling, it then crashes because it calls __init__ with the wrong amount of parameters. (why is it bothering with __init__ anyway? Aren't exceptions new style classes?) This started happening in Python 2.5, Python 2.4 works without error. What is causing this? How can I best solve this error? (using pickle instead of cPickle and changing the protocol number doesn't help). --irmen ~~~~code follows~~~~ import cPickle as pickle class MyObj(object): def __init__(self, mymessage): print "myobj init:",mymessage self.mymessage=mymessage def __str__(self): return "[MyObj '%s']" % self.mymessage def __getinitargs__(self): print "myobj getinitargs" return (self.mymessage,) def __getnewargs__(self): print "myobj getnewargs" return (self.mymessage,) def __getstate__(self): print "myobj getstate" return {"mymessage":self.mymessage} class MyEx(Exception): def __init__(self, mymessage): print "myex init:",mymessage self.mymessage=mymessage def __str__(self): return "[MyEx '%s']" % self.mymessage def __getinitargs__(self): print "myex getinitargs" return (self.mymessage,) def __getnewargs__(self): print "myex getnewargs" return (self.mymessage,) def __getstate__(self): print "myex getstate" return {"mymessage":self.mymessage} print "creating MyObj" myobj=MyObj("bla") print "creating MyEx" myex=MyEx("foutje") print "pickle myobj" p_myobj=pickle.dumps(myobj,protocol=pickle.HIGHEST_PROTOCOL) print "pickle myex" p_myex=pickle.dumps(myex,protocol=pickle.HIGHEST_PROTOCOL) print "unpickling MyObj" o=pickle.loads(p_myobj) print "unpickled MyObj:",o print "unpickling MyEx" o=pickle.loads(p_myex) print "unpickled MyEx:",o From wolftracks at invalid.com Sun Dec 6 06:37:48 2009 From: wolftracks at invalid.com (W. eWatson) Date: Sun, 06 Dec 2009 03:37:48 -0800 Subject: Why Doesn't XP Pro Show Size, Time and Date Mod of a Created File? In-Reply-To: <0ceab209-dd73-4c5e-88a4-f550747c13b1@o23g2000vbi.googlegroups.com> References: <0ceab209-dd73-4c5e-88a4-f550747c13b1@o23g2000vbi.googlegroups.com> Message-ID: Mensanator wrote: > On Dec 5, 11:38?pm, "W. eWatson" wrote: >> I created a folder, and wrote a file to it. When I look at what files >> are in it, they are correct. However, The Size, Type, and Date Mod are >> not shown. Why am I missing those columns? I'm writing files with a >> suffix of dat, which seem only to match up with video CD movie. > > Got to the View menu and select Details. > > Once in the Details view, click on the column > headings and select which details to view. That's strange. I had gone to details before without any luck, but now it's showing the above columns. From python.list at tim.thechases.com Sun Dec 6 07:34:17 2009 From: python.list at tim.thechases.com (Tim Chase) Date: Sun, 06 Dec 2009 06:34:17 -0600 Subject: How to create a docstring for a module? In-Reply-To: <00a50dbe$0$15659$c3e8da3@news.astraweb.com> References: <20091206105550.16570a30@geekmail.INVALID> <00a50dbe$0$15659$c3e8da3@news.astraweb.com> Message-ID: <4B1BA4C9.5090702@tim.thechases.com> > * He hasn't actually defined a docstring. Docstrings have to be string > literals, you can't do this: > > """%s does everything you could possibly want.""" % "xyz" I've occasionally wanted something like this, and have found that it can be done by manually assigning to __doc__ (either at the module-level or classes) which can make some documentation bits a little easier: # ds.py ############## "original docstring" OPTIONS = { 'FOO': 'bar', 'BAZ': 'boing', } __doc__ = """ This is %(FOO)s and it does %(BAZ)s """ % OPTIONS more_code_that_uses(OPTIONS) ###################### you can then >>> import ds >>> help(ds) ... and see the formatted help that makes use of the options in the file. Being lazy, I'm all for self-updating documentation ;-) Even weirder is assigning a repr()/str()'able class-instance as the __doc__ for even crazier behaviors (though it looks like the internal help() function ignores them, perhaps requiring isinstance(__doc__, basestring) to pass) # ds2.py ############### class DynamicHelp: def __init__(self, name, count=0): self.name = name self.count = count def __str__(self): self.count += 1 if self.count = 3: return "Are you REALLY that forgetful?!" return "%s:%i" % (self.name, self.count) def __repr__(self): return "<%s>" % self class C: "Raw C" def __init__(self, name): self.__doc__ = DynamicHelp(name) where you can then do weird things like >>> import ds2 >>> c = ds2.C("Hello") >>> c.__doc__ >>> c.__doc__ >>> c.__doc__ Are you REALLY that forgetful?! >>> c.__doc__ -tkc From steve at REMOVE-THIS-cybersource.com.au Sun Dec 6 08:43:40 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 06 Dec 2009 13:43:40 GMT Subject: How to create a docstring for a module? References: <20091206105550.16570a30@geekmail.INVALID> <00a50dbe$0$15659$c3e8da3@news.astraweb.com> Message-ID: <00a53998$0$15659$c3e8da3@news.astraweb.com> On Sun, 06 Dec 2009 06:34:17 -0600, Tim Chase wrote: >> * He hasn't actually defined a docstring. Docstrings have to be string >> literals, you can't do this: >> >> """%s does everything you could possibly want.""" % "xyz" > > I've occasionally wanted something like this, and have found that it can > be done by manually assigning to __doc__ (either at the module-level or > classes) which can make some documentation bits a little easier: Unfortunately, and surprisingly, assigning to __doc__ doesn't work with new-style classes. >>> class K(object): ... pass ... >>> K.__doc__ is None True >>> K.__doc__ = "docstring" Traceback (most recent call last): File "", line 1, in AttributeError: attribute '__doc__' of 'type' objects is not writable -- Steven From michaelmossey at yahoo.com Sun Dec 6 08:57:59 2009 From: michaelmossey at yahoo.com (Michael) Date: Sun, 6 Dec 2009 05:57:59 -0800 (PST) Subject: Organization of GUIs References: <424dcb65-735c-4779-ae0a-5c4e662b24ac@b36g2000prf.googlegroups.com> <6d83fec3-ad8d-43d3-ada6-18ff3d189aed@2g2000prl.googlegroups.com> Message-ID: <9d4c1765-cd4e-45ac-bc14-be8a2ad5361e@z4g2000prh.googlegroups.com> On Dec 5, 11:50?pm, zeph wrote: > I highly recommend reading the Cocoa documentation, which has volumes > on all sorts of things like this. ?Here's a link that talks about > views in that context, and should give you more ideas about well- > designed GUI layouts:http://bit.ly/6b8PYh Cool link. Thanks! -Mike From feliphil at gmx.net Sun Dec 6 09:07:42 2009 From: feliphil at gmx.net (Wolfgang Keller) Date: Sun, 6 Dec 2009 15:07:42 +0100 Subject: postgresql_autodoc in Python? Message-ID: <20091206150742.45d0c4aa.feliphil@gmx.net> Hello, has anyone ever implemented something similar to postgresql_autodoc in Python? TIA, Sincerely, Wolfgang -- NO "Courtesy Copies" PLEASE! From albert at spenarnc.xs4all.nl Sun Dec 6 09:07:55 2009 From: albert at spenarnc.xs4all.nl (Albert van der Horst) Date: 06 Dec 2009 14:07:55 GMT Subject: semantics of ** (unexpected/inconsistent?) References: <4b132c1b$1@dnews.tpgi.com.au> <87eingrbh9.fsf@benfinney.id.au> Message-ID: In article <87eingrbh9.fsf at benfinney.id.au>, Ben Finney wrote: >Lie Ryan writes: > >> I generally do not expect operator precedence to be reliable at all > >Have another read of the thread. The OP's confusion was not over >operator precedence, but over how names resolve to values in >expressions. Operator precedence comes naturally into this matter. For example, in algol 68 -3**2 is parsed as (-3)**2 because of the simple rule that all unary operators have precedence over all binary operators. (It is a good rule, and this is about the only way to get a somewhat surprising result. Unary operators -- as long as they are always put up front -- need not have a precedence among themselves, so with this rule they don't need a precedence full stop. ) >Ben Finney Groetjes Albert -- -- Albert van der Horst, UTRECHT,THE NETHERLANDS Economic growth -- being exponential -- ultimately falters. albert at spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst From vinay_sajip at yahoo.co.uk Sun Dec 6 13:12:25 2009 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Sun, 6 Dec 2009 10:12:25 -0800 (PST) Subject: logging module, SMTPHandler and gmail in python 2.6 References: Message-ID: <822db793-1fcb-43c6-84ed-4a73c27ff88a@m11g2000vbo.googlegroups.com> On Dec 4, 12:31?pm, mynthon wrote: Thank you for this suggestion. Ideally, you would have created an issue for this on bugs.python.org, because then it would be more likely to be acted upon. I've implemented this feature in r76691 (in Python trunk and py3k) in a more general way. It works by specifying an optional secure argument to SMTPHandler.__init__. This defaults to None, which implements the current behaviour - no TLS support. If TLS support is required, pass in a tuple for secure, with one of the following values: 1. An empty tuple 2. A 1-tuple with the name of the PEM-formatted keyfile with a private key. 3. A 2-tuple with the name of the PEM-formatted keyfile and a PEM- formatted certificate chain file. This tuple, if specified, is passed to the SMTP object's starttls method (and via that to socket.ssl). Check the starttls/ssl methods for more information. Regards, Vinay Sajip From vicente.soler at gmail.com Sun Dec 6 13:21:20 2009 From: vicente.soler at gmail.com (vsoler) Date: Sun, 6 Dec 2009 10:21:20 -0800 (PST) Subject: When will Python 3 be fully deployed Message-ID: I recently read that many libraries, including Numpy have not been ported to Python 3. When do you think that Python 3 will be fully deployed? Should I stick, so far, to Python 2.6? Regards Vicente Soler From luismgz at gmail.com Sun Dec 6 13:25:35 2009 From: luismgz at gmail.com (=?ISO-8859-1?Q?Luis_M=2E_Gonz=E1lez?=) Date: Sun, 6 Dec 2009 10:25:35 -0800 (PST) Subject: When will Python 3 be fully deployed References: Message-ID: On Dec 6, 3:21?pm, vsoler wrote: > I recently read that many libraries, including Numpy have not been > ported to Python 3. > > When do you think that Python 3 will be fully deployed? > > Should I stick, so far, to Python 2.6? > > Regards > > Vicente Soler You'll have some answers here: http://jessenoller.com/2009/12/04/pythons-moratorium-lets-think-about-this/ From valter.foresto at gmail.com Sun Dec 6 13:35:11 2009 From: valter.foresto at gmail.com (Valter.Foresto) Date: Sun, 6 Dec 2009 10:35:11 -0800 (PST) Subject: wxEasyGUI: Easy and Interactive GUI Function Dialogs for Python newbie Message-ID: Python newbie, like me, need a simple, easy to understand and use, simple interactive GUI functions abd dialogs for starting using the language quickly. I wrote the wxEasyGUI simple library with this idea in my mind and started a new project on the SourceForge.net << wxEasyGUI - Easy to Use Interactive GUI Functions Dialogs based on "wxPython" and deep inspired by "EasyGui". >> Files are availables at http://sourceforge.net/projects/wxeasygui/files/ and on the Google Group http://groups.google.com/group/wxeasygui we can discuss this new small project. I very appreciate if the Python community can comments the idea, suggest improvements and review the wxEasyGUI code. Thanks. Valter Foresto. http://electronicbricks.blogspot.com/2009/11/wxeasygui.html From aleaxit at gmail.com Sun Dec 6 13:37:06 2009 From: aleaxit at gmail.com (Alex) Date: Sun, 6 Dec 2009 10:37:06 -0800 (PST) Subject: NumPy installation won't import correctly References: <661c84c0-4f7a-4a77-9418-193aa9cacadf@13g2000prl.googlegroups.com> <7nkd87F3mdj8mU1@mid.uni-berlin.de> <4d3d4246-3073-4ed4-a570-dbb94b46d4e4@r24g2000yqd.googlegroups.com> Message-ID: <27d85031-f9af-4160-8412-61d9493e6eb5@2g2000prl.googlegroups.com> On Dec 1, 7:04?pm, Ethos wrote: > On Dec 1, 6:37?pm, David Cournapeau wrote: > > > On Wed, Dec 2, 2009 at 11:03 AM, Ethos wrote: > > > > I reinstallednumpy, from sourceforge, even though I had already > > > installed the latest version. Same business. 2.5 imports fine, 2.6 > > > doesn't. > > > > Here's the output of the commands you gave me. > > > Which exact version of mac os x are you using ? (the output of sw_vers > > -productVersion > > ?would be fine). > > > David > > ProductName: ? ?Mac OS X > ProductVersion: 10.5.8 > BuildVersion: ? 9L30 > > Kevin I am also trying to install numpy 1.4 and observing exactly the same symptoms as Kevin (unsurprisingly, since it's a very similar installation: BuildVersion of 10.5.8 is 9L31a, otherwise identical). I can also reproduce the problem with the 2.5 version of the 1.4 rc1 numpy DMG (with macpython 2.5.4 from python.org -- it refuses to install using Apple's own 2.5.1). Is there any known-to-work way to install numpy 1.4 on Mac OS X 10.5.8, and Python either 2.5 or 2.6? Guess next I'll try building from sources... Alex From ptmcg at austin.rr.com Sun Dec 6 14:03:07 2009 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sun, 6 Dec 2009 11:03:07 -0800 (PST) Subject: How to create a docstring for a module? References: <20091206105550.16570a30@geekmail.INVALID> <00a50dbe$0$15659$c3e8da3@news.astraweb.com> <00a53998$0$15659$c3e8da3@news.astraweb.com> Message-ID: On Dec 6, 7:43?am, Steven D'Aprano wrote: > On Sun, 06 Dec 2009 06:34:17 -0600, Tim Chase wrote: > > I've occasionally wanted something like this, and have found that it can > > be done by manually assigning to __doc__ (either at the module-level or > > classes) which can make some documentation bits a little easier: > > Unfortunately, and surprisingly, assigning to __doc__ doesn't work with > new-style classes. > > -- > Steven Fortunately, in the OP's case, he isn't trying to do this with a class, but with a module. For me, assigning to __doc__ at the module works in defining a docstring for pyparsing, at least for Py2.5. -- Paul From hansmu at xs4all.nl Sun Dec 6 14:08:25 2009 From: hansmu at xs4all.nl (Hans Mulder) Date: Sun, 06 Dec 2009 20:08:25 +0100 Subject: Why Can't I Delete a File I Created with Win XP? In-Reply-To: References: <62dbb389-6e6b-42bc-876d-85389784a408@z10g2000prh.googlegroups.com> Message-ID: <4b1c019a$0$22919$e4fe514c@news.xs4all.nl> J wrote: > But that being said, this brings to mind a question about this... in > *nix, when I can't do something like delete a file or directory, or > unmount a filesystem and cant find the cause, I can do an lsof and > grep for references to the file/directory in question, then work from > there to close anything that still has a lock. It's been a while since a last had this problem. I found a program named "handle.exe" somewhere on microsoft.com. It spits out a listing showing which process has which files open. You can kill the offending processes, and then you can delete your file. I suppose Google can help you find this program. Hope this helps, -- HansM From dbd at ieee.org Sun Dec 6 14:23:34 2009 From: dbd at ieee.org (dbd) Date: Sun, 6 Dec 2009 11:23:34 -0800 (PST) Subject: Float precision and float equality References: <2f0dee67-6fda-47c0-8266-d2d6b02ed655@e4g2000prn.googlegroups.com> <574bd33c-a38b-4af5-802e-fc081965a230@g23g2000vbr.googlegroups.com> <6624fc07-c6d5-40e1-a899-6eb73603a980@u8g2000prd.googlegroups.com> <335cb11d-e862-4daa-aec6-8f96b56bc28a@u1g2000pre.googlegroups.com> Message-ID: <79c41269-2b84-4fb1-8694-c7212f92be62@d9g2000prh.googlegroups.com> On Dec 6, 1:12?am, Raymond Hettinger wrote: > On Dec 5, 11:42?pm, Tim Roberts wrote: > > > Raymond Hettinger wrote: > > > > ? if not round(x - y, 6): ... > > > That's a dangerous suggestion. ?It only works if x and y happen to be > > roughly in the range of integers. .> .> Right. ?Using abs(x-y) < eps is the way to go. .> .> Raymond This only works when abs(x) and abs(y) are larger that eps, but not too much larger. Mark's suggestion is longer, but it works. The downside is it requires you to think about the scale and accuracy of your application. Dale B. Dalrymple From gerenuk81 at googlemail.com Sun Dec 6 14:34:21 2009 From: gerenuk81 at googlemail.com (Anton81) Date: Sun, 6 Dec 2009 11:34:21 -0800 (PST) Subject: Float precision and float equality References: <3abf9dfb-fa01-4f71-9214-a06d8b847ebf@e20g2000vbb.googlegroups.com> Message-ID: I do some linear algebra and whenever the prefactor of a vector turns out to be zero, I want to remove it. I'd like to keep the system comfortable. So basically I should write a new class for numbers that has it's own __eq__ operator? Is there an existing module for that? From bdesth.quelquechose at free.quelquepart.fr Sun Dec 6 15:04:44 2009 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 06 Dec 2009 21:04:44 +0100 Subject: Python3: Sane way to deal with broken encodings In-Reply-To: <7o2ibkF3o3ddhU1@mid.dfncis.de> References: <7o2ibkF3o3ddhU1@mid.dfncis.de> Message-ID: <4b1c1bea$0$9415$426a74cc@news.free.fr> Johannes Bauer a ?crit : > Dear all, > > I've some applciations which fetch HTML docuemnts off the web, parse > their content and do stuff with it. Every once in a while it happens > that the web site administrators put up files which are encoded in a > wrong manner. > > Thus my Python script dies a horrible death: > > File "./update_db", line 67, in > for line in open(tempfile, "r"): > File "/usr/local/lib/python3.1/codecs.py", line 300, in decode > (result, consumed) = self._buffer_decode(data, self.errors, final) > UnicodeDecodeError: 'utf8' codec can't decode byte 0x92 in position > 3286: unexpected code byte > > This is well and ok usually, but I'd like to be able to tell Python: > "Don't worry, some idiot encoded that file, just skip over such > parts/replace them by some character sequence". > > Is that possible? If so, how? This might get you started: """ >>> help(str.decode) decode(...) S.decode([encoding[,errors]]) -> object Decodes S using the codec registered for encoding. encoding defaults to the default encoding. errors may be given to set a different error handling scheme. Default is 'strict' meaning that encoding errors raise a UnicodeDecodeError. Other possible values are 'ignore' and 'replace' as well as any other name registered with codecs.register_error that is able to handle UnicodeDecodeErrors. """ HTH From jorgeecardona at gmail.com Sun Dec 6 15:22:59 2009 From: jorgeecardona at gmail.com (Jorge Cardona) Date: Sun, 6 Dec 2009 15:22:59 -0500 Subject: Generators. Message-ID: <51d803a90912061222i746950a2jc5ed9a9c094426e9@mail.gmail.com> Hi, I was trying to create a function that receive a generator and return a list but that each elements were computed in a diferent core of my machine. I start using islice function in order to split the job in a way that if there is "n" cores each "i" core will compute the elements i,i+n,i+2n,..., but islice has a weird (to me) behavior, look: from itertools import islice def f(x): print("eval: %d"%x) return x X = range(10) g = (f(x) for x in X) print(list(x for x in islice(g,0,None,2))) $ python2.5 test.py eval: 0 eval: 1 eval: 2 eval: 3 eval: 4 eval: 5 eval: 6 eval: 7 eval: 8 eval: 9 [0, 2, 4, 6, 8] $ python2.7 test.py eval: 0 eval: 1 eval: 2 eval: 3 eval: 4 eval: 5 eval: 6 eval: 7 eval: 8 eval: 9 [0, 2, 4, 6, 8] $ python3.0 test.py eval: 0 eval: 1 eval: 2 eval: 3 eval: 4 eval: 5 eval: 6 eval: 7 eval: 8 eval: 9 [0, 2, 4, 6, 8] islice execute the function at the generator and drop the elements that aren't in the slice. I found that pretty weird, the way that i see generators is like an association between and indexing set (an iterator or another generator) and a computation that is made indexed by the indexing set, and islice is like a "transformation" on the indexing set,it doesn't matter the result of the function, the slice should act only on the indexing set, some other "transformation" like takewhile act on the result so, the execution it has to be made, but in the islice, or other "transformation" that act only in the indexing set, the function shouldn't be executed at each element, but only on that new set that result of the application of the "transformation" on the original set. I search a little bit and found that gi_frame.f_locals['.0'] holds the inner indexing element of a generator, so i decide to define my own islice like this: from itertools import islice import sys if sys.version_info[0] != 3: def next(it): return it.next() def f(x): print("eval: %d"%x) return x def islice(iterable, *args): s = slice(*args) # search the deepest iter (Base indexing set) it = iterable while hasattr(it, 'gi_frame'): it = it.gi_frame.f_locals['.0'] # Consume the base indexing set until the first element for i in range(s.start): it.next() for e in iterable: yield e # Consume the base indexing set until the next element for i in range(s.step-1): next(it) X = range(10) g = (f(x) for x in X) print(list(x for x in islice(g,0,None,2))) jcardona at terminus:/tmp$ python2.5 test.py eval: 0 eval: 2 eval: 4 eval: 6 eval: 8 [0, 2, 4, 6, 8] jcardona at terminus:/tmp$ python2.7 test.py eval: 0 eval: 2 eval: 4 eval: 6 eval: 8 [0, 2, 4, 6, 8] jcardona at terminus:/tmp$ python3.0 test.py eval: 0 eval: 2 eval: 4 eval: 6 eval: 8 [0, 2, 4, 6, 8] Well, it works for what i need, but is not very neat, and i think that there it should be a formal way to act on the base indexing iterator, such way exists? Is there a better approach to get what i need? Thanks. -- Jorge Eduardo Cardona jorgeecardona at gmail.com jorgeecardona.blogspot.com ------------------------------------------------ Linux registered user #391186 Registered machine #291871 ------------------------------------------------ From dfnsonfsduifb at gmx.de Sun Dec 6 15:26:30 2009 From: dfnsonfsduifb at gmx.de (Johannes Bauer) Date: Sun, 06 Dec 2009 21:26:30 +0100 Subject: Python3: Sane way to deal with broken encodings Message-ID: <7o2ibkF3o3ddhU1@mid.dfncis.de> Dear all, I've some applciations which fetch HTML docuemnts off the web, parse their content and do stuff with it. Every once in a while it happens that the web site administrators put up files which are encoded in a wrong manner. Thus my Python script dies a horrible death: File "./update_db", line 67, in for line in open(tempfile, "r"): File "/usr/local/lib/python3.1/codecs.py", line 300, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) UnicodeDecodeError: 'utf8' codec can't decode byte 0x92 in position 3286: unexpected code byte This is well and ok usually, but I'd like to be able to tell Python: "Don't worry, some idiot encoded that file, just skip over such parts/replace them by some character sequence". Is that possible? If so, how? Kind regards, Johannes -- "Aus starken Potentialen k?nnen starke Erdbeben resultieren; es k?nnen aber auch kleine entstehen - und "du" wirst es nicht f?r m?glich halten (!), doch sieh': Es k?nnen dabei auch gar keine Erdbeben resultieren." -- "R?diger Thomas" alias Thomas Schulz in dsa ?ber seine "Vorhersagen" <1a30da36-68a2-4977-9eed-154265b17d28 at q14g2000vbi.googlegroups.com> From pfeldman at verizon.net Sun Dec 6 15:31:06 2009 From: pfeldman at verizon.net (Dr. Phillip M. Feldman) Date: Sun, 6 Dec 2009 12:31:06 -0800 (PST) Subject: How to create a docstring for a module? In-Reply-To: <00a50dbe$0$15659$c3e8da3@news.astraweb.com> References: <26662729.post@talk.nabble.com> <20091206105550.16570a30@geekmail.INVALID> <00a50dbe$0$15659$c3e8da3@news.astraweb.com> Message-ID: <26668719.post@talk.nabble.com> Steven D'Aprano-7 wrote: > > On Sun, 06 Dec 2009 10:55:50 +0100, Andreas Waldenburger wrote: > >> On Sat, 5 Dec 2009 23:04:42 -0800 (PST) "Dr. Phillip M. Feldman" >> wrote: >> >> >>> If I create a module xyz.py with a docstring """xyz does everything you >>> could possibly want.""" at the top, the command ?xyz issued at the >>> IPython prompt does not display this docstring. What am I doing wrong? >> >> Stab in the dark: You have imported the module first, right? >> >> Also: Never, EVER, ask a question like this on any technical forum >> without posting your code (or rather: a minimal version of it that still >> exhibits the problem). That way, people can help you directly instead of >> taking wild guesses at what your problem might be. > > In fairness, Phillip's description of the problem is pretty straight- > forward: he has a module xyz.py with a docstring. The minimal version of > the code is no code at all, just a docstring: > > """xyz does everything you could possibly want.""" > > His problem isn't an error when running the code, but an error with > IPython's command ?xyz. > > What he didn't say is what IPython prints instead of the expected > docstring. Over to you Phillip, don't just tell us what IPython doesn't > do, tell us what it does do. > > My guesses are: > > * He hasn't imported the module, so he gets an error of some sort. > > * He hasn't actually defined a docstring. Docstrings have to be string > literals, you can't do this: > > """%s does everything you could possibly want.""" % "xyz" > > Nor can you have anything except comments and whitespace between the top > of the module and the string. > > * He has another module called xyz which is shadowing the module he > expects, and so he sees that module's docstring instead. > > > -- > Steven > -- > http://mail.python.org/mailman/listinfo/python-list > > My bad. This is working for me now. I could swear that I imported the module previously, but perhaps I didn't . My apologies, and thanks for the help! -- View this message in context: http://old.nabble.com/How-to-create-a-docstring-for-a-module--tp26662729p26668719.html Sent from the Python - python-list mailing list archive at Nabble.com. From pfeldman at verizon.net Sun Dec 6 15:34:53 2009 From: pfeldman at verizon.net (Dr. Phillip M. Feldman) Date: Sun, 6 Dec 2009 12:34:53 -0800 (PST) Subject: How to create a docstring for a module? In-Reply-To: <00a50dbe$0$15659$c3e8da3@news.astraweb.com> References: <26662729.post@talk.nabble.com> <20091206105550.16570a30@geekmail.INVALID> <00a50dbe$0$15659$c3e8da3@news.astraweb.com> Message-ID: <26668758.post@talk.nabble.com> OK. I was able to reproduce the problem. My difficulty was that the command that I issued initially was "from xyz import *" rather than just "import xyz". If I say "import xyz", then the docstring is defined; if I say "from xyz import *", it isn't. I'm not sure whether this is a bug or expected behavior. -- View this message in context: http://old.nabble.com/How-to-create-a-docstring-for-a-module--tp26662729p26668758.html Sent from the Python - python-list mailing list archive at Nabble.com. From aioe.org at technicalbloke.com Sun Dec 6 15:52:05 2009 From: aioe.org at technicalbloke.com (r0g) Date: Sun, 06 Dec 2009 20:52:05 +0000 Subject: Float precision and float equality References: <2f0dee67-6fda-47c0-8266-d2d6b02ed655@e4g2000prn.googlegroups.com> <574bd33c-a38b-4af5-802e-fc081965a230@g23g2000vbr.googlegroups.com> <6624fc07-c6d5-40e1-a899-6eb73603a980@u8g2000prd.googlegroups.com> <335cb11d-e862-4daa-aec6-8f96b56bc28a@u1g2000pre.googlegroups.com> <79c41269-2b84-4fb1-8694-c7212f92be62@d9g2000prh.googlegroups.com> Message-ID: dbd wrote: > On Dec 6, 1:12 am, Raymond Hettinger wrote: >> On Dec 5, 11:42 pm, Tim Roberts wrote: >> >>> Raymond Hettinger wrote: >>>> if not round(x - y, 6): ... >>> That's a dangerous suggestion. It only works if x and y happen to be >>> roughly in the range of integers. > .> > .> Right. Using abs(x-y) < eps is the way to go. > .> > .> Raymond > > This only works when abs(x) and abs(y) are larger that eps, but not > too much larger. Okay, I'm confused now... I thought them being larger was entirely the point. At what point can they become too large? Isn't eps entirely arbitrary anyway? > > Mark's suggestion is longer, but it works. The downside is it requires > you to think about the scale and accuracy of your application. > Shouldn't one be doing that in any case?? Roger. From rune.strand at gmail.com Sun Dec 6 15:54:37 2009 From: rune.strand at gmail.com (Rune Strand) Date: Sun, 6 Dec 2009 12:54:37 -0800 (PST) Subject: How to timeout when waiting for raw_input from user ? References: <55b6b337-fb8f-46b9-a665-108dd19e1dd8@w19g2000pre.googlegroups.com> <7xhbs6xad0.fsf@ruckus.brouhaha.com> <465b7ba8-d2cd-4962-ad17-e22a75383e21@x25g2000prf.googlegroups.com> Message-ID: On Dec 5, 3:42?pm, Maxim Khitrov wrote: > I'm not talking about the Timer, I'm talking about the original > question. There's nothing (that I know of) you can do with a Timer on > Windows to interrupt a raw_input call. That is true. But if the issue here is to present a question, and await answer for N seconds, before pusing next question, Timer() can be used to call SendKeys() and have it send "{ENTER}" to raw_input. http://www.rutherfurd.net/python/sendkeys/index.html SendKeys is Win-only From clp2 at rebertia.com Sun Dec 6 16:06:05 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 6 Dec 2009 13:06:05 -0800 Subject: How to create a docstring for a module? In-Reply-To: <26668758.post@talk.nabble.com> References: <26662729.post@talk.nabble.com> <20091206105550.16570a30@geekmail.INVALID> <00a50dbe$0$15659$c3e8da3@news.astraweb.com> <26668758.post@talk.nabble.com> Message-ID: <50697b2c0912061306i29d5faf9q9c25357c85652e44@mail.gmail.com> On Sun, Dec 6, 2009 at 12:34 PM, Dr. Phillip M. Feldman wrote: > OK. ?I was able to reproduce the problem. ?My difficulty was that the command > that I issued initially was "from xyz import *" rather than just "import > xyz". ?If I say "import xyz", then the docstring is defined; if I say "from > xyz import *", it isn't. ?I'm not sure whether this is a bug or expected > behavior. Expected behavior. If you `from foo import bar`, the name `foo` won't be bound, so needless to say you won't be able to access its docstring foo.__doc__. $ ipython Python 2.6.2 (r262:71600, Nov 5 2009, 15:03:16) Type "copyright", "credits" or "license" for more information. IPython 0.10 -- An enhanced Interactive Python. ? -> Introduction and overview of IPython's features. %quickref -> Quick reference. help -> Python's own help system. object? -> Details about 'object'. ?object also works, ?? prints more. In [1]: ?pickle Object `pickle` not found. In [2]: from pickle import * In [3]: ?pickle Object `pickle` not found. In [4]: pickle.__doc__ --------------------------------------------------------------------------- NameError Traceback (most recent call last) /Users/chris/ in () NameError: name 'pickle' is not defined In [5]: import pickle In [6]: ?pickle In [7]: pickle.__doc__ Out[7]: 'Create portable serialized representations of Python objects.\n\nSee module cPickle for a (much) faster implementation.\nSee module copy_reg for a mechanism for registering custom picklers.\nSee module pickletools source for extensive comments.\n\nClasses:\n\n Pickler\n Unpickler\n\nFunctions:\n\n dump(object, file)\n dumps(object) -> string\n load(file) -> object\n loads(string) -> object\n\nMisc variables:\n\n __version__\n format_version\n compatible_formats\n\n' Cheers, Chris -- http://blog.rebertia.com From stefan_ml at behnel.de Sun Dec 6 16:08:08 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sun, 06 Dec 2009 22:08:08 +0100 Subject: How to create a docstring for a module? In-Reply-To: References: <26662729.post@talk.nabble.com> <20091206105550.16570a30@geekmail.INVALID> <00a50dbe$0$15659$c3e8da3@news.astraweb.com> Message-ID: <4b1c1d38$0$6581$9b4e6d93@newsspool3.arcor-online.net> Dr. Phillip M. Feldman, 06.12.2009 21:34: > OK. I was able to reproduce the problem. My difficulty was that the command > that I issued initially was "from xyz import *" rather than just "import > xyz". If I say "import xyz", then the docstring is defined; if I say "from > xyz import *", it isn't. I'm not sure whether this is a bug or expected > behavior. Definitely expected behaviour. The problem isn't the docstring but what you import. "from xyz import a,b,c" does not import "xyz" into the current namespace. Only the names a,b,c are imported. If you do "import xyz", then "xyz" becomes a defined name in your current namespace. Stefan From sturlamolden at yahoo.no Sun Dec 6 16:48:24 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Sun, 6 Dec 2009 13:48:24 -0800 (PST) Subject: Float precision and float equality References: <2f0dee67-6fda-47c0-8266-d2d6b02ed655@e4g2000prn.googlegroups.com> <574bd33c-a38b-4af5-802e-fc081965a230@g23g2000vbr.googlegroups.com> <6624fc07-c6d5-40e1-a899-6eb73603a980@u8g2000prd.googlegroups.com> <335cb11d-e862-4daa-aec6-8f96b56bc28a@u1g2000pre.googlegroups.com> <79c41269-2b84-4fb1-8694-c7212f92be62@d9g2000prh.googlegroups.com> Message-ID: <49d04d6f-551b-46a9-8a11-7abe308a0154@f10g2000vbl.googlegroups.com> On 6 Des, 21:52, r0g wrote: > > .> Right. ?Using abs(x-y) < eps is the way to go. > > .> > > .> Raymond > > > This only works when abs(x) and abs(y) are larger that eps, but not > > too much larger. > > Okay, I'm confused now... I thought them being larger was entirely the > point. Yes. dbd got it wrong. If both a smaller than eps, the absolute difference is smaller than eps, so they are considered equal. From falk at mauve.rahul.net Sun Dec 6 17:10:15 2009 From: falk at mauve.rahul.net (Edward A. Falk) Date: Sun, 6 Dec 2009 22:10:15 +0000 (UTC) Subject: When will Python 3 be fully deployed References: Message-ID: In article , vsoler wrote: >I recently read that many libraries, including Numpy have not been >ported to Python 3. > >When do you think that Python 3 will be fully deployed? It will never be fully deployed. There will always be people out there who haven't felt it necessary to upgrade their systems. The question you should be asking is "when will the percentage of systems without Python 3 be so small that I don't care about the customers I'll lose if I switch?" I can say personally that I still haven't seen any needs pressing enough to upgrade my perfectly-function Ubuntu 8 system. That means I can't even run Python 2.6 code. I'm still using 2.5. >Should I stick, so far, to Python 2.6? For development purposes, you should stick with the oldest version that will actually run your code. Every time you move to a more modern version, you're leaving potential users/customers out in the cold. -- -Ed Falk, falk at despams.r.us.com http://thespamdiaries.blogspot.com/ From davea at ieee.org Sun Dec 6 17:12:23 2009 From: davea at ieee.org (Dave Angel) Date: Sun, 06 Dec 2009 17:12:23 -0500 Subject: Why Can't I Delete a File I Created with Win XP? In-Reply-To: <4b1c019a$0$22919$e4fe514c@news.xs4all.nl> References: <62dbb389-6e6b-42bc-876d-85389784a408@z10g2000prh.googlegroups.com> <4b1c019a$0$22919$e4fe514c@news.xs4all.nl> Message-ID: <4B1C2C47.6080701@ieee.org> Hans Mulder wrote: >
J wrote: > >> But that being said, this brings to mind a question about this... in >> *nix, when I can't do something like delete a file or directory, or >> unmount a filesystem and cant find the cause, I can do an lsof and >> grep for references to the file/directory in question, then work from >> there to close anything that still has a lock. > > It's been a while since a last had this problem. I found a program > named "handle.exe" somewhere on microsoft.com. It spits out a listing > showing which process has which files open. You can kill the offending > processes, and then you can delete your file. > > I suppose Google can help you find this program. > > > Hope this helps, > > -- HansM > > Handle.exe and "Process Explorer" (mentioned by J) are both from Sysinternals, which was acquired by Microsoft, and to be found on their site. http://technet.microsoft.com/en-us/sysinternals/default.aspx http://technet.microsoft.com/en-us/sysinternals/bb896655.aspx for handle.exe http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx for process explorer But as long as I'm in the thread, I'll state that I suspect the problem to be simply that the OP is running his script inside some IDE, and it hasn't really ended. So the first thing I'd try is to exit the IDE, and see whether the file is then released. DaveA From davea at ieee.org Sun Dec 6 17:21:46 2009 From: davea at ieee.org (Dave Angel) Date: Sun, 06 Dec 2009 17:21:46 -0500 Subject: Float precision and float equality In-Reply-To: References: <3abf9dfb-fa01-4f71-9214-a06d8b847ebf@e20g2000vbb.googlegroups.com> Message-ID: <4B1C2E7A.60702@ieee.org> Anton81 wrote: > I do some linear algebra and whenever the prefactor of a vector turns > out to be zero, I want to remove it. > > I'd like to keep the system comfortable. So basically I should write a > new class for numbers that has it's own __eq__ operator? > Is there an existing module for that? > > > You have to define your own "comfortable." But if it's zero you're checking for, then I most certainly wouldn't try to hide it inside a "number class." Most such formulas go ballistic when you get near zero. The definition of 'close enough" is very context dependent, and shouldn't be hidden at too low a level. But your mileage may vary. For example, in your case, you might want to check that the prefactor is much smaller than the average (of the abs values) of the vector elements. Enough orders of magnitude smaller, and you call it equal to zero. DaveA From ffrankisoft at gmail.com Sun Dec 6 17:29:32 2009 From: ffrankisoft at gmail.com (franki fuentes cueto) Date: Sun, 6 Dec 2009 17:29:32 -0500 Subject: hola Message-ID: <4f981bd80912061429g77b0bd66r617950b5d35e1caa@mail.gmail.com> hola soy un peque?o programador y quiesiera pedirles ayuda para programar en python, no se si me podrian mandar ejemplos para poder empezar, y como terminarlo para que se ejecute, me entiendes , aver sime ayudan gracias -- ......FrankiSoft....... -------------- next part -------------- An HTML attachment was scrubbed... URL: From bthate at gmail.com Sun Dec 6 17:38:08 2009 From: bthate at gmail.com (Bart Thate) Date: Sun, 6 Dec 2009 14:38:08 -0800 (PST) Subject: CMNDBOT 0.1 BETA2 released Message-ID: <6f5922af-ce5c-4c7c-bc0e-cfcefdd702a5@1g2000vbm.googlegroups.com> Hello world ! a week after BETA1 i'm releasing BETA2, changes go fast ;] what changed in this version: * RSS plugin can now push to xmpp clients .. add cmndbot at appspot.com to your jabber client and do 1) rss-add to add a feed 2) use rss-start to make the bot start sending you feed updates. * a gadget plugin that enables you to load gadgets with one command (well two if you need to add the gadgets url) * a iframe gadget was made that loads the bots web interface into wave and other gadget containers * focus of the command box is now off when loading the gadget * a plugin dedicated to wave functionality was made. currently it has commands to get the id of the wave, getting the url redirecting to the wave and one to get a list of the wave's participants * lots of other bug fixes .. running from one to the other ;] Bart About CMNDBOT: CMNDBOT is an IRC like command bot for wave, web and xmpp, and has a plugin structure to allow users to program there own plugins. CMNDBOT is free code (BSD) so you can clone it and run a CMNDBOT yourself. Source is available at http://cmndbot.googlecode.com/ For a live example of CMNDBOT see cmndbot at appspot.com for jabber and wave and http://cmndbot.appspot.com for web. You can also try the new iframe gadget at http://cmndbot.appspot.com/iframe.xml or ... invite the bot to your wave and run !load cmndbot ;] feedback is very much appriciated, i made a wave where we can meet: https://wave.google.com/wave/#restored:wave:googlewave.com!w%252BV9a2mVSOC From cjwilliams43 at gmail.com Sun Dec 6 17:40:48 2009 From: cjwilliams43 at gmail.com (Colin W.) Date: Sun, 06 Dec 2009 17:40:48 -0500 Subject: When will Python 3 be fully deployed In-Reply-To: References: Message-ID: On 06-Dec-09 13:25 PM, Luis M. Gonz?lez wrote: > On Dec 6, 3:21 pm, vsoler wrote: >> I recently read that many libraries, including Numpy have not been >> ported to Python 3. >> >> When do you think that Python 3 will be fully deployed? >> >> Should I stick, so far, to Python 2.6? >> >> Regards >> >> Vicente Soler > > You'll have some answers here: http://jessenoller.com/2009/12/04/pythons-moratorium-lets-think-about-this/ 2.7 is now available. Work is going on numpy with Python 3.0 Colin W. From clp2 at rebertia.com Sun Dec 6 17:48:28 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 6 Dec 2009 14:48:28 -0800 Subject: hola In-Reply-To: <4f981bd80912061429g77b0bd66r617950b5d35e1caa@mail.gmail.com> References: <4f981bd80912061429g77b0bd66r617950b5d35e1caa@mail.gmail.com> Message-ID: <50697b2c0912061448w78bdecbci4cf38b9123bf403b@mail.gmail.com> 2009/12/6 franki fuentes cueto : > hola soy un peque?o programador y quiesiera pedirles ayuda para programar en > python, no se si me podrian mandar ejemplos para poder empezar, y como > terminarlo para que se ejecute, me entiendes , aver sime ayudan gracias Esta lista de discusi?n es en Ingl?s. Hay una lista de discusi?n en Espa?ol aqui: http://listas.aditel.org/listinfo/python-es Salud, Chris -- S? solamente un poquito de Espa?ol. http://blog.rebertia.com From martin.hellwig at dcuktec.org Sun Dec 6 17:53:07 2009 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Sun, 06 Dec 2009 22:53:07 +0000 Subject: When will Python 3 be fully deployed In-Reply-To: References: Message-ID: Edward A. Falk wrote: > For development purposes, you should stick with the oldest version that will > actually run your code. Every time you move to a more modern version, you're > leaving potential users/customers out in the cold. If the fear of customers disatification prevents you from using a certain version of X, you should consider a deployment strategy that cuts out dependencies as much as possible. Although this will result in a larger end package and possible high amount of duplication, it is still preferable to just stop supporting popular platforms or be swamped away with bugs due to version mismatches. -- MPH http://blog.dcuktec.com 'If consumed, best digested with added seasoning to own preference.' From pavlovevidence at gmail.com Sun Dec 6 17:54:37 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Sun, 6 Dec 2009 14:54:37 -0800 (PST) Subject: Float precision and float equality References: <3abf9dfb-fa01-4f71-9214-a06d8b847ebf@e20g2000vbb.googlegroups.com> Message-ID: <6474d583-e797-45d1-af81-7bca5072a3b9@a39g2000pre.googlegroups.com> On Dec 6, 11:34?am, Anton81 wrote: > I do some linear algebra and whenever the prefactor of a vector turns > out to be zero, I want to remove it. > > I'd like to keep the system comfortable. So basically I should write a > new class for numbers that has it's own __eq__ operator? > Is there an existing module for that? I highly recommend against it; among other things it invalidates the transitive property of equality: "If a == b and b == c, then a == c." It will also make the number non-hashable, and have several other negative consequences. Plus, it's not something that's never foolproof. What numbers are close enought to be condidered "equal" depends on the calculations. (I remember once struggling in a homework assignment over seemingly large discrepancies in a calculation I was doing, until i realized that the actual numbers were on the scale of 10**11, and the difference was around 10**1, so it really didn't matter.) Carl Banks From duane.kaufman at gmail.com Sun Dec 6 19:12:07 2009 From: duane.kaufman at gmail.com (TheSeeker) Date: Sun, 6 Dec 2009 16:12:07 -0800 (PST) Subject: Float precision and float equality References: <3abf9dfb-fa01-4f71-9214-a06d8b847ebf@e20g2000vbb.googlegroups.com> <6474d583-e797-45d1-af81-7bca5072a3b9@a39g2000pre.googlegroups.com> Message-ID: <2c9f5673-da46-4a4e-924a-63146c3f65be@o9g2000prg.googlegroups.com> On Dec 6, 4:54?pm, Carl Banks wrote: > On Dec 6, 11:34?am, Anton81 wrote: > > > I do some linear algebra and whenever the prefactor of a vector turns > > out to be zero, I want to remove it. > > > I'd like to keep the system comfortable. So basically I should write a > > new class for numbers that has it's own __eq__ operator? > > Is there an existing module for that? > > I highly recommend against it; among other things it invalidates the > transitive property of equality: > > "If a == b and b == c, then a == c." > > It will also make the number non-hashable, and have several other > negative consequences. ? ?What numbers are close enought to be condidered "equal" > depends on the calculations. > > (I remember once struggling in a homework assignment over seemingly > large discrepancies in a calculation I was doing, until i realized > that the actual numbers were on the scale of 10**11, and the > difference was around 10**1, so it really didn't matter.) > > Carl Banks Maybe it's the gin, but "Plus, it's not something that's never foolproof.' +1 QOTW Cheers, TheSeeker From cournape at gmail.com Sun Dec 6 19:16:22 2009 From: cournape at gmail.com (David Cournapeau) Date: Mon, 7 Dec 2009 09:16:22 +0900 Subject: Float precision and float equality In-Reply-To: <3abf9dfb-fa01-4f71-9214-a06d8b847ebf@e20g2000vbb.googlegroups.com> References: <3abf9dfb-fa01-4f71-9214-a06d8b847ebf@e20g2000vbb.googlegroups.com> Message-ID: <5b8d13220912061616k136dcb84t31d4be802cb13800@mail.gmail.com> On Sun, Dec 6, 2009 at 1:46 AM, Mark Dickinson wrote: > On Dec 5, 3:37?pm, Anton81 wrote: >> I'd like to do calculations with floats and at some point equality of >> two number will be checked. >> What is the best way to make sure that equality of floats will be >> detected, where I assume that mismatches beyond a certain point are >> due to truncation errors? > > Well, it depends a lot on the details of the application, but > a good general scheme is to allow both a fixed relative error > and an absolute error, and to assert that your two values are > 'nearly equal' if they're within *either* the relative error *or* > the absolute error. ?Something like, for example: > > def almostEqual(expected, actual, rel_err=1e-7, abs_err = 1e-20): > ? ?absolute_error = abs(actual-expected) > ? ?return absolute_error <= max(abs_err, rel_err * abs(expected)) If you can depend on IEEE 754 semantics, one relatively robust method is to use the number of representable floats between two numbers. The main advantage compared to the proposed methods is that it somewhat automatically takes into account the amplitude of input numbers: abs(x - y) <= N * spacing(max(abs(x), abs(y))) Where spacing(a) is the smallest number such as a + spacing(a) != a. Whether a and b are small or big, the same value of N can be used, and it tells you how close two numbers are in terms of internal representation. Upcoming numpy 1.4.0 has an implementation for spacing - implementing your own for double is not difficult, though, cheers, David From pfeldman at verizon.net Sun Dec 6 19:32:39 2009 From: pfeldman at verizon.net (Phillip M. Feldman) Date: Sun, 06 Dec 2009 16:32:39 -0800 Subject: How to create a docstring for a module? In-Reply-To: <50697b2c0912061306i29d5faf9q9c25357c85652e44@mail.gmail.com> References: <26662729.post@talk.nabble.com> <20091206105550.16570a30@geekmail.INVALID> <00a50dbe$0$15659$c3e8da3@news.astraweb.com> <26668758.post@talk.nabble.com> <50697b2c0912061306i29d5faf9q9c25357c85652e44@mail.gmail.com> Message-ID: <4B1C4D27.3050801@verizon.net> Chris Rebert wrote: > On Sun, Dec 6, 2009 at 12:34 PM, Dr. Phillip M. Feldman > wrote: > >> OK. I was able to reproduce the problem. My difficulty was that the command >> that I issued initially was "from xyz import *" rather than just "import >> xyz". If I say "import xyz", then the docstring is defined; if I say "from >> xyz import *", it isn't. I'm not sure whether this is a bug or expected >> behavior. >> > > Expected behavior. If you `from foo import bar`, the name `foo` won't > be bound, so needless to say you won't be able to access its docstring > foo.__doc__. > > $ ipython > Python 2.6.2 (r262:71600, Nov 5 2009, 15:03:16) > Type "copyright", "credits" or "license" for more information. > > IPython 0.10 -- An enhanced Interactive Python. > ? -> Introduction and overview of IPython's features. > %quickref -> Quick reference. > help -> Python's own help system. > object? -> Details about 'object'. ?object also works, ?? prints more. > > In [1]: ?pickle > Object `pickle` not found. > > In [2]: from pickle import * > > In [3]: ?pickle > Object `pickle` not found. > > In [4]: pickle.__doc__ > --------------------------------------------------------------------------- > NameError Traceback (most recent call last) > > /Users/chris/ in () > > NameError: name 'pickle' is not defined > > In [5]: import pickle > > In [6]: ?pickle > > > > In [7]: pickle.__doc__ > Out[7]: 'Create portable serialized representations of Python > objects.\n\nSee module cPickle for a (much) faster > implementation.\nSee module copy_reg for a mechanism for registering > custom picklers.\nSee module pickletools source for extensive > comments.\n\nClasses:\n\n Pickler\n Unpickler\n\nFunctions:\n\n > dump(object, file)\n dumps(object) -> string\n load(file) -> > object\n loads(string) -> object\n\nMisc variables:\n\n > __version__\n format_version\n compatible_formats\n\n' > > > Cheers, > Chris > -- > http://blog.rebertia.com > > Hello Chris- It does seem as though IPython could be a bit more clever about this. If the user asks for documentation on xyz via "?xyz" and xyz is not defined, then I'd like to see IPython check for a module named "xyz" and if it exists, extract and display the docstring. Phillip From alfps at start.no Sun Dec 6 20:00:31 2009 From: alfps at start.no (Alf P. Steinbach) Date: Mon, 07 Dec 2009 02:00:31 +0100 Subject: Are routine objects guaranteed mutable & with dictionary? In-Reply-To: References: <4a2a7fdf-99d4-4219-a56c-7cd9146b3c85@f20g2000prn.googlegroups.com> Message-ID: * Dennis Lee Bieber: > On Sat, 05 Dec 2009 11:26:34 +0100, "Alf P. Steinbach" > declaimed the following in gmane.comp.python.general: > >> The devolution of terminology has been so severe that now even the Wikipedia >> article on this subject confounds the general concept of "routine" with the far >> more specialized term "sub-routine", which is just one kind of routine. It is of > > Well, if this were a FORTRAN IV text from the mid-70s you'd be > talking about > > function subprograms > and > subroutine subprograms It's in that direction yes, but the distinction that you mention, which is essentially the same as Pascal 'function' versus 'procedure', or Visual Basic 'function' versus 'sub', is just a distinction of two variants of subroutines. Up above there is the more general concept of a routine, where there are more possibilites than just subroutines; Python generators are one example. As I mentioned earlier, in Eiffel, which is a more modern language than Fortran, routines are still called routines. And specialized terms include "routine". So it's not like that language independent terminology has been phased out in general; it's mostly only in the C syntax family (e.g. Python operators come mostly from C) that "function" is, misleadingly and with associated severe constraints, used as a general term. Cheers, - Alf From python at mrabarnett.plus.com Sun Dec 6 20:18:10 2009 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 07 Dec 2009 01:18:10 +0000 Subject: Are routine objects guaranteed mutable & with dictionary? In-Reply-To: References: <4a2a7fdf-99d4-4219-a56c-7cd9146b3c85@f20g2000prn.googlegroups.com> Message-ID: <4B1C57D2.3010701@mrabarnett.plus.com> Alf P. Steinbach wrote: > * Dennis Lee Bieber: >> On Sat, 05 Dec 2009 11:26:34 +0100, "Alf P. Steinbach" >> declaimed the following in >> gmane.comp.python.general: >> >>> The devolution of terminology has been so severe that now even the >>> Wikipedia article on this subject confounds the general concept of >>> "routine" with the far more specialized term "sub-routine", which >>> is just one kind of routine. It is of >> >> Well, if this were a FORTRAN IV text from the mid-70s you'd be >> talking about >> >> function subprograms >> and >> subroutine subprograms > > It's in that direction yes, but the distinction that you mention, > which is essentially the same as Pascal 'function' versus > 'procedure', or Visual Basic 'function' versus 'sub', is just a > distinction of two variants of subroutines. > > Up above there is the more general concept of a routine, where there > are more possibilites than just subroutines; Python generators are > one example. > > As I mentioned earlier, in Eiffel, which is a more modern language > than Fortran, routines are still called routines. And specialized > terms include "routine". So it's not like that language independent > terminology has been phased out in general; it's mostly only in the C > syntax family (e.g. Python operators come mostly from C) that > "function" is, misleadingly and with associated severe constraints, > used as a general term. > In C there were originally only functions; if you didn't specify a return type then it would default to 'int' ('void' was a later addition). In Python there are only functions; if you don't explicitly return a value then None is returned. The distinction between functions and procedures can be helpful in deciding whether something is Pythonic (for example, in the use of list comprehensions), but in reality they are all still functions. From aaron.watters at gmail.com Sun Dec 6 21:38:55 2009 From: aaron.watters at gmail.com (Aaron Watters) Date: Sun, 6 Dec 2009 18:38:55 -0800 (PST) Subject: High-performance Python websites References: <7cdd7775-0524-4f10-a347-6e79038c821b@a39g2000pre.googlegroups.com> <06d5bca6-8bf6-4f14-96bc-2f5c32b27a40@15g2000prz.googlegroups.com> <87my1xklh4.fsf@free.fr> Message-ID: The key to scaling a web site is to make sure you can load-balance to as many front ends as needed and then use a common database backend that is fast enough or possibly a common file system that is fast enough. I can't speak to Django specifically but you can certainly get essentially unlimited scalability on the front-end side of the equation using a Python based web app. The google app engine will set such a configuration up for you automatically, but they are still working some bugs out with regard to performance, I think, based on my experience here http://whiffdoc.appspot.com/ and here http://listtree.appspot.com/ I hope that helps. -- Aaron Watters === an apple every 8 hours will keep 3 doctors away. -kliban From wuwei23 at gmail.com Sun Dec 6 21:51:30 2009 From: wuwei23 at gmail.com (alex23) Date: Sun, 6 Dec 2009 18:51:30 -0800 (PST) Subject: How to create a docstring for a module? References: <26662729.post@talk.nabble.com> <20091206105550.16570a30@geekmail.INVALID> <00a50dbe$0$15659$c3e8da3@news.astraweb.com> <26668758.post@talk.nabble.com> <50697b2c0912061306i29d5faf9q9c25357c85652e44@mail.gmail.com> Message-ID: "Phillip M. Feldman" wrote: > It does seem as though IPython could be a bit more clever about this. ? I disagree. I _like_ that IPython is only reporting on the current state of the interpreter and not trying to second guess what I meant. > If the user asks for documentation on xyz via "?xyz" and xyz is not > defined, then I'd like to see IPython check for a module named "xyz" and > if it exists, extract and display the docstring. How would you recommend IPython distinguish between which "xyz" you meant: the one in site-packages, the one in some package on the python path, or the one in the folder you're running IPython from? From davea at ieee.org Sun Dec 6 22:15:30 2009 From: davea at ieee.org (Dave Angel) Date: Sun, 06 Dec 2009 22:15:30 -0500 Subject: Float precision and float equality In-Reply-To: <6474d583-e797-45d1-af81-7bca5072a3b9@a39g2000pre.googlegroups.com> References: <3abf9dfb-fa01-4f71-9214-a06d8b847ebf@e20g2000vbb.googlegroups.com> <6474d583-e797-45d1-af81-7bca5072a3b9@a39g2000pre.googlegroups.com> Message-ID: <4B1C7352.9030505@ieee.org> Carl Banks wrote: > On Dec 6, 11:34 am, Anton81 wrote: > >> I do some linear algebra and whenever the prefactor of a vector turns >> out to be zero, I want to remove it. >> >> I'd like to keep the system comfortable. So basically I should write a >> new class for numbers that has it's own __eq__ operator? >> Is there an existing module for that? >> > > I highly recommend against it; among other things it invalidates the > transitive property of equality: > > "If a =b and b == c, then a == c." > > It will also make the number non-hashable, and have several other > negative consequences. Plus, it's not something that's never > foolproof. What numbers are close enought to be condidered "equal" > depends on the calculations. > > (I remember once struggling in a homework assignment over seemingly > large discrepancies in a calculation I was doing, until i realized > that the actual numbers were on the scale of 10**11, and the > difference was around 10**1, so it really didn't matter.) > > > > Carl Banks > > A few decades ago I implemented the math package (microcode) under the machine language for a proprietary processor (this is when a processor took 5 boards of circuitry to implement). I started with floating point add and subtract, and continued all the way through the trig, log, and even random functions. Anyway, a customer called asking whether a particular problem he had was caused by his logic, or by errors in our math. He was calculating the difference in height between an always-level table and a perfectly flat table (between an arc of a great circle around the earth, and a flat table that doesn't follow the curvature.) In a couple of hundred feet of table, the difference was measured in millionths of an inch, as I recall. Anyway it turned out his calculation was effectively subtracting (8000 miles plus a little bit) - (8000 miles) and if he calculated it three different ways, he got three different results, one was off in about the 3rd place, while the other was only half the value. I was able to show him another way (through geometrical transformations) to solve the problem that got the exact answer, or at least to more digits than he could possibly measure. I think I recall that the new solution also cancelled out the need for trig. Sometimes the math package shouldn't hide the problem, but give it to you straight. DaveA From wolftracks at invalid.com Sun Dec 6 22:29:48 2009 From: wolftracks at invalid.com (W. eWatson) Date: Sun, 06 Dec 2009 19:29:48 -0800 Subject: What is the significance of after() in this code? Message-ID: See Subject. def StackImages(self): self.Upload("P") self.after_id = self.master.after(10000,self.GetFrameOne) From pavlovevidence at gmail.com Sun Dec 6 23:31:42 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Sun, 6 Dec 2009 20:31:42 -0800 (PST) Subject: What is the significance of after() in this code? References: Message-ID: On Dec 6, 7:29?pm, "W. eWatson" wrote: > See Subject. > ? ? ?def StackImages(self): > ? ? ? ? ?self.Upload("P") > ? ? ? ? ?self.after_id = self.master.after(10000,self.GetFrameOne) It's a "method" of the object that is bound to "self.master". It's return value is then bound to the attribute "after_id" of the object "self". Carl Banks From benjamin.kaplan at case.edu Sun Dec 6 23:46:05 2009 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Sun, 6 Dec 2009 23:46:05 -0500 Subject: What is the significance of after() in this code? In-Reply-To: References: Message-ID: On Sun, Dec 6, 2009 at 10:29 PM, W. eWatson wrote: > See Subject. > ? ?def StackImages(self): > ? ? ? ?self.Upload("P") > ? ? ? ?self.after_id = self.master.after(10000,self.GetFrameOne) > -- > http://mail.python.org/mailman/listinfo/python-list > I think this is close to winning an award for "least information provided". How are we supposed to know with the information you gave us? We don't know what package you're using, what type anything is, or even the purpose of that method. Try putting this line in there somewhere print type(self.master) and then open up the interactive interpreter, import whatever you need and do help(.after) From highcar at gmail.com Mon Dec 7 00:01:56 2009 From: highcar at gmail.com (elca) Date: Sun, 6 Dec 2009 21:01:56 -0800 (PST) Subject: python proxy checker ,change to threaded version Message-ID: <26672548.post@talk.nabble.com> Hello ALL, i have some python proxy checker . and to speed up check, i was decided change to mutlthreaded version, and thread module is first for me, i was tried several times to convert to thread version and look for many info, but it not so much easy for novice python programmar . if anyone can help me really much appreciate!! thanks in advance! import urllib2, socket socket.setdefaulttimeout(180) # read the list of proxy IPs in proxyList proxyList = open('listproxy.txt').read() def is_bad_proxy(pip): try: proxy_handler = urllib2.ProxyHandler({'http': pip}) opener = urllib2.build_opener(proxy_handler) opener.addheaders = [('User-agent', 'Mozilla/5.0')] urllib2.install_opener(opener) req=urllib2.Request('http://www.yahoo.com') # <---check whether proxy alive sock=urllib2.urlopen(req) except urllib2.HTTPError, e: print 'Error code: ', e.code return e.code except Exception, detail: print "ERROR:", detail return 1 return 0 for item in proxyList: if is_bad_proxy(item): print "Bad Proxy", item else: print item, "is working" -- View this message in context: http://old.nabble.com/python-proxy-checker-%2Cchange-to-threaded-version-tp26672548p26672548.html Sent from the Python - python-list mailing list archive at Nabble.com. From lie.1296 at gmail.com Mon Dec 7 00:01:56 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Mon, 07 Dec 2009 16:01:56 +1100 Subject: Generators. In-Reply-To: References: Message-ID: <4b1c8cc3$1@dnews.tpgi.com.au> On 12/7/2009 7:22 AM, Jorge Cardona wrote: > Hi, > > I was trying to create a function that receive a generator and return > a list but that each elements were computed in a diferent core of my > machine. I start using islice function in order to split the job in a > way that if there is "n" cores each "i" core will compute the elements > i,i+n,i+2n,..., but islice has a weird (to me) behavior, look: it's nothing weird, python just do what you're telling it to: transform all x in X with f(x) > g = (f(x) for x in X) then slice the result of that > print(list(x for x in islice(g,0,None,2))) what you want to do is to slice before you transform: >>> g = (x for x in islice(X, 0, None, 2)) >>> print(list(f(x) for x in g)) eval: 0 eval: 2 eval: 4 eval: 6 eval: 8 [0, 2, 4, 6, 8] > islice execute the function at the generator and drop the elements > that aren't in the slice. I found that pretty weird, the way that i > see generators is like an association between and indexing set (an > iterator or another generator) and a computation that is made indexed > by the indexing set, and islice is like a "transformation" on the > indexing set,it doesn't matter the result of the function, the slice > should act only on the indexing set, some other "transformation" like > takewhile act on the result so, the execution it has to be made, but > in the islice, or other "transformation" that act only in the indexing > set, the function shouldn't be executed at each element, but only on > that new set that result of the application of the "transformation" on > the original set. that seems like an extremely lazy evaluation, I don't know if even a true lazy language do that. Python is a strict language, with a few laziness provided by generators, in the end it's still a strict language. > Well, it works for what i need, but is not very neat, and i think that > there it should be a formal way to act on the base indexing iterator, > such way exists? Is there a better approach to get what i need? Reverse your operation. From dbd at ieee.org Mon Dec 7 00:43:28 2009 From: dbd at ieee.org (dbd) Date: Sun, 6 Dec 2009 21:43:28 -0800 (PST) Subject: Float precision and float equality References: <2f0dee67-6fda-47c0-8266-d2d6b02ed655@e4g2000prn.googlegroups.com> <574bd33c-a38b-4af5-802e-fc081965a230@g23g2000vbr.googlegroups.com> <6624fc07-c6d5-40e1-a899-6eb73603a980@u8g2000prd.googlegroups.com> <335cb11d-e862-4daa-aec6-8f96b56bc28a@u1g2000pre.googlegroups.com> <79c41269-2b84-4fb1-8694-c7212f92be62@d9g2000prh.googlegroups.com> <49d04d6f-551b-46a9-8a11-7abe308a0154@f10g2000vbl.googlegroups.com> Message-ID: On Dec 6, 1:48?pm, sturlamolden wrote: > On 6 Des, 21:52, r0g wrote: > > > > .> Right. ?Using abs(x-y) < eps is the way to go. > > > .> > > > .> Raymond > > > > This only works when abs(x) and abs(y) are larger that eps, but not > > > too much larger. > > > Okay, I'm confused now... I thought them being larger was entirely the > > point. > > Yes. dbd got it wrong. If both a smaller than eps, the absolute > difference is smaller than eps, so they are considered equal. Small x,y failure case: eps and even eps squared are representable as floats. If you have samples of a sine wave with peak amplitude of one half eps, the "abs(x- y) < eps" test would report all values on the sine wave as equal to zero. This would not be correct. Large x,y failure case: If you have two calculation paths that symbolically should produce the same value of size one over eps, valid floating point implementations may differ by an lsb or more. An single lsb error would be 1, much greater than the test allows as 'nearly equal' for floating point comparison. 1.0 + eps is the smallest value greater than 1.0, distinguishable from 1.0. Long chains of floating point calculations that would symbolically be expected to produce a value of 1.0 many be expected to produce errors of an eps or more due to the inexactness of floating point representation. These errors should be allowed in floating point equality comparison. The value of the minimum representable error will scale as the floating point number varies. A constant comparison value is not appropriate. Mark was right, DaveA's discussion explains a strategy to use. Dale B. Dalrymple From zephjc at gmail.com Mon Dec 7 01:40:07 2009 From: zephjc at gmail.com (zeph) Date: Sun, 6 Dec 2009 22:40:07 -0800 (PST) Subject: What is the significance of after() in this code? References: Message-ID: On Dec 6, 8:46?pm, Benjamin Kaplan wrote: > On Sun, Dec 6, 2009 at 10:29 PM, W. eWatson wrote: > > See Subject. > > ? ?def StackImages(self): > > ? ? ? ?self.Upload("P") > > ? ? ? ?self.after_id = self.master.after(10000,self.GetFrameOne) > > -- > >http://mail.python.org/mailman/listinfo/python-list > > I think this is close to winning an award for "least information > provided". How are we supposed to know with the information you gave > us? We don't know what package you're using, what type anything is, or > even the purpose of that method. Try putting this line in there > somewhere > print type(self.master) > > and then open up the interactive interpreter, import whatever you need and do > help(.after) True, though by *context* the after method looks like it takes a time (probably in milliseconds, given its size), and a method, and calls the method after that amount of time, and returning some process/ thread id to self.after_id. Though if that's right, we still don't know if its synchronous or not, if its calling it in a new thread or a new process, etc etc. From wuwei23 at gmail.com Mon Dec 7 01:43:27 2009 From: wuwei23 at gmail.com (alex23) Date: Sun, 6 Dec 2009 22:43:27 -0800 (PST) Subject: What is the significance of after() in this code? References: Message-ID: <50984412-7faf-4e6b-a58e-277bd1e9df80@x25g2000prf.googlegroups.com> zeph wrote: > True, though by *context* the after method looks like it takes a time > (probably in milliseconds, given its size), and a method, and calls > the method after that amount of time, and returning some process/ > thread id to self.after_id. ?Though if that's right, we still don't > know if its synchronous or not, if its calling it in a new thread or a > new process, etc etc. "Please tell me what this function does based solely on its name and signature" is _still_ a ridiculous question, though, even given the context you can extrapolate from it. From pfeldman at verizon.net Mon Dec 7 01:47:48 2009 From: pfeldman at verizon.net (Dr. Phillip M. Feldman) Date: Sun, 6 Dec 2009 22:47:48 -0800 (PST) Subject: how to convert string function to string method? Message-ID: <26673209.post@talk.nabble.com> I wrote a handy-dandy function (see below) called "strip_pairs" for stripping matching pairs of characters from the beginning and end of a string. This function works, but I would like to be able to invoke it as a string method rather than as a function. Is this possible? def strip_pairs(s=None, open='([{\'"', close=')]}\'"'): """This function strips matching pairs of characters from the beginning and end of the input string `s`. `open` and `close` specify corresponding pairs of characters, and must be equal-length strings. If `s` begins with a character in `open` and ends with the corresponding character in `close`, both are removed from the string. This process continues until no further matching pairs can be removed.""" if len(open) != len(close): raise Exception, \ '\'open\' and \'close\' arguments must be strings of equal length.' # If input is missing or is not of type `str` (or `unicode`), return None: if s is None or not isinstance(s,(str,unicode)): return None while len(s) >= 2: # Check whether first character of `s` is in `open`: i= open.find(s[0]) # If `s` does not begin with a character from `open`, there are no more # pairs to be stripped: if i == -1: break # If `s` does not begin and end with matching characters, there are no # more pairs to be stripped: if s[-1] != close[i]: break # Strip the first and last character from `s`: s= s[1:-1] return s -- View this message in context: http://old.nabble.com/how-to-convert-string-function-to-string-method--tp26673209p26673209.html Sent from the Python - python-list mailing list archive at Nabble.com. From apt.shansen at gmail.com Mon Dec 7 02:20:36 2009 From: apt.shansen at gmail.com (Stephen Hansen) Date: Sun, 6 Dec 2009 23:20:36 -0800 Subject: how to convert string function to string method? In-Reply-To: <26673209.post@talk.nabble.com> References: <26673209.post@talk.nabble.com> Message-ID: <7a9c25c20912062320s674ce1ddt213c59e5da4144f3@mail.gmail.com> On Sun, Dec 6, 2009 at 10:47 PM, Dr. Phillip M. Feldman < pfeldman at verizon.net> wrote: > > I wrote a handy-dandy function (see below) called "strip_pairs" for > stripping > matching pairs of characters from the beginning and end of a string. This > function works, but I would like to be able to invoke it as a string method > rather than as a function. Is this possible? > No. String objects are immutable and you can not set new attributes/methods on the type itself. Really the best thing to do in this case is to just have this in an easy to access library, and call it as a function and not a string method. The only alternative is to create a string subtype which has a new method-- but that would require all the strings you're using to be this subclass. E.g. you'd have to do MyString(regular_String) for each. This is really IMHO unwieldy and not really worth the effort -- just put strip_pairs into a library and call it as a function. --S -------------- next part -------------- An HTML attachment was scrubbed... URL: From alfps at start.no Mon Dec 7 02:36:40 2009 From: alfps at start.no (Alf P. Steinbach) Date: Mon, 07 Dec 2009 08:36:40 +0100 Subject: Are routine objects guaranteed mutable & with dictionary? In-Reply-To: References: <4a2a7fdf-99d4-4219-a56c-7cd9146b3c85@f20g2000prn.googlegroups.com> Message-ID: * MRAB: > Alf P. Steinbach wrote: > > * Dennis Lee Bieber: > >> On Sat, 05 Dec 2009 11:26:34 +0100, "Alf P. Steinbach" > >> declaimed the following in > >> gmane.comp.python.general: > >> > >>> The devolution of terminology has been so severe that now even the > >>> Wikipedia article on this subject confounds the general concept of > >>> "routine" with the far more specialized term "sub-routine", which > >>> is just one kind of routine. It is of > >> > >> Well, if this were a FORTRAN IV text from the mid-70s you'd be > >> talking about > >> > >> function subprograms > >> and > >> subroutine subprograms > > > > It's in that direction yes, but the distinction that you mention, > > which is essentially the same as Pascal 'function' versus > > 'procedure', or Visual Basic 'function' versus 'sub', is just a > > distinction of two variants of subroutines. > > > > Up above there is the more general concept of a routine, where there > > are more possibilites than just subroutines; Python generators are > > one example. > > > > As I mentioned earlier, in Eiffel, which is a more modern language > > than Fortran, routines are still called routines. And specialized > > terms include "routine". So it's not like that language independent > > terminology has been phased out in general; it's mostly only in the C > > syntax family (e.g. Python operators come mostly from C) that > > "function" is, misleadingly and with associated severe constraints, > > used as a general term. > > > In C there were originally only functions; if you didn't specify a > return type then it would default to 'int' ('void' was a later > addition). > > In Python there are only functions; if you don't explicitly return a > value then None is returned. > > The distinction between functions and procedures can be helpful in > deciding whether something is Pythonic (for example, in the use of list > comprehensions), but in reality they are all still functions. I'm sorry, but, first, looking at ways to emulate a syntax, thinking about whether something looks like mathematical functions, the eye-candy, is pretty irrelevant, at least IMO. To see that it is irrelevant you might consider how that works in assembly language. Or you might consider that a call of a C++ 'void' routine can be used in C++ expressions. I think that even by your mainly visual syntax criterion that must be difficult to think of as a "function". Another way of looking at it is that the information conveyed by a result restricted to N=1 possible significant values, such as Python None or C arbitrary value (all possible return values of a non-result-producing routine to be treated as the same), is log(N)/log(2) = log(1)/whatever = 0, i.e., the routine then produces zero information via its expression result. Second, what's discussed isn't the distinction between various kinds of subroutines, so that wrt. to the earlier thread it's at best a detail. Although I think that the distinction that you and Dennis raise *is* a useful discussion! :-) Cheers & hth., - Alf From aioe.org at technicalbloke.com Mon Dec 7 03:09:03 2009 From: aioe.org at technicalbloke.com (r0g) Date: Mon, 07 Dec 2009 08:09:03 +0000 Subject: python proxy checker ,change to threaded version References: Message-ID: elca wrote: > Hello ALL, > > i have some python proxy checker . > > and to speed up check, i was decided change to mutlthreaded version, > > and thread module is first for me, i was tried several times to convert to > thread version > > and look for many info, but it not so much easy for novice python programmar > . > > if anyone can help me really much appreciate!! > > thanks in advance! > > > import urllib2, socket > > socket.setdefaulttimeout(180) > # read the list of proxy IPs in proxyList > proxyList = open('listproxy.txt').read() > > def is_bad_proxy(pip): > try: > proxy_handler = urllib2.ProxyHandler({'http': pip}) > opener = urllib2.build_opener(proxy_handler) > opener.addheaders = [('User-agent', 'Mozilla/5.0')] > urllib2.install_opener(opener) > req=urllib2.Request('http://www.yahoo.com') # <---check whether > proxy alive > sock=urllib2.urlopen(req) > except urllib2.HTTPError, e: > print 'Error code: ', e.code > return e.code > except Exception, detail: > > print "ERROR:", detail > return 1 > return 0 > > > for item in proxyList: > if is_bad_proxy(item): > print "Bad Proxy", item > else: > print item, "is working" The trick to threads is to create a subclass of threading.Thread, define the 'run' function and call the 'start()' method. I find threading quite generally useful so I created this simple generic function for running things in threads... def run_in_thread( func, func_args=[], callback=None, callback_args=[] ): import threading class MyThread ( threading.Thread ): def run ( self ): # Call function if function_args: result = function(*function_args) else: result = function() # Call callback if callback: if callback_args: callback(result, *callback_args) else: callback(result) MyThread().start() You need to pass it a test function (+args) and, if you want to get a result back from each thread you also need to provide a callback function (+args). The first parameter of the callback function receives the result of the test function so your callback would loo something like this... def cb( result, item ): if result: print "Bad Proxy", item else: print item, "is working" And your calling loop would be something like this... for item in proxyList: run_in_thread( is_bad_proxy, func_args=[ item ], cb, callback_args=[ item ] ) Also, you might want to limit the number of concurrent threads so as not to overload your system, one quick and dirty way to do this is... import time if threading.activeCount() > 9: time.sleep(1) Note, this is a far from exact method but it works well enough for one off scripting use Hope this helps. Suggestions from hardcore pythonistas on how to my make run_in_thread function more elegant are quite welcome also :) Roger Heathcote From martin.hellwig at dcuktec.org Mon Dec 7 03:10:02 2009 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Mon, 07 Dec 2009 08:10:02 +0000 Subject: What is the significance of after() in this code? In-Reply-To: References: Message-ID: W. eWatson wrote: > See Subject. > def StackImages(self): > self.Upload("P") > self.after_id = self.master.after(10000,self.GetFrameOne) If you are talking tkinter here, it is an alarm callback. See http://effbot.org/tkinterbook/widget.htm -- MPH http://blog.dcuktec.com 'If consumed, best digested with added seasoning to own preference.' From highcar at gmail.com Mon Dec 7 03:16:46 2009 From: highcar at gmail.com (elca) Date: Mon, 7 Dec 2009 00:16:46 -0800 (PST) Subject: python proxy checker ,change to threaded version In-Reply-To: References: <26672548.post@talk.nabble.com> Message-ID: <26673953.post@talk.nabble.com> r0g wrote: > > elca wrote: >> Hello ALL, >> >> i have some python proxy checker . >> >> and to speed up check, i was decided change to mutlthreaded version, >> >> and thread module is first for me, i was tried several times to convert >> to >> thread version >> >> and look for many info, but it not so much easy for novice python >> programmar >> . >> >> if anyone can help me really much appreciate!! >> >> thanks in advance! >> >> >> import urllib2, socket >> >> socket.setdefaulttimeout(180) >> # read the list of proxy IPs in proxyList >> proxyList = open('listproxy.txt').read() >> >> def is_bad_proxy(pip): >> try: >> proxy_handler = urllib2.ProxyHandler({'http': pip}) >> opener = urllib2.build_opener(proxy_handler) >> opener.addheaders = [('User-agent', 'Mozilla/5.0')] >> urllib2.install_opener(opener) >> req=urllib2.Request('http://www.yahoo.com') # <---check >> whether >> proxy alive >> sock=urllib2.urlopen(req) >> except urllib2.HTTPError, e: >> print 'Error code: ', e.code >> return e.code >> except Exception, detail: >> >> print "ERROR:", detail >> return 1 >> return 0 >> >> >> for item in proxyList: >> if is_bad_proxy(item): >> print "Bad Proxy", item >> else: >> print item, "is working" > > > > The trick to threads is to create a subclass of threading.Thread, define > the 'run' function and call the 'start()' method. I find threading quite > generally useful so I created this simple generic function for running > things in threads... > > > def run_in_thread( func, func_args=[], callback=None, callback_args=[] ): > import threading > class MyThread ( threading.Thread ): > def run ( self ): > > # Call function > if function_args: > result = function(*function_args) > else: > result = function() > > # Call callback > if callback: > if callback_args: > callback(result, *callback_args) > else: > callback(result) > > MyThread().start() > > > You need to pass it a test function (+args) and, if you want to get a > result back from each thread you also need to provide a callback > function (+args). The first parameter of the callback function receives > the result of the test function so your callback would loo something > like this... > > def cb( result, item ): > if result: > print "Bad Proxy", item > else: > print item, "is working" > > > And your calling loop would be something like this... > > for item in proxyList: > run_in_thread( is_bad_proxy, func_args=[ item ], cb, callback_args=[ > item ] ) > > > Also, you might want to limit the number of concurrent threads so as not > to overload your system, one quick and dirty way to do this is... > > import time > if threading.activeCount() > 9: time.sleep(1) > > Note, this is a far from exact method but it works well enough for one > off scripting use > > Hope this helps. > > > Suggestions from hardcore pythonistas on how to my make run_in_thread > function more elegant are quite welcome also :) > > > Roger Heathcote > -- > http://mail.python.org/mailman/listinfo/python-list > > Hello :) thanks for your reply ! i will test it now and will comment soon thanks again -- View this message in context: http://old.nabble.com/python-proxy-checker-%2Cchange-to-threaded-version-tp26672548p26673953.html Sent from the Python - python-list mailing list archive at Nabble.com. From __peter__ at web.de Mon Dec 7 03:25:33 2009 From: __peter__ at web.de (Peter Otten) Date: Mon, 07 Dec 2009 09:25:33 +0100 Subject: how to convert string function to string method? References: Message-ID: Dr. Phillip M. Feldman wrote: > I wrote a handy-dandy function (see below) called "strip_pairs" for > stripping > matching pairs of characters from the beginning and end of a string. This > function works, but I would like to be able to invoke it as a string > method > rather than as a function. Is this possible? This requires a feature called "open classes" (Ruby has them). It is not possible in Python, at least for built-in types like str. Peter From steven at REMOVE.THIS.cybersource.com.au Mon Dec 7 03:27:55 2009 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 07 Dec 2009 08:27:55 GMT Subject: Float precision and float equality References: <3abf9dfb-fa01-4f71-9214-a06d8b847ebf@e20g2000vbb.googlegroups.com> <6474d583-e797-45d1-af81-7bca5072a3b9@a39g2000pre.googlegroups.com> Message-ID: On Sun, 06 Dec 2009 14:54:37 -0800, Carl Banks wrote: > (I remember once struggling in a homework assignment over seemingly > large discrepancies in a calculation I was doing, until i realized that > the actual numbers were on the scale of 10**11, and the difference was > around 10**1, so it really didn't matter.) Well that depends on the accuracy of the calculations, surely? If the calculations were accurate to one part in 10**20, then an error around 10**1 is about ten trillion times larger than acceptable. *wink* -- Steven From aioe.org at technicalbloke.com Mon Dec 7 03:37:47 2009 From: aioe.org at technicalbloke.com (r0g) Date: Mon, 07 Dec 2009 08:37:47 +0000 Subject: how to convert string function to string method? References: Message-ID: Dr. Phillip M. Feldman wrote: > I wrote a handy-dandy function (see below) called "strip_pairs" for stripping > matching pairs of characters from the beginning and end of a string. This > function works, but I would like to be able to invoke it as a string method > rather than as a function. Is this possible? > > def strip_pairs(s=None, open='([{\'"', close=')]}\'"'): > """This function strips matching pairs of characters from the beginning > and > end of the input string `s`. `open` and `close` specify corresponding > pairs > of characters, and must be equal-length strings. If `s` begins with a > character in `open` and ends with the corresponding character in `close`, > both are removed from the string. This process continues until no > further > matching pairs can be removed.""" > > if len(open) != len(close): raise Exception, \ > '\'open\' and \'close\' arguments must be strings of equal length.' > > # If input is missing or is not of type `str` (or `unicode`), return > None: > if s is None or not isinstance(s,(str,unicode)): return None > > while len(s) >= 2: > > # Check whether first character of `s` is in `open`: > i= open.find(s[0]) > > # If `s` does not begin with a character from `open`, there are no > more > # pairs to be stripped: > if i == -1: break > > # If `s` does not begin and end with matching characters, there are no > # more pairs to be stripped: > if s[-1] != close[i]: break > > # Strip the first and last character from `s`: > s= s[1:-1] > > return s I've never tried it but I think it is possible to inject new methods into existing classes, see... http://www.daniel-lemire.com/blog/archives/2005/12/21/metaclass-programming-in-python/ Not sure how good an idea it would be though, I have heard it refered to as "monkey patching" and I can imagine doing it to classes as fundamental as the string class could have negative performace consequences. Roger. From tsviki.hirsh at gmail.com Mon Dec 7 03:42:47 2009 From: tsviki.hirsh at gmail.com (Tsviki Hirsh) Date: Mon, 7 Dec 2009 10:42:47 +0200 Subject: dict.fromkeys strange behavior Message-ID: <8a0588790912070042j5954f48u360f3cfabf19bf12@mail.gmail.com> Dear list, I'm trying to create a dictionary from set of keys and values using dict.fromkeys When I type: >>>dict.fromkeys('a',50) the output is: {'a': 50} This is fine, but when I try to set the same value to a different name key: >>>dict.fromkeys('at',50) the output now is: {'a': 50, 't': 50} This is obviously not what I wanted. What are the alternatives? Thanks a lot Tsviki Hirsh -------------- next part -------------- An HTML attachment was scrubbed... URL: From bruno.42.desthuilliers at websiteburo.invalid Mon Dec 7 03:46:30 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 07 Dec 2009 09:46:30 +0100 Subject: how to convert string function to string method? In-Reply-To: References: Message-ID: <4b1cc0e6$0$14670$426a74cc@news.free.fr> Dr. Phillip M. Feldman a ?crit : > I wrote a handy-dandy function (see below) called "strip_pairs" for stripping > matching pairs of characters from the beginning and end of a string. This > function works, but I would like to be able to invoke it as a string method > rather than as a function. Is this possible? No. Basic type (strings/unicode, numerics, lists, tuples, dicts etc) are not "opened" to monkeypatching. Partly for performance reasons, partly to avoid the insanity that we've seen in the Ruby world where everyone and it's little sisters extends basic types with tons of more or less usefull and often conflicting features. > def strip_pairs(s=None, open='([{\'"', close=')]}\'"'): Why a default value of None for the first param ??? > """This function strips matching pairs of characters from the beginning > and > end of the input string `s`. `open` and `close` specify corresponding > pairs > of characters, and must be equal-length strings. If `s` begins with a > character in `open` and ends with the corresponding character in `close`, > both are removed from the string. This process continues until no > further > matching pairs can be removed.""" > > if len(open) != len(close): raise Exception, \ > '\'open\' and \'close\' arguments must be strings of equal length.' Please use proper exception types. Here you want a ValueError. Also, you just dont care whether open and close are proper strings - any sequence of characters would do. > # If input is missing or is not of type `str` (or `unicode`), return > None: > if s is None or not isinstance(s,(str,unicode)): return None If s is None, it won't be a str or unicode instance, so the test is redundant !-) But anyway : if this function is supposed to operate on strings, don't accept None (and even less provide it as default), and don't fail silently - you should really raise a TypeError here IMHO. > while len(s) >= 2: > > # Check whether first character of `s` is in `open`: > i= open.find(s[0]) > > # If `s` does not begin with a character from `open`, there are no > more > # pairs to be stripped: > if i == -1: break > > # If `s` does not begin and end with matching characters, there are no > # more pairs to be stripped: > if s[-1] != close[i]: break > > # Strip the first and last character from `s`: > s= s[1:-1] > > return s HTH From steven at REMOVE.THIS.cybersource.com.au Mon Dec 7 03:49:28 2009 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 07 Dec 2009 08:49:28 GMT Subject: how to convert string function to string method? References: Message-ID: On Sun, 06 Dec 2009 22:47:48 -0800, Dr. Phillip M. Feldman wrote: > I wrote a handy-dandy function (see below) called "strip_pairs" for > stripping matching pairs of characters from the beginning and end of a > string. This function works, but I would like to be able to invoke it > as a string method rather than as a function. Is this possible? Not exactly. You can subclass string and add such a method: class MyString(str): def strip_pairs(self, ...): ... but then you have to convert every string to a MyString before you use it. That way leads to madness. Better to just use a function. Don't worry, you're allowed to mix functional and OO code :) As for the function, I think we can re-write it to be a bit more Pythonic. We start with a helper function. (Since it's a one-liner, that's not strictly necessary.) def bracketed_by(s, open, close): """Return True if string s is bracketed by open and close pairs.""" # I'm too lazy to put proper error handling here... return s.startswith(open) and s.endswith(close) # UNTESTED def strip_pairs(s, open='([{\'"', close=')]}\'"'): if len(open) != len(close): raise ValueError( "'open' and 'close' arguments must be equal length strings.") if not isinstance(s, basestring): # FIX ME: this wrongly fails on UserString arguments. raise TypeError('argument must be a string') pairs = zip(open, close) while any(bracketed_by(s, a, b) for (a,b) in pairs): s = s[1:-1] return s The above is written for simplicity rather than efficiency -- for small strings, say, under a couple of megabytes, it is likely to be faster than a more "clever" algorithm. If you are routinely dealing with strings which are tens of megabytes in size, bracketed by dozens or hundreds of pairs of brackets, then the above may be a little slow. But for small strings, it will probably be faster than a routine which tries to be smarter at avoiding copying strings. -- Steven From __peter__ at web.de Mon Dec 7 04:12:38 2009 From: __peter__ at web.de (Peter Otten) Date: Mon, 07 Dec 2009 10:12:38 +0100 Subject: Exception classes don't follow pickle protocol, problems unpickling References: <4b1b96e2$0$22938$e4fe514c@news.xs4all.nl> Message-ID: Irmen de Jong wrote: > I am puzzled why Python's exception classes don't seem to follow the > pickle protocol. To be more specific: an instance of a user defined > exception, subclassed from Exception, cannot be pickled/unpickled > correctly in the expected way. > > The pickle protocol says that: > __getinitargs__ is used if you want __init__ to be called for old-style > classes __getnewargs__ is used if you want to pass params to __new__ for > new-style classes __getstate__ is used to determine what to pickle instead > of the objects __dict__ > > None of these are used when pickling Exception objects! > I've pasted some test code at the end of this message that creates a > normal object and an object derived from Exception, and pickles them both. > Then it unpickles them. The output is: > So there are 2 problems: the pickle protocol isn't used when exception > objects (or instances of classes derived from Exception) are pickled, and > during unpickling, it then > crashes because it calls __init__ with the wrong amount of parameters. > (why is it bothering with __init__ anyway? Aren't exceptions new style > classes?) The __reduce__() method is called when you pickle an object. It returns an argument tuple and a factory. For exceptions that factory is the class which is why __init__() is called when the object is unpickled. > This started happening in Python 2.5, Python 2.4 works without error. > > What is causing this? I think Exceptions need special treatment because they have state that is not stored in the instance __dict__. > How can I best solve this error? You could override __reduce__() to call __getstate__(). I don't see the need for __getnewargs__() because exceptions aren't immutable. Peter From clp2 at rebertia.com Mon Dec 7 04:14:05 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Mon, 7 Dec 2009 01:14:05 -0800 Subject: dict.fromkeys strange behavior In-Reply-To: <8a0588790912070042j5954f48u360f3cfabf19bf12@mail.gmail.com> References: <8a0588790912070042j5954f48u360f3cfabf19bf12@mail.gmail.com> Message-ID: <50697b2c0912070114r51f106f1lcfbadb646dfa99cd@mail.gmail.com> On Mon, Dec 7, 2009 at 12:42 AM, Tsviki Hirsh wrote: > Dear list, > I'm trying to create a dictionary from set of keys and values using > dict.fromkeys > When I type: >>>>dict.fromkeys('a',50) > the output is: > {'a': 50} > This is fine, but when I try to set the same value to a different name key: >>>>dict.fromkeys('at',50) > the output now is: > {'a': 50, 't': 50} > This is obviously not what I wanted. > What are the alternatives? >>> dict.fromkeys(['at'],50) {'at': 50} Remember that strings are collections too (of individual characters). Cheers, Chris -- http://blog.rebertia.com From jeanmichel at sequans.com Mon Dec 7 05:04:06 2009 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Mon, 07 Dec 2009 11:04:06 +0100 Subject: subprocess kill In-Reply-To: References: <5f755846-e79d-444b-b608-86f5823540e8@j19g2000yqk.googlegroups.com> <68cd2042-cd2a-43a8-97ae-2893f181168c@c3g2000yqd.googlegroups.com> <011ae123-d777-438c-83b6-f6600c1dfde1@m25g2000yqc.googlegroups.com> <786e4fb7-1f03-45d5-9be0-55926387283f@s20g2000yqd.googlegroups.com> Message-ID: <4B1CD316.8020907@sequans.com> luca72 wrote: > On 5 Dic, 03:06, Carl Banks wrote: > >> On Dec 4, 3:44 pm, luca72 wrote: >> >> >> >> >>> On 5 Dic, 00:14, luca72 wrote: >>> >>>> On 5 Dic, 00:03, luca72 wrote: >>>> >>>>> On 4 Dic, 23:23, Mike Driscoll wrote: >>>>> >>>>>> On Dec 4, 3:50 pm, luca72 wrote: >>>>>> >>>>>>> Hello i'm using subprocess in this way: >>>>>>> self.luca = subprocess.Popen(['/usr/bin/ >>>>>>> dvbtune'+frase_sint],shell=True, stdout=self.f_s_l,stderr=self.f_s_e ) >>>>>>> >>>>>>> then i kill: >>>>>>> self.luca.Kill() >>>>>>> >>>>>>> but the process is still active and the file self.f_s_l increase it >>>>>>> size because the process is not killed. >>>>>>> >>>>>>> How i can kill the process? >>>>>>> Regards >>>>>>> >>>>>>> Luca >>>>>>> >>>>>> Seehttp://lmgtfy.com/?q=python+kill+subprocess+linux >>>>>> >>>>>> When I do that on my machine, the 2nd result has the answer: >>>>>> >>>>>> http://stackoverflow.com/questions/1064335/in-python-2-5-how-do-i-kil... >>>>>> >>>>>> ------------------- >>>>>> Mike Driscoll >>>>>> >>>>>> Blog: http://blog.pythonlibrary.org >>>>>> >>>>> Hello Mike i have also test but they never kill the process the file >>>>> (stdout=self.f_s_l) increase it's size, haveyou some idea. >>>>> also if i close the program the process is still active. >>>>> >>>>> Regards >>>>> >>>>> Luca >>>>> >>>> i'm able only to kill via shell like kill -9 process pid, Why? >>>> >>> Now the only way to solve the problem is to call a c program that kill >>> the process via subprocess in other case i can't close it, i have also >>> try with >>> >>> subprocess.Popen(['kill -9 dvbtune'] shell=True), but the process is >>> still active >>> >> This is not working because the kill command does not accept the name >> of a program. You have to give it a process id. >> >> As for your general question, we really can't answer it. There a lot >> of reasons a process might not die when you try to kill it: it could >> be trapping and ignoring signals (which is rude but it happens), it >> could be stuck in a critical section, the program might be threaded >> and not handling signals well, the program might have forked itself >> and the original process id has disappeared, etc. We can't read your >> mind or divine what's running on your computer, so we can't answer >> your question. We can only suggest things that might be wrong. It's >> up to you to investigate and/or dig deeper. >> >> Carl Banks >> > > The firs thing that i have tested is with the process id get by > Popen.pid ,but it don't works. > Thank I'm no specialist of linux stuff but the google link suggests that child PID may not be killed when killing the parent PID. When using shell=True, your process is started in a shell, meaning the PID of your subprocess is not self.luca.pid, self.luca.pid is the PID of the shell. - You might try to kill the pid of your subprocess explicitly (you can't use self.luca.pid directly but you can filter the process list using this parentID) - If the argument shell=True is not absolutely required, you may set it to false, self.luca.pid will then *be* the pid of your process JM From victorsubervi at gmail.com Mon Dec 7 05:25:07 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Mon, 7 Dec 2009 05:25:07 -0500 Subject: unsupported operand type(s) for %: 'NoneType' and 'tuple' Message-ID: <4dc0cfea0912070225s3079a060xcf70c9285430feef@mail.gmail.com> Hi; I get the following error: /var/www/html/angrynates.com/cart/createCats2.py 111 112 113 ''' 114 115 createCats2() createCats2 = /var/www/html/angrynates.com/cart/createCats2.py in createCats2() 85 for standAloneStore in storePrimaryStandAlone: 86 allStores.append(standAloneStore) 87 tree = catTree(allStores) 88 for store in allStores: 89 i = 0 tree undefined, global catTree = , allStores = ['products', 'prescriptions'] /var/www/html/angrynates.com/cart/catTree.py in catTree(allStores=['products', 'prescriptions']) 76 returnFlag = 'gotNoStuff' 77 if returnFlag == 'gotStuff': 78 return printTree(allTrees) 79 else: 80 return '' global printTree = , allTrees = [{'prodCat1': {}, 'prodCat2': {}}, {'presCat1': {}, 'presCat2': {}}] /var/www/html/angrynates.com/cart/catTree.py in printTree(allTrees=[{'prodCat1': {}, 'prodCat2': {}}, {'presCat1': {}, 'presCat2': {}}], level=0) 12 for name in sorted(aTree.keys()): 13 print '\t' * level, name 14 tree.append("%s%s") % ("\t" * level, name) 15 printTree(aTree[name], level + 1) 16 tree = ['%s%s'], tree.append = , level = 0, name = 'prodCat1' TypeError: unsupported operand type(s) for %: 'NoneType' and 'tuple' args = ("unsupported operand type(s) for %: 'NoneType' and 'tuple'",) But according to the same error, level = 0 [the NoneType, I presume] and name = 'prodCat1', which is most certainly not a tuple! Why the error? TIA, Victor -------------- next part -------------- An HTML attachment was scrubbed... URL: From contact at xavierho.com Mon Dec 7 05:37:10 2009 From: contact at xavierho.com (Xavier Ho) Date: Mon, 7 Dec 2009 20:37:10 +1000 Subject: unsupported operand type(s) for %: 'NoneType' and 'tuple' In-Reply-To: <4dc0cfea0912070225s3079a060xcf70c9285430feef@mail.gmail.com> References: <4dc0cfea0912070225s3079a060xcf70c9285430feef@mail.gmail.com> Message-ID: <2d56febf0912070237q6317286bt922d694c4d2478fd@mail.gmail.com> Hi Victor, the .append function doesn't return anything, so it's a None. And you should have it inside the parentheses. >>> tree.append("%s%s" % ("\t" * level, name)) is probably what you're after. Cheers, Xav -------------- next part -------------- An HTML attachment was scrubbed... URL: From bruno.42.desthuilliers at websiteburo.invalid Mon Dec 7 06:02:32 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 07 Dec 2009 12:02:32 +0100 Subject: how to convert string function to string method? In-Reply-To: References: Message-ID: <4b1ce0c7$0$21169$426a74cc@news.free.fr> r0g a ?crit : (snip) > I've never tried it but I think it is possible to inject new methods > into existing classes, see... Doesn't work for most builtin types - for both performances and sanity reasons. From urbangabo at gmail.com Mon Dec 7 06:57:02 2009 From: urbangabo at gmail.com (Gabor Urban) Date: Mon, 7 Dec 2009 12:57:02 +0100 Subject: Two questions ( Oracle and modules ) Message-ID: Hi guys, I have two questions. 1. I have choice to introduce Python to my new employee. We are to write and application that uses databases stored partially in Oracle 10 and partially in Oracle 11. We have to execute standard SQL commands and stored procedures as well. Which is best conection / module to use. A couple of years ago we had DCOracle2 for the same task, but is written for Oracle8, so I gues it might not be a good idea to use. What is your oppinion? 2. We have tp write a module that will be imported a couple of places. Though we must be sure, this module's initialization is performed only once. How can we implement this? I do not know what to google for..... Gabor -- Linux: Choice of a GNU Generation From wolftracks at invalid.com Mon Dec 7 07:13:12 2009 From: wolftracks at invalid.com (W. eWatson) Date: Mon, 07 Dec 2009 04:13:12 -0800 Subject: What is the significance of after() in this code? In-Reply-To: References: Message-ID: Martin P. Hellwig wrote: > W. eWatson wrote: >> See Subject. >> def StackImages(self): >> self.Upload("P") >> self.after_id = self.master.after(10000,self.GetFrameOne) > > If you are talking tkinter here, it is an alarm callback. > See http://effbot.org/tkinterbook/widget.htm > Very good. I recall encountering this once before. I knew it had to be something like that, since the code does not provide a method called after(). From jeanmichel at sequans.com Mon Dec 7 07:14:12 2009 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Mon, 07 Dec 2009 13:14:12 +0100 Subject: unsupported operand type(s) for %: 'NoneType' and 'tuple' In-Reply-To: <4dc0cfea0912070225s3079a060xcf70c9285430feef@mail.gmail.com> References: <4dc0cfea0912070225s3079a060xcf70c9285430feef@mail.gmail.com> Message-ID: <4B1CF194.4010805@sequans.com> Victor Subervi wrote: > > global printTree = , allTrees = [{'prodCat1': {}, > 'prodCat2': {}}, {'presCat1': {}, 'presCat2': {}}] > /var/www/html/angrynates.com/cart/catTree.py > in > printTree(allTrees=[{'prodCat1': {}, 'prodCat2': {}}, {'presCat1': {}, > 'presCat2': {}}], level=0) > 12 for name in sorted(aTree.keys()): > 13 print '\t' * level, name > 14 tree.append("%s%s") % ("\t" * level, name) > 15 printTree(aTree[name], level + 1) > 16 > tree = ['%s%s'], tree.append = object>, level = 0, name = 'prodCat1' > > TypeError: unsupported operand type(s) for %: 'NoneType' and 'tuple' > args = ("unsupported operand type(s) for %: 'NoneType' and > 'tuple'",) > > But according to the same error, level = 0 [the NoneType, I presume] > and name = 'prodCat1', which is most certainly not a tuple! Why the error? > TIA, > Victor Come on Victor, Given the error, you can easily see that tree.append("%s%s") % ("\t" * level, name) is involved in the error you get. The correct thing may be tree.append("%s%s" % ("\t" * level, name)) It should be easy for you to spot. FYI, tree.append('%s%s') returns None, then ("\t" * level, name) is the tuple applied to None through the % operator. That is why you get the above error. Cheers, JM From sturlamolden at yahoo.no Mon Dec 7 07:28:07 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Mon, 7 Dec 2009 04:28:07 -0800 (PST) Subject: Float precision and float equality References: <2f0dee67-6fda-47c0-8266-d2d6b02ed655@e4g2000prn.googlegroups.com> <574bd33c-a38b-4af5-802e-fc081965a230@g23g2000vbr.googlegroups.com> <6624fc07-c6d5-40e1-a899-6eb73603a980@u8g2000prd.googlegroups.com> <335cb11d-e862-4daa-aec6-8f96b56bc28a@u1g2000pre.googlegroups.com> <79c41269-2b84-4fb1-8694-c7212f92be62@d9g2000prh.googlegroups.com> <49d04d6f-551b-46a9-8a11-7abe308a0154@f10g2000vbl.googlegroups.com> Message-ID: On 7 Des, 06:43, dbd wrote: > If you have > samples of a sine wave with peak amplitude of one half eps, the "abs(x- > y) < eps" test would report all values on the sine wave as equal to > zero. This would not be correct. You don't understand this at all do you? If you have a sine wave with an amplitude less than the truncation error, it will always be approximately equal to zero. Numerical maths is about approximations, not symbolic equalities. > 1.0 + eps is the smallest value greater than 1.0, distinguishable from > 1.0. Which is the reason 0.5*eps*sin(x) is never distinguishable from 0. > A constant comparison value is not appropriate. That require domain specific knowledge. Sometimes we look at a significant number of digits; sometimes we look at a fixed number of decimals; sometimes we look at abs(y/x). But there will always be a truncation error of some sort, and differences less than that is never significant. > > Mark was right, DaveA's discussion explains a strategy to use. > > Dale B. Dalrymple From mcrute at gmail.com Mon Dec 7 07:50:47 2009 From: mcrute at gmail.com (Michael Crute) Date: Mon, 7 Dec 2009 07:50:47 -0500 Subject: Two questions ( Oracle and modules ) In-Reply-To: References: Message-ID: <558b73fb0912070450o5f907460q4cb3a51916e08dd5@mail.gmail.com> On Mon, Dec 7, 2009 at 6:57 AM, Gabor Urban wrote: > 1. I have choice to introduce Python to my new employee. We are to > write and application that uses databases stored partially in Oracle > 10 and partially in Oracle 11. We have to execute standard SQL > commands and stored procedures as well. Which is best conection / > module to use. A couple of years ago we had DCOracle2 for the same > task, but is written for Oracle8, so I gues it might not be a good > idea to use. What is your oppinion? cx_Oracle is the best way to connect to Oracle databases, DCOracle2 hasn't been maintained in some time. http://cx-oracle.sourceforge.net/ -mike -- Michael E. Crute http://mike.crute.org It is a mistake to think you can solve any major problem just with potatoes. --Douglas Adams From mal at egenix.com Mon Dec 7 07:51:02 2009 From: mal at egenix.com (M.-A. Lemburg) Date: Mon, 07 Dec 2009 13:51:02 +0100 Subject: python bijection In-Reply-To: References: <7n39ojF3jj6iuU1@mid.individual.net> <12c55890-118d-4655-b6c0-c908c9734a17@a32g2000yqm.googlegroups.com> <85100df7-a8b0-47e9-a854-ba8a8a2f3b98@r31g2000vbi.googlegroups.com> <4B17A960.1090700@egenix.com> <4B17FBFE.8070903@egenix.com> <4B18F685.8050102@egenix.com> Message-ID: <4B1CFA36.9060805@egenix.com> Terry Reedy wrote: > M.-A. Lemburg wrote: > >> Integrating an easy-to-use graph library into the collections >> module (and it's C companion) is good idea. >> >>>> This would have to be written in C, though, >>> That's currently in the works, along with database backing. >>> We'd welcome any help though... hint, hint... > > The current thinking among deveopers is that new modules should be > written and maintained in Python, which all implementations can use, > with speed-critical parts written in C for speed and imported by the > Python code. I don't think you are speaking for Python developers in general. The usual approach is to develop a prototype in Python and then rewrite it in C. Since the prototype is already there, what remains is the rewrite to get better performance. -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Dec 07 2009) >>> 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 our new mxODBC.Connect Python Database Interface 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 http://www.egenix.com/company/contact/ From mal at egenix.com Mon Dec 7 08:07:17 2009 From: mal at egenix.com (M.-A. Lemburg) Date: Mon, 07 Dec 2009 14:07:17 +0100 Subject: python bijection In-Reply-To: References: <4B17A960.1090700@egenix.com> <4B17FBFE.8070903@egenix.com> <4B18F685.8050102@egenix.com> <4B193610.6050700@mrabarnett.plus.com> <4b196d1f$1@dnews.tpgi.com.au> <5ac80cf9-d0fc-450e-b8bb-ffef91e81f0a@d10g2000yqh.googlegroups.com> <4b19ace0$1@dnews.tpgi.com.au> Message-ID: <4B1CFE05.4080401@egenix.com> Carl Banks wrote: > On Dec 4, 4:42 pm, Lie Ryan wrote: >> On 12/5/2009 9:41 AM, Carl Banks wrote: >> >> >> >> >> >>> On Dec 4, 12:46 pm, geremy condra wrote: >>> more common than full-blown graph package). >>>> Sure, its a tree, which is also a graph. In this case it looks to >>>> me more like a directed acyclic graph than anything, but its >>>> pretty much just semantics since the interface is functionally >>>> equivalent. >> >>> I'd have to agree with Lie, yes a tree is a graph, but it's simply not >>> an argument that Python community is grasping for graph structures. >>> It's like arguing that the Python community could benefit from a >>> quaternion type, because quaternions are actually heavily used in >>> Python, because a scalar number is a quarternion. >> >>> Carl Banks >> >>> (Would be +1 on a good graph implementation... just not because of >>> ElementTree.) >> >> I think this could be an interpretation of the Zen: >> >> Simple is better than complex. >> Complex is better than complicated. >> >> can be read as: >> List is better than Tree >> Tree is better than Graph >> >> not having Tree and Graph package in the standard library force most >> people to find List-based solution. And people that know they need >> graphs will find them in 3rd party modules. I have needed Trees a few >> times in python, but very rarely a Graph (except for playing around). >> YMDWV (your mileage definitely will vary). Trees are only a subset of general graphs and graphs often provide a more intuitive approach to problem representation than trying to squash all information into a tree or list. For certain problems, like e.g. dependency checking or routing, you can easily run into cycles which cannot be represented by trees (*). Furthermore, the property of being cycle-free (acyclic) is often one of the things you want to find out when dealing with graph data sets. (*) Note that Python does allow creating lists with cyclic references, but such usage is not really encouraged and will lead to delays in garbage collection: >>> l = [1,2,3] >>> l[2] = l >>> l [1, 2, [...]] -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Dec 07 2009) >>> 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 our new mxODBC.Connect Python Database Interface 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 http://www.egenix.com/company/contact/ From neilc at norwich.edu Mon Dec 7 08:17:54 2009 From: neilc at norwich.edu (Neil Cerutti) Date: 7 Dec 2009 13:17:54 GMT Subject: What is the significance of after() in this code? References: Message-ID: <7o4dk2F3j6jhmU2@mid.individual.net> On 2009-12-07, W. eWatson wrote: > See Subject. > def StackImages(self): > self.Upload("P") > self.after_id = self.master.after(10000,self.GetFrameOne) It's a violation of the Law of Demeter. -- Neil Cerutti From dickinsm at gmail.com Mon Dec 7 08:23:21 2009 From: dickinsm at gmail.com (Mark Dickinson) Date: Mon, 7 Dec 2009 05:23:21 -0800 (PST) Subject: Float precision and float equality References: <3abf9dfb-fa01-4f71-9214-a06d8b847ebf@e20g2000vbb.googlegroups.com> Message-ID: <93277fba-fed4-439c-952c-3de246f190c5@j24g2000yqa.googlegroups.com> On Dec 6, 7:34?pm, Anton81 wrote: > I do some linear algebra and whenever the prefactor of a vector turns > out to be zero, I want to remove it. Hmm. Comparing against zero is something of a special case. So you'd almost certainly be doing an 'if abs(x) < tol: ...' check, but the question is what value to use for tol, and that (again) depends on what you're doing. Perhaps 'tol' could be something like 'eps * scale', where 'eps' is an indication of the size of relative error you're prepared to admit (eps = 1e-12 might be reasonable; to allow for rounding errors, it should be something comfortably larger than the machine epsilon sys.float_info.epsilon, which is likely to be around 2e-16 for a typical machine), and 'scale' is something closely related to the scale of your problem: in your example, perhaps scale could be the largest of all the prefactors you have, or some sort of average of all the prefactors. There's really no one-size-fits-all easy answer here. > I'd like to keep the system comfortable. So basically I should write a > new class for numbers that has it's own __eq__ operator? That's probably not a good idea, for the reasons that Carl Banks already enumerated. Mark From neilc at norwich.edu Mon Dec 7 08:25:54 2009 From: neilc at norwich.edu (Neil Cerutti) Date: 7 Dec 2009 13:25:54 GMT Subject: What is the significance of after() in this code? References: <7o4dk2F3j6jhmU2@mid.individual.net> Message-ID: <7o4e32F3of9sqU1@mid.individual.net> On 2009-12-07, Neil Cerutti wrote: > On 2009-12-07, W. eWatson wrote: >> See Subject. >> def StackImages(self): >> self.Upload("P") >> self.after_id = self.master.after(10000,self.GetFrameOne) > > It's a violation of the Law of Demeter. Actually, I take that back. Dur. -- Neil Cerutti From dickinsm at gmail.com Mon Dec 7 08:30:10 2009 From: dickinsm at gmail.com (Mark Dickinson) Date: Mon, 7 Dec 2009 05:30:10 -0800 (PST) Subject: Float precision and float equality References: <3abf9dfb-fa01-4f71-9214-a06d8b847ebf@e20g2000vbb.googlegroups.com> Message-ID: <39d9eb50-b8b1-4096-a61d-3069b364d0a7@9g2000yqa.googlegroups.com> On Dec 7, 12:16?am, David Cournapeau wrote: > If you can depend on IEEE 754 semantics, one relatively robust method > is to use the number of representable floats between two numbers. The > main advantage compared to the proposed methods is that it somewhat > automatically takes into account the amplitude of input numbers: FWIW, there's a function that can be used for this in Lib/test/ test_math.py in Python svn; it's used to check that math.gamma isn't out by more than 20 ulps (for a selection of test values). def to_ulps(x): """Convert a non-NaN float x to an integer, in such a way that adjacent floats are converted to adjacent integers. Then abs(ulps(x) - ulps(y)) gives the difference in ulps between two floats. The results from this function will only make sense on platforms where C doubles are represented in IEEE 754 binary64 format. """ n = struct.unpack(' References: <20091206150742.45d0c4aa.feliphil@gmx.net> Message-ID: <8c7f10c60912070547t2cdde8dase9b92812969f069f@mail.gmail.com> 2009/12/6 Wolfgang Keller : > Hello, > > has anyone ever implemented something similar to postgresql_autodoc in Python? Dunno - what is it? -- Cheers, Simon B. From victorsubervi at gmail.com Mon Dec 7 09:14:00 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Mon, 7 Dec 2009 09:14:00 -0500 Subject: unsupported operand type(s) for %: 'NoneType' and 'tuple' In-Reply-To: <4B1CF194.4010805@sequans.com> References: <4dc0cfea0912070225s3079a060xcf70c9285430feef@mail.gmail.com> <4B1CF194.4010805@sequans.com> Message-ID: <4dc0cfea0912070614r525ab55by8365e9ea540945f5@mail.gmail.com> On Mon, Dec 7, 2009 at 7:14 AM, Jean-Michel Pichavant < jeanmichel at sequans.com> wrote: > Victor Subervi wrote: > >> >> global printTree = , allTrees = [{'prodCat1': {}, >> 'prodCat2': {}}, {'presCat1': {}, 'presCat2': {}}] >> /var/www/html/angrynates.com/cart/catTree.py < >> http://angrynates.com/cart/catTree.py> in >> printTree(allTrees=[{'prodCat1': {}, 'prodCat2': {}}, {'presCat1': {}, >> 'presCat2': {}}], level=0) >> >> 12 for name in sorted(aTree.keys()): >> 13 print '\t' * level, name >> 14 tree.append("%s%s") % ("\t" * level, name) >> 15 printTree(aTree[name], level + 1) >> 16 >> tree = ['%s%s'], tree.append = , >> level = 0, name = 'prodCat1' >> >> TypeError: unsupported operand type(s) for %: 'NoneType' and 'tuple' >> args = ("unsupported operand type(s) for %: 'NoneType' and 'tuple'",) >> >> But according to the same error, level = 0 [the NoneType, I presume] and >> name = 'prodCat1', which is most certainly not a tuple! Why the error? >> TIA, >> Victor >> > > Come on Victor, > > Given the error, you can easily see that > > tree.append("%s%s") % ("\t" * level, name) > is involved in the error you get. > > The correct thing may be > tree.append("%s%s" % ("\t" * level, name)) > > It should be easy for you to spot. > FYI, tree.append('%s%s') returns None, then ("\t" * level, name) is the > tuple applied to None through the % operator. That is why you get the above > error. > You're absolutely right. This code was supplied to me by a lister. Had I written it myself, I would have caught it. Reading his code, I didn't. I will train myself from now on to write out the code when I come across such errors in the future (and re-write my own as well) so that I can spot such errors: >>> level = 0 >>> name = 'one' >>> tree = [] >>> tree.append("%s%s" % ("\t" * level, name)) >>> However, the code threw one of those blasted HTTP 500 errors and the log had this terse comment: [Mon Dec 07 06:01:23 2009] [error] [client 208.84.198.58] Premature end of script headers: catTree.py Thank you. How helpful. Here's the code: def printTree(allTrees, level=0): tree = [] for aTree in allTrees: for name in sorted(aTree.keys()): tree.append("%s%s" % ("\t" * level, name)) printTree(aTree[name], level + 1) The problem must be occurring in the last line which creates a loop since printTree is called only once at the very end of the entire script (where it is returned to the referrer), but it seems perfectly logical to me. Please advise. V -------------- next part -------------- An HTML attachment was scrubbed... URL: From jeanmichel at sequans.com Mon Dec 7 09:14:27 2009 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Mon, 07 Dec 2009 15:14:27 +0100 Subject: postgresql_autodoc in Python? In-Reply-To: <20091206150742.45d0c4aa.feliphil@gmx.net> References: <20091206150742.45d0c4aa.feliphil@gmx.net> Message-ID: <4B1D0DC3.5060107@sequans.com> Wolfgang Keller wrote: > Hello, > > has anyone ever implemented something similar to postgresql_autodoc in Python? > > TIA, > > Sincerely, > > Wolfgang > > If by postgresql_autodoc you mean tools for generating html documentation from python code, yes. Starting from the ugliest: - pydoc - epydoc - sphinx are 3 of them. I would suggest epydoc, the best look&feel/complexity ratio. Sphinx is used to generate any kind of documentation (look at http://docs.python.org/ it's build with Sphinx) but I never figured out how to easily build documentation from code despite it states it is posible. With epydoc you only need to press the GO button. JM From jeanmichel at sequans.com Mon Dec 7 09:36:25 2009 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Mon, 07 Dec 2009 15:36:25 +0100 Subject: unsupported operand type(s) for %: 'NoneType' and 'tuple' In-Reply-To: <4dc0cfea0912070614r525ab55by8365e9ea540945f5@mail.gmail.com> References: <4dc0cfea0912070225s3079a060xcf70c9285430feef@mail.gmail.com> <4B1CF194.4010805@sequans.com> <4dc0cfea0912070614r525ab55by8365e9ea540945f5@mail.gmail.com> Message-ID: <4B1D12E9.4000001@sequans.com> Victor Subervi wrote: > On Mon, Dec 7, 2009 at 7:14 AM, Jean-Michel Pichavant > > wrote: > > Victor Subervi wrote: > > > global printTree = , allTrees = > [{'prodCat1': {}, 'prodCat2': {}}, {'presCat1': {}, > 'presCat2': {}}] > /var/www/html/angrynates.com/cart/catTree.py > > in > printTree(allTrees=[{'prodCat1': {}, 'prodCat2': {}}, > {'presCat1': {}, 'presCat2': {}}], level=0) > > 12 for name in sorted(aTree.keys()): > 13 print '\t' * level, name > 14 tree.append("%s%s") % ("\t" * level, name) > 15 printTree(aTree[name], level + 1) > 16 > tree = ['%s%s'], tree.append = object>, level = 0, name = 'prodCat1' > > TypeError: unsupported operand type(s) for %: 'NoneType' and > 'tuple' > args = ("unsupported operand type(s) for %: 'NoneType' > and 'tuple'",) > > But according to the same error, level = 0 [the NoneType, I > presume] and name = 'prodCat1', which is most certainly not a > tuple! Why the error? > TIA, > Victor > > > Come on Victor, > > Given the error, you can easily see that > > tree.append("%s%s") % ("\t" * level, name) > is involved in the error you get. > > The correct thing may be > tree.append("%s%s" % ("\t" * level, name)) > > It should be easy for you to spot. > FYI, tree.append('%s%s') returns None, then ("\t" * level, name) > is the tuple applied to None through the % operator. That is why > you get the above error. > > > You're absolutely right. This code was supplied to me by a lister. Had > I written it myself, I would have caught it. Reading his code, I > didn't. I will train myself from now on to write out the code when I > come across such errors in the future (and re-write my own as well) so > that I can spot such errors: > > >>> level = 0 > >>> name = 'one' > >>> tree = [] > >>> tree.append("%s%s" % ("\t" * level, name)) > >>> > > However, the code threw one of those blasted HTTP 500 errors and the > log had this terse comment: > > [Mon Dec 07 06:01:23 2009] [error] [client 208.84.198.58] Premature > end of script headers: catTree.py > > Thank you. How helpful. Here's the code: > > def printTree(allTrees, level=0): > tree = [] > for aTree in allTrees: > for name in sorted(aTree.keys()): > tree.append("%s%s" % ("\t" * level, name)) > printTree(aTree[name], level + 1) > > The problem must be occurring in the last line which creates a loop > since printTree is called only once at the very end of the entire > script (where it is returned to the referrer), but it seems perfectly > logical to me. Please advise. > V Is allTrees a dict or a list ? Did you try to define what could be a allTree value and test your code step by step in a python shell ? That's what is missing in your example: an allTrees values for us to execute your code and check what is going wrong. JM From tino at wildenhain.de Mon Dec 7 09:44:16 2009 From: tino at wildenhain.de (Tino Wildenhain) Date: Mon, 07 Dec 2009 15:44:16 +0100 Subject: postgresql_autodoc in Python? In-Reply-To: <4B1D0DC3.5060107@sequans.com> References: <20091206150742.45d0c4aa.feliphil@gmx.net> <4B1D0DC3.5060107@sequans.com> Message-ID: <4B1D14C0.6010701@wildenhain.de> Am 07.12.2009 15:14, schrieb Jean-Michel Pichavant: > Wolfgang Keller wrote: >> Hello, >> >> has anyone ever implemented something similar to postgresql_autodoc in >> Python? >> >> TIA, >> >> Sincerely, >> >> Wolfgang >> > If by postgresql_autodoc you mean tools for generating html > documentation from python code, yes. > > Starting from the ugliest: > > - pydoc > - epydoc > - sphinx > > are 3 of them. I would suggest epydoc, the best look&feel/complexity > ratio. Sphinx is used to generate any kind of documentation (look at > http://docs.python.org/ it's build with Sphinx) but I never figured out > how to easily build documentation from code despite it states it is > posible. With epydoc you only need to press the GO button. I suspect he meant documenting postgres database structure. One way would be reading the informaton_schema* and generating python code out of it then use any of the above methods to finally document the stuff :-) *) http://www.alberton.info/postgresql_meta_info.html Regards Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/pkcs7-signature Size: 3254 bytes Desc: S/MIME Cryptographic Signature URL: From victorsubervi at gmail.com Mon Dec 7 09:57:17 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Mon, 7 Dec 2009 09:57:17 -0500 Subject: unsupported operand type(s) for %: 'NoneType' and 'tuple' In-Reply-To: <4B1D12E9.4000001@sequans.com> References: <4dc0cfea0912070225s3079a060xcf70c9285430feef@mail.gmail.com> <4B1CF194.4010805@sequans.com> <4dc0cfea0912070614r525ab55by8365e9ea540945f5@mail.gmail.com> <4B1D12E9.4000001@sequans.com> Message-ID: <4dc0cfea0912070657o112c777eo948d578e4be0e0dc@mail.gmail.com> On Mon, Dec 7, 2009 at 9:36 AM, Jean-Michel Pichavant < jeanmichel at sequans.com> wrote: > Victor Subervi wrote: > > On Mon, Dec 7, 2009 at 7:14 AM, Jean-Michel Pichavant < >> jeanmichel at sequans.com > wrote: >> >> Victor Subervi wrote: >> >> >> global printTree = , allTrees = >> [{'prodCat1': {}, 'prodCat2': {}}, {'presCat1': {}, >> 'presCat2': {}}] >> /var/www/html/angrynates.com/cart/catTree.py >> >> in >> printTree(allTrees=[{'prodCat1': {}, 'prodCat2': {}}, >> {'presCat1': {}, 'presCat2': {}}], level=0) >> >> 12 for name in sorted(aTree.keys()): >> 13 print '\t' * level, name >> 14 tree.append("%s%s") % ("\t" * level, name) >> 15 printTree(aTree[name], level + 1) >> 16 >> tree = ['%s%s'], tree.append = > object>, level = 0, name = 'prodCat1' >> >> TypeError: unsupported operand type(s) for %: 'NoneType' and >> 'tuple' >> args = ("unsupported operand type(s) for %: 'NoneType' >> and 'tuple'",) >> >> But according to the same error, level = 0 [the NoneType, I >> presume] and name = 'prodCat1', which is most certainly not a >> tuple! Why the error? >> TIA, >> Victor >> >> >> Come on Victor, >> >> Given the error, you can easily see that >> >> tree.append("%s%s") % ("\t" * level, name) >> is involved in the error you get. >> >> The correct thing may be >> tree.append("%s%s" % ("\t" * level, name)) >> >> It should be easy for you to spot. >> FYI, tree.append('%s%s') returns None, then ("\t" * level, name) >> is the tuple applied to None through the % operator. That is why >> you get the above error. >> >> >> You're absolutely right. This code was supplied to me by a lister. Had I >> written it myself, I would have caught it. Reading his code, I didn't. I >> will train myself from now on to write out the code when I come across such >> errors in the future (and re-write my own as well) so that I can spot such >> errors: >> >> >>> level = 0 >> >>> name = 'one' >> >>> tree = [] >> >>> tree.append("%s%s" % ("\t" * level, name)) >> >>> >> >> However, the code threw one of those blasted HTTP 500 errors and the log >> had this terse comment: >> >> [Mon Dec 07 06:01:23 2009] [error] [client 208.84.198.58] Premature end of >> script headers: catTree.py >> >> Thank you. How helpful. Here's the code: >> >> def printTree(allTrees, level=0): >> tree = [] >> for aTree in allTrees: >> for name in sorted(aTree.keys()): >> tree.append("%s%s" % ("\t" * level, name)) >> printTree(aTree[name], level + 1) >> >> The problem must be occurring in the last line which creates a loop since >> printTree is called only once at the very end of the entire script (where it >> is returned to the referrer), but it seems perfectly logical to me. Please >> advise. >> V >> > Is allTrees a dict or a list ? > Did you try to define what could be a allTree value and test your code step > by step in a python shell ? > That's what is missing in your example: an allTrees values for us to > execute your code and check what is going wrong. > That was a great suggestion. I'll do my best to remember to do that from now on to: >>> allTrees = [{'prodCat1': {}, 'prodCat2': {}}, {'presCat1': {}, 'presCat2': {}}] >>> level = 0 >>> tree = [] >>> for aTree in allTrees: ... for name in sorted(aTree.keys()): ... tree.append("%s%s" % ("\t" * level, name)) ... print aTree([name], level + 1) ... Traceback (most recent call last): File "", line 4, in ? TypeError: 'dict' object is not callable >>> So It would seem I need to either figure a way to coerce the dicts into being tuples a la: http://code.activestate.com/recipes/361668/ (which looks like a lot of work) or I need to supply tuples instead of dicts. The dicts come from here: cursor.execute('select category from categories%s order by Category;' % (store[0].upper() + store[1:])) theTree = expand(cursor.fetchall()) which is the magical code supplied by the lister that does all the heavy lifting but that I don't understand :-} Suggestions? TIA, V -------------- next part -------------- An HTML attachment was scrubbed... URL: From jeanmichel at sequans.com Mon Dec 7 10:19:46 2009 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Mon, 07 Dec 2009 16:19:46 +0100 Subject: unsupported operand type(s) for %: 'NoneType' and 'tuple' In-Reply-To: <4dc0cfea0912070657o112c777eo948d578e4be0e0dc@mail.gmail.com> References: <4dc0cfea0912070225s3079a060xcf70c9285430feef@mail.gmail.com> <4B1CF194.4010805@sequans.com> <4dc0cfea0912070614r525ab55by8365e9ea540945f5@mail.gmail.com> <4B1D12E9.4000001@sequans.com> <4dc0cfea0912070657o112c777eo948d578e4be0e0dc@mail.gmail.com> Message-ID: <4B1D1D12.4080300@sequans.com> Victor Subervi wrote: > > > printTree(aTree[name], level + 1) > > > ... print aTree([name], level + 1) > ... > Traceback (most recent call last): > File "", line 4, in ? > TypeError: 'dict' object is not callable > >>> > Be cautious, you are now executing the same code ! Again, read carefully the error message, you tried to call a dictionary : aTree([name], level + 1) the following code below works fine in a python 2.5 shell: allTrees = [{'prodCat1': {}, 'prodCat2': {}}, {'presCat1': {}, 'presCat2': {}}] level = 0 tree=[] def printTree(allTrees, level=0): for aTree in allTrees: for name in sorted(aTree.keys()): print '\t' * level, name tree.append("%s%s" % ("\t" * level, name)) printTree(aTree[name], level + 1) In [9]: run ~/test.py In [10]: printTree(allTrees) prodCat1 prodCat2 presCat1 presCat2 In [11]: print tree ['prodCat1', 'prodCat2', 'presCat1', 'presCat2'] Though I'm not sure this is exactly want you want. Anyway, there is a big probelm happening when using the following value : allTrees = [{'prodCat1': {'test':'success'}, 'prodCat2': {}}, {'presCat1': {}, 'presCat2': {}}] printTree take a list in the first place, but when recursively calling printTree(aTree[name], level + 1), you pass a dictionary. Your code will fail as soon as the dictionary is not empty. JM From carsten.haese at gmail.com Mon Dec 7 10:29:20 2009 From: carsten.haese at gmail.com (Carsten Haese) Date: Mon, 07 Dec 2009 10:29:20 -0500 Subject: unsupported operand type(s) for %: 'NoneType' and 'tuple' In-Reply-To: <4dc0cfea0912070657o112c777eo948d578e4be0e0dc@mail.gmail.com> References: <4dc0cfea0912070225s3079a060xcf70c9285430feef@mail.gmail.com> <4B1CF194.4010805@sequans.com> <4dc0cfea0912070614r525ab55by8365e9ea540945f5@mail.gmail.com> <4B1D12E9.4000001@sequans.com> <4dc0cfea0912070657o112c777eo948d578e4be0e0dc@mail.gmail.com> Message-ID: Victor Subervi wrote: > I'll do my best to remember to do that from > now on to: > >>>> allTrees = [{'prodCat1': {}, 'prodCat2': {}}, {'presCat1': {}, > 'presCat2': {}}] >>>> level = 0 >>>> tree = [] >>>> for aTree in allTrees: > ... for name in sorted(aTree.keys()): > ... tree.append("%s%s" % ("\t" * level, name)) > ... print aTree([name], level + 1) > ... > Traceback (most recent call last): > File "", line 4, in ? > TypeError: 'dict' object is not callable >>>> > > So It would seem I need to either figure a way to coerce the dicts into > being tuples a la: > http://code.activestate.com/recipes/361668/ > (which looks like a lot of work) or I need to supply tuples instead of > dicts. No. You need to test the actual code you want to test. The code you typed manually has some very significant differences from the code you first posted. For example, one uses <>, and the other uses <>. The conclusions you are drawing from this test are meaningless guesses that have nothing to do with solving your actual problem. > The dicts come from here: > > cursor.execute('select category from categories%s order by Category;' % > (store[0].upper() + store[1:])) > theTree = expand(cursor.fetchall()) > > which is the magical code supplied by the lister that does all the heavy > lifting but that I don't understand :-} > Suggestions? Start by understanding the code you're using. -- Carsten Haese http://informixdb.sourceforge.net From jfabiani at yolo.com Mon Dec 7 10:31:44 2009 From: jfabiani at yolo.com (jfabiani at yolo.com) Date: Mon, 07 Dec 2009 07:31:44 -0800 Subject: opening a connection to quickbooks Message-ID: Hi, Has anyone ever attempted to work with quickbooks in a real time fashion? I need some advise. I'm trying to work out a way to have real time updates/inserts/and queries. I'd also like not to use all the user licenses. But... I have discovered that opening a connection to quickbooks takes a long time (as much as 11 seconds). Is there a way I can open/create the connection in a thread (so the rest of the prog can continue) and then use the connection in the rest of the program to make queries? Or does someone have a suggestion as how to get around this problem. I'm using QB's Simple Start Edition - would the enterprise edition have better performance? Thanks in advance, Johnf From vicente.soler at gmail.com Mon Dec 7 10:59:05 2009 From: vicente.soler at gmail.com (vsoler) Date: Mon, 7 Dec 2009 07:59:05 -0800 (PST) Subject: When will Python 3 be fully deployed References: Message-ID: On Dec 6, 11:53?pm, "Martin P. Hellwig" wrote: > Edward A. Falk wrote: > > > > > For development purposes, you should stick with the oldest version that will > > actually run your code. ?Every time you move to a more modern version, you're > > leaving potential users/customers out in the cold. > > If the fear of customers disatification prevents you from using a > certain version of X, you should consider a deployment strategy that > cuts out dependencies as much as possible. Although this will result in > a larger end package and possible high amount of duplication, it is > still preferable to just stop supporting popular platforms or be swamped > away with bugs due to version mismatches. > > -- > MPHhttp://blog.dcuktec.com > 'If consumed, best digested with added seasoning to own preference.' Your posts have been very enlightening. Thank you very much!!! From victorsubervi at gmail.com Mon Dec 7 11:01:41 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Mon, 7 Dec 2009 12:01:41 -0400 Subject: unsupported operand type(s) for %: 'NoneType' and 'tuple' In-Reply-To: References: <4dc0cfea0912070225s3079a060xcf70c9285430feef@mail.gmail.com> <4B1CF194.4010805@sequans.com> <4dc0cfea0912070614r525ab55by8365e9ea540945f5@mail.gmail.com> <4B1D12E9.4000001@sequans.com> <4dc0cfea0912070657o112c777eo948d578e4be0e0dc@mail.gmail.com> Message-ID: <4dc0cfea0912070801y28fce630t722176d7ad5eeef3@mail.gmail.com> On Mon, Dec 7, 2009 at 11:29 AM, Carsten Haese wrote: > Victor Subervi wrote: > > I'll do my best to remember to do that from > > now on to: > > > >>>> allTrees = [{'prodCat1': {}, 'prodCat2': {}}, {'presCat1': {}, > > 'presCat2': {}}] > >>>> level = 0 > >>>> tree = [] > >>>> for aTree in allTrees: > > ... for name in sorted(aTree.keys()): > > ... tree.append("%s%s" % ("\t" * level, name)) > > ... print aTree([name], level + 1) > > ... > > Traceback (most recent call last): > > File "", line 4, in ? > > TypeError: 'dict' object is not callable > >>>> > > > > So It would seem I need to either figure a way to coerce the dicts into > > being tuples a la: > > http://code.activestate.com/recipes/361668/ > > (which looks like a lot of work) or I need to supply tuples instead of > > dicts. > > No. You need to test the actual code you want to test. The code you > typed manually has some very significant differences from the code you > first posted. For example, one uses < 1)>>, and the other uses <>. The > conclusions you are drawing from this test are meaningless guesses that > have nothing to do with solving your actual problem. > Another screw-up. Now that I'm at a computer where I can right click to paste the correctly copied code, it executed in the shell just fine. For whatever reason, the page itself no longer throws an error, although it's still not working properly. > > > The dicts come from here: > > > > cursor.execute('select category from categories%s order by Category;' % > > (store[0].upper() + store[1:])) > > theTree = expand(cursor.fetchall()) > > > > which is the magical code supplied by the lister that does all the heavy > > lifting but that I don't understand :-} > > Suggestions? > > Start by understanding the code you're using. > Well, if you could point me in the right direction, it would be appreciated. I've tried googling this with no luck. Apparently, "expand" is not a well-documented term in python and, of course, it's an often-used term in English, which further confuses the issue. Yes, I would like to understand this code. TIA, V -------------- next part -------------- An HTML attachment was scrubbed... URL: From vicente.soler at gmail.com Mon Dec 7 11:10:11 2009 From: vicente.soler at gmail.com (vsoler) Date: Mon, 7 Dec 2009 08:10:11 -0800 (PST) Subject: Where is my namespace? Message-ID: I take the example from Mark Lutz's excellent book "Learning Python". *** In nested1.py I have: X=99 def printer(): print X *** In nested2.py I have: from nested1 import X, printer X=88 printer() What is amazing is that running nested2.py prints 99 and not 88. My questions are: 1. Using statement "from" instead of "import" should not create a namespace, at least that's what I think. However, the printer() function is able to find 99 which is residing in... a namespace? 2. I have tried to access the 88 by qualification from nested2.py. However, I cannot. If using "print nested1.X" in nested2.py I get an error 3. Mark says: The from statement is really an assignment to names in the importer's scope--a name-copy operation, not a name aliasing. I don't fully understand what he means. Could anybody explain? Thank you very much for your time. Vicente Soler From simon at brunningonline.net Mon Dec 7 11:25:39 2009 From: simon at brunningonline.net (Simon Brunning) Date: Mon, 7 Dec 2009 16:25:39 +0000 Subject: Where is my namespace? In-Reply-To: References: Message-ID: <8c7f10c60912070825v121638d1lfa7c370a16d3a565@mail.gmail.com> 2009/12/7 vsoler : > I take the example from Mark Lutz's excellent book "Learning Python". > > *** In nested1.py ?I have: > X=99 > def printer(): print X > > *** In nested2.py ?I have: > from nested1 import X, printer > X=88 > printer() > > What is amazing is that running nested2.py prints 99 and not 88. > > My questions are: > > 1. Using statement "from" instead of "import" should not create a > namespace, at least that's what I think. However, the printer() > function is able to find 99 which is residing in... ?a namespace? Sorry - you think wrong. All modules have their own namespace. "from blah import" injects the objects from the imported module directly into the importing modules namespace, but they are still two distinct namespaces. > 2. I have tried to access the 88 by qualification from nested2.py. > However, I cannot. If using "print nested1.X" in nested2.py I get an > error If you do "from blah import" the imported module itself isn't bound to any name in the importing module - you can't get at it at all. > 3. Mark says: The from statement is really an assignment to names in > the importer's scope--a name-copy operation, not a name aliasing. ? I > don't fully understand what he means. Could anybody explain? Does the above help? -- Cheers, Simon B. From bruno.42.desthuilliers at websiteburo.invalid Mon Dec 7 11:38:46 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 07 Dec 2009 17:38:46 +0100 Subject: Where is my namespace? In-Reply-To: References: Message-ID: <4b1d2f95$0$14448$426a74cc@news.free.fr> vsoler a ?crit : > I take the example from Mark Lutz's excellent book "Learning Python". > > *** In nested1.py I have: > X=99 > def printer(): print X > > *** In nested2.py I have: > from nested1 import X, printer > X=88 > printer() > > What is amazing is that running nested2.py prints 99 and not 88. It's "amazing" only if you believe Python's "global" scope is really global. Thruth is that in Python, "global" means "module-level" - so when you call printer, it resolves X in it's own "global" namespace - that is, nested1's global namespace. > My questions are: > > 1. Using statement "from" instead of "import" should not create a > namespace, It doesn't. > at least that's what I think. However, the printer() > function is able to find 99 which is residing in... a namespace? Yes, cf above. This namespace is created when the nested1.py module is first loaded (whether via any form of import or via direct execution of nested1 as a script). > 2. I have tried to access the 88 by qualification from nested2.py. > However, I cannot. If using "print nested1.X" in nested2.py I get an > error You have to import the nested1 module itself, ie: # nested3.py import nested1 print nested1.X printer() nested1.X = 42 printer > 3. Mark says: The from statement is really an assignment to names in > the importer's scope--a name-copy operation, not a name aliasing. I > don't fully understand what he means. Could anybody explain? Think of Python's namespaces as dicts, where names are keys and reference to objects are values. If you do: import nested1 then your current namespace will look like : {"nested1" : } But if you do: from nested1 import printer Then your namespace will look like: {"printer" : } Of course, in this case, the name "printer" in the current namespace is bound to the same function object as nested1.printer - but the _name_ "printer" is local to your current namespace. If you rebind this name in the current namespace, it wont affect nested1's namespace. HTH From benjamin.kaplan at case.edu Mon Dec 7 11:39:06 2009 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Mon, 7 Dec 2009 11:39:06 -0500 Subject: Where is my namespace? In-Reply-To: References: Message-ID: On Mon, Dec 7, 2009 at 11:10 AM, vsoler wrote: > I take the example from Mark Lutz's excellent book "Learning Python". > > *** In nested1.py ?I have: > X=99 > def printer(): print X > > *** In nested2.py ?I have: > from nested1 import X, printer > X=88 > printer() > > What is amazing is that running nested2.py prints 99 and not 88. > > My questions are: > > 1. Using statement "from" instead of "import" should not create a > namespace, at least that's what I think. However, the printer() > function is able to find 99 which is residing in... ?a namespace? > It doesn't create a namespace. But printer is still in nested1. When you do a "from ... import ...", the objects are imported into the current namespace. However, they are different names for what is currently the same object. They still follow Python's object semantics. Here's a simplified overview of what happens you run nested2.py 1 namespace: nested2, nothing in it (except for the special stuff) you run "from nested1 import X, printer". This executes everything in nested1 (because def and class are just executable statements in Python) and binds X and printer in nested2 to the objects in nested1. Note that these are now different names for the same objects. nested1: X = 99, printer = nested2: X = 99 printer = you call X = 88. Because you are rebinding the object, this name (nested2.X) is the only one that gets changed. Rebinding doesn't touch the object in nested1. nested1: X=99, printer = nested2: x=88 printer = Notice how the name "printer" in nested2 still refers to an object in nested1. It is simply another reference, not a new object. When you call printer, it's still sitting in nested1 and only sees nested1's X. > 2. I have tried to access the 88 by qualification from nested2.py. > However, I cannot. If using "print nested1.X" in nested2.py I get an > error that's because when you do "from ... import ..." it doesn't import the module itself. There's a totally different behavior between from ... import and import. Here's what you're trying to do nested2.py : import nested1 nested1.X = 88 nested1.printer() > > 3. Mark says: The from statement is really an assignment to names in > the importer's scope--a name-copy operation, not a name aliasing. ? I > don't fully understand what he means. Could anybody explain? > Like I showed before, when you change the unqualified "X" in nested2, the X in nested1 doesn't change. Using from import is identical to doing something like this a = 1 b = a b = 5 a == 1 #True a is a name that temporarily referred to the same object as a. However, when you reassign b, it makes the name "b" refer to a different object. It doesn't change the object that a and b both refer to. When you import using from ... import, you end up with 2 different names that, at the start refer to the same object. Mutation (if you're using a mutable object) will show up in both namespaces, since they are referring to the same object, but assignment does not. > Thank you very much for your time. > > Vicente Soler > -- > http://mail.python.org/mailman/listinfo/python-list > From rami.chowdhury at gmail.com Mon Dec 7 11:40:01 2009 From: rami.chowdhury at gmail.com (Rami Chowdhury) Date: Mon, 7 Dec 2009 08:40:01 -0800 Subject: unsupported operand type(s) for %: 'NoneType' and 'tuple' In-Reply-To: <4dc0cfea0912070801y28fce630t722176d7ad5eeef3@mail.gmail.com> References: <4dc0cfea0912070225s3079a060xcf70c9285430feef@mail.gmail.com> <4B1CF194.4010805@sequans.com> <4dc0cfea0912070614r525ab55by8365e9ea540945f5@mail.gmail.com> <4B1D12E9.4000001@sequans.com> <4dc0cfea0912070657o112c777eo948d578e4be0e0dc@mail.gmail.com> <4dc0cfea0912070801y28fce630t722176d7ad5eeef3@mail.gmail.com> Message-ID: <2f79f590912070840q18ca8be6uece6e2022e9ef437@mail.gmail.com> On Mon, Dec 7, 2009 at 08:01, Victor Subervi wrote: > On Mon, Dec 7, 2009 at 11:29 AM, Carsten Haese > wrote: >> >> Victor Subervi wrote: >> > I'll do my best to remember to do that from >> > now on to: >> > >> >>>> allTrees = [{'prodCat1': {}, 'prodCat2': {}}, {'presCat1': {}, >> > 'presCat2': {}}] >> >>>> level = 0 >> >>>> tree = [] >> >>>> for aTree in allTrees: >> > ... ? for name in sorted(aTree.keys()): >> > ... ? ? tree.append("%s%s" % ("\t" * level, name)) >> > ... ? ? print aTree([name], level + 1) >> > ... >> > Traceback (most recent call last): >> > ? File "", line 4, in ? >> > TypeError: 'dict' object is not callable >> >>>> >> > >> > So It would seem I need to either figure a way to coerce the dicts into >> > being tuples a la: >> > http://code.activestate.com/recipes/361668/ >> > (which looks like a lot of work) or I need to supply tuples instead of >> > dicts. >> >> No. You need to test the actual code you want to test. The code you >> typed manually has some very significant differences from the code you >> first posted. For example, one uses <> 1)>>, and the other uses <>. The >> conclusions you are drawing from this test are meaningless guesses that >> have nothing to do with solving your actual problem. > > Another screw-up. Now that I'm at a computer where I can right click to > paste the correctly copied code, it executed in the shell just fine. For > whatever reason, the page itself no longer throws an error, although it's > still not working properly. >> >> > The dicts come from here: >> > >> > cursor.execute('select category from categories%s order by Category;' % >> > (store[0].upper() + store[1:])) >> > theTree = expand(cursor.fetchall()) >> > >> > which is the magical code supplied by the lister that does all the heavy >> > lifting but that I don't understand :-} >> > Suggestions? >> >> Start by understanding the code you're using. > > Well, if you could point me in the right direction, it would be appreciated. > I've tried googling this with no luck. Apparently, "expand" is not a > well-documented term in python and, of course, it's an often-used term in > English, which further confuses the issue. Yes, I would like to understand > this code. Coming from PHP, I can see why you might be confused. Python is not PHP -- Python has namespaces and uses them, unlike PHP which IIRC shoves nearly everything into the default namespace. So you need to start by figuring out where the 'expand' function came from -- I'm pretty sure it's not a builtin. Look at the import statements in the file to see if the function has been specifically imported from somewhere, or if there's a statement of the form "from [module] import *". You will then know the module it came from, and be able to either look at the code or the documentation for that module, which should tell you more. -------- Rami Chowdhury "Never assume malice when stupidity will suffice." -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) From debatem1 at gmail.com Mon Dec 7 11:46:04 2009 From: debatem1 at gmail.com (geremy condra) Date: Mon, 7 Dec 2009 11:46:04 -0500 Subject: python bijection In-Reply-To: <4B1CFA36.9060805@egenix.com> References: <85100df7-a8b0-47e9-a854-ba8a8a2f3b98@r31g2000vbi.googlegroups.com> <4B17A960.1090700@egenix.com> <4B17FBFE.8070903@egenix.com> <4B18F685.8050102@egenix.com> <4B1CFA36.9060805@egenix.com> Message-ID: On Mon, Dec 7, 2009 at 7:51 AM, M.-A. Lemburg wrote: > Terry Reedy wrote: >> M.-A. Lemburg wrote: >> >>> Integrating an easy-to-use graph library into the collections >>> module (and it's C companion) is good idea. >>> >>>>> This would have to be written in C, though, >>>> That's currently in the works, along with database backing. >>>> We'd welcome any help though... hint, hint... >> >> The current thinking among deveopers is that new modules should be >> written and maintained in Python, which all implementations can use, >> with speed-critical parts written in C for speed and imported by the >> Python code. > > I don't think you are speaking for Python developers in general. I believe he's referring to the core developers. Geremy Condra From carsten.haese at gmail.com Mon Dec 7 11:52:47 2009 From: carsten.haese at gmail.com (Carsten Haese) Date: Mon, 07 Dec 2009 11:52:47 -0500 Subject: unsupported operand type(s) for %: 'NoneType' and 'tuple' In-Reply-To: <4dc0cfea0912070801y28fce630t722176d7ad5eeef3@mail.gmail.com> References: <4dc0cfea0912070225s3079a060xcf70c9285430feef@mail.gmail.com> <4B1CF194.4010805@sequans.com> <4dc0cfea0912070614r525ab55by8365e9ea540945f5@mail.gmail.com> <4B1D12E9.4000001@sequans.com> <4dc0cfea0912070657o112c777eo948d578e4be0e0dc@mail.gmail.com> <4dc0cfea0912070801y28fce630t722176d7ad5eeef3@mail.gmail.com> Message-ID: Victor Subervi wrote: > Well, if you could point me in the right direction, it would be > appreciated. I've tried googling this with no luck. Apparently, "expand" > is not a well-documented term in python and, of course, it's an > often-used term in English, which further confuses the issue. Yes, I > would like to understand this code. If I remember correctly from one of your earlier posts, "expand" is a name of a function that's actually defined in your code. Understanding its name won't help you understand what it does. It would do exactly the same if it were called "frobnicate" and all instances of "expand" in your code were replaced with "frobnicate". To understand what the function does, look at the function definition and pretend that you're the Python interpreter: Follow the code one instruction at a time and imagine what each instruction does. If you do this correctly, you will understand what the code does. This won't tell you *why* it does it, but it's your code, and you put it there to serve a particular purpose. If you don't understand its purpose, you shouldn't be using it at all. -- Carsten Haese http://informixdb.sourceforge.net From mal at egenix.com Mon Dec 7 12:05:00 2009 From: mal at egenix.com (M.-A. Lemburg) Date: Mon, 07 Dec 2009 18:05:00 +0100 Subject: python bijection In-Reply-To: References: <85100df7-a8b0-47e9-a854-ba8a8a2f3b98@r31g2000vbi.googlegroups.com> <4B17A960.1090700@egenix.com> <4B17FBFE.8070903@egenix.com> <4B18F685.8050102@egenix.com> <4B1CFA36.9060805@egenix.com> Message-ID: <4B1D35BC.5000002@egenix.com> geremy condra wrote: > On Mon, Dec 7, 2009 at 7:51 AM, M.-A. Lemburg wrote: >> Terry Reedy wrote: >>> M.-A. Lemburg wrote: >>> >>>> Integrating an easy-to-use graph library into the collections >>>> module (and it's C companion) is good idea. >>>> >>>>>> This would have to be written in C, though, >>>>> That's currently in the works, along with database backing. >>>>> We'd welcome any help though... hint, hint... >>> >>> The current thinking among deveopers is that new modules should be >>> written and maintained in Python, which all implementations can use, >>> with speed-critical parts written in C for speed and imported by the >>> Python code. >> >> I don't think you are speaking for Python developers in general. > > I believe he's referring to the core developers. I was as well, being one of them :-) -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Dec 07 2009) >>> 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 our new mxODBC.Connect Python Database Interface 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 http://www.egenix.com/company/contact/ From victorsubervi at gmail.com Mon Dec 7 12:06:20 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Mon, 7 Dec 2009 13:06:20 -0400 Subject: unsupported operand type(s) for %: 'NoneType' and 'tuple' In-Reply-To: <2f79f590912070840q18ca8be6uece6e2022e9ef437@mail.gmail.com> References: <4dc0cfea0912070225s3079a060xcf70c9285430feef@mail.gmail.com> <4B1CF194.4010805@sequans.com> <4dc0cfea0912070614r525ab55by8365e9ea540945f5@mail.gmail.com> <4B1D12E9.4000001@sequans.com> <4dc0cfea0912070657o112c777eo948d578e4be0e0dc@mail.gmail.com> <4dc0cfea0912070801y28fce630t722176d7ad5eeef3@mail.gmail.com> <2f79f590912070840q18ca8be6uece6e2022e9ef437@mail.gmail.com> Message-ID: <4dc0cfea0912070906i1108c762i49b4039a97536c21@mail.gmail.com> On Mon, Dec 7, 2009 at 12:40 PM, Rami Chowdhury wrote: > Coming from PHP, > Wash your mouth out with soap, Rami! I might not be a good programmer, but I'm loyal to the Flying Circus. I only did one job, my first one, in PHP before I became "enlightened" :)) > I can see why you might be confused. Python is not > PHP -- Python has namespaces and uses them, unlike PHP which IIRC > shoves nearly everything into the default namespace. So you need to > start by figuring out where the 'expand' function came from -- I'm > pretty sure it's not a builtin. Look at the import statements in the > file to see if the function has been specifically imported from > somewhere, or if there's a statement of the form "from [module] import > *". You will then know the module it came from, and be able to either > look at the code or the documentation for that module, which should > tell you more. > No, it's not imported. These are the only imports: import sys,os sys.path.append(os.getcwd()) import MySQLdb from login import login import re, string TIA, V -------------- next part -------------- An HTML attachment was scrubbed... URL: From victorsubervi at gmail.com Mon Dec 7 12:07:09 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Mon, 7 Dec 2009 13:07:09 -0400 Subject: unsupported operand type(s) for %: 'NoneType' and 'tuple' In-Reply-To: References: <4dc0cfea0912070225s3079a060xcf70c9285430feef@mail.gmail.com> <4B1CF194.4010805@sequans.com> <4dc0cfea0912070614r525ab55by8365e9ea540945f5@mail.gmail.com> <4B1D12E9.4000001@sequans.com> <4dc0cfea0912070657o112c777eo948d578e4be0e0dc@mail.gmail.com> <4dc0cfea0912070801y28fce630t722176d7ad5eeef3@mail.gmail.com> Message-ID: <4dc0cfea0912070907l2edade3bs27c690d98af49f68@mail.gmail.com> On Mon, Dec 7, 2009 at 12:52 PM, Carsten Haese wrote: > Victor Subervi wrote: > > Well, if you could point me in the right direction, it would be > > appreciated. I've tried googling this with no luck. Apparently, "expand" > > is not a well-documented term in python and, of course, it's an > > often-used term in English, which further confuses the issue. Yes, I > > would like to understand this code. > > If I remember correctly from one of your earlier posts, "expand" is a > name of a function that's actually defined in your code. Understanding > its name won't help you understand what it does. It would do exactly the > same if it were called "frobnicate" and all instances of "expand" in > your code were replaced with "frobnicate". > > To understand what the function does, look at the function definition > and pretend that you're the Python interpreter: Follow the code one > instruction at a time and imagine what each instruction does. If you do > this correctly, you will understand what the code does. This won't tell > you *why* it does it, but it's your code, and you put it there to serve > a particular purpose. If you don't understand its purpose, you shouldn't > be using it at all. > <:-} Right again. V -------------- next part -------------- An HTML attachment was scrubbed... URL: From denis.papathanasiou at gmail.com Mon Dec 7 12:12:50 2009 From: denis.papathanasiou at gmail.com (dpapathanasiou) Date: Mon, 7 Dec 2009 09:12:50 -0800 (PST) Subject: IO Gurus: what are the differences between these two methods? Message-ID: <75da8a5f-857b-4fab-bfb9-8d03b1cadf1a@u1g2000pre.googlegroups.com> I have two methods for writing binaries files: the first works with data received by a server corresponding to a file upload, and the second works with data sent as email attachments. The odd thing is, they're not interchangeable: if I use the first one to saved data parsed from an email attachment, it fails; similarly, the second function fails when dealing with an uploaded file data. What are the critical differences? def write_binary_file (folder, filename, f, chunk_size=4096): """Write the file data f to the folder and filename combination""" result = False if confirm_folder(folder): try: file_obj = open(os.path.join(folder, file_base_name (filename)), 'wb', chunk_size) for file_chunk in read_buffer(f, chunk_size): file_obj.write(file_chunk) file_obj.close() result = True except (IOError): print "file_utils.write_binary_file: could not write '%s' to '%s'" % (file_base_name(filename), folder) return result def write_binary_file (folder, filename, filedata): """Write the binary file data to the folder and filename combination""" result = False if confirm_folder(folder): try: file_obj = open(os.path.join(folder, file_base_name (filename)), 'wb') file_obj.write(filedata) file_obj.close() result = True except (IOError): print "file_utils.write_binary_file: could not write '%s' to '%s'" % (file_base_name(filename), folder) return result From debatem1 at gmail.com Mon Dec 7 12:14:05 2009 From: debatem1 at gmail.com (geremy condra) Date: Mon, 7 Dec 2009 12:14:05 -0500 Subject: python bijection In-Reply-To: <4B1D35BC.5000002@egenix.com> References: <4B17A960.1090700@egenix.com> <4B17FBFE.8070903@egenix.com> <4B18F685.8050102@egenix.com> <4B1CFA36.9060805@egenix.com> <4B1D35BC.5000002@egenix.com> Message-ID: On Mon, Dec 7, 2009 at 12:05 PM, M.-A. Lemburg wrote: > geremy condra wrote: >> On Mon, Dec 7, 2009 at 7:51 AM, M.-A. Lemburg wrote: >>> Terry Reedy wrote: >>>> M.-A. Lemburg wrote: >>>> >>>>> Integrating an easy-to-use graph library into the collections >>>>> module (and it's C companion) is good idea. >>>>> >>>>>>> This would have to be written in C, though, >>>>>> That's currently in the works, along with database backing. >>>>>> We'd welcome any help though... hint, hint... >>>> >>>> The current thinking among deveopers is that new modules should be >>>> written and maintained in Python, which all implementations can use, >>>> with speed-critical parts written in C for speed and imported by the >>>> Python code. >>> >>> I don't think you are speaking for Python developers in general. >> >> I believe he's referring to the core developers. > > I was as well, being one of them :-) Misunderstanding: 2, Me: 0... moving on ;) How interested are you in a C port of graphine? I haven't had any specific requests for it, but if its something you need I can shuffle it towards the top of the to do pile. Geremy Condra From goon12 at gmail.com Mon Dec 7 12:47:27 2009 From: goon12 at gmail.com (Joe Riopel) Date: Mon, 7 Dec 2009 12:47:27 -0500 Subject: IO Gurus: what are the differences between these two methods? In-Reply-To: <75da8a5f-857b-4fab-bfb9-8d03b1cadf1a@u1g2000pre.googlegroups.com> References: <75da8a5f-857b-4fab-bfb9-8d03b1cadf1a@u1g2000pre.googlegroups.com> Message-ID: <6a2ccd190912070947j3732b776if04287136757f013@mail.gmail.com> On Mon, Dec 7, 2009 at 12:12 PM, dpapathanasiou wrote: > I have two methods for writing binaries files: the first works with > data received by a server corresponding to a file upload, and the > second works with data sent as email attachments. > > The odd thing is, they're not interchangeable: if I use the first one > to saved data parsed from an email attachment, it fails; similarly, > the second function fails when dealing with an uploaded file data. When you say it fails, are there any error messages displayed, exceptions raised, etc? I am not sure what you mean, in regards to "fails". From tjreedy at udel.edu Mon Dec 7 13:04:03 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 07 Dec 2009 13:04:03 -0500 Subject: how to convert string function to string method? In-Reply-To: References: Message-ID: Steven D'Aprano wrote: > On Sun, 06 Dec 2009 22:47:48 -0800, Dr. Phillip M. Feldman wrote: > >> I wrote a handy-dandy function (see below) called "strip_pairs" for >> stripping matching pairs of characters from the beginning and end of a >> string. This function works, but I would like to be able to invoke it >> as a string method rather than as a function. Is this possible? > > Not exactly. You can subclass string and add such a method: > > class MyString(str): > def strip_pairs(self, ...): > ... > > but then you have to convert every string to a MyString before you use > it. That way leads to madness. > > Better to just use a function. Don't worry, you're allowed to mix > functional and OO code :) Unlike certain other languages, Python is not designed around a fetish for calling all functions as methods. s.func(arg) is immediately translated to cls.func(s,arg) where cls is either the class of s or some superclass thereof. Directly writing mod.func(s,arg), where mod is some module, is just as good. Methods have three purposes: bundle several related functions in a class-specific namespace; inheritance; mapping of operations, like '+', to class-specific (special) methods. Modules are an alernative namespace bundle. Terry Jan Reedy From tjreedy at udel.edu Mon Dec 7 13:21:23 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 07 Dec 2009 13:21:23 -0500 Subject: python proxy checker ,change to threaded version In-Reply-To: References: Message-ID: r0g wrote: > The trick to threads is to create a subclass of threading.Thread, define > the 'run' function and call the 'start()' method. I find threading quite > generally useful so I created this simple generic function for running > things in threads... Great idea. Thanks for posting this. > def run_in_thread( func, func_args=[], callback=None, callback_args=[] ): > import threading > class MyThread ( threading.Thread ): > def run ( self ): > > # Call function > if function_args: > result = function(*function_args) > else: > result = function() The check is not necessary. by design, f(*[]) == f() Names do not match param names ;=) > > # Call callback > if callback: > if callback_args: > callback(result, *callback_args) > else: > callback(result) Ditto. g(x,*[]) == g(x) def run(self): result = func(*func_args) # matching run_in_thread param names callback(result, *callback_args) > MyThread().start() This is one of the best uses I have seen for a nested class definition. > Suggestions from hardcore pythonistas on how to my make run_in_thread > function more elegant are quite welcome also :) I shortened it, at least. Terry Jan Reedy From jorgeecardona at gmail.com Mon Dec 7 13:29:45 2009 From: jorgeecardona at gmail.com (Jorge Cardona) Date: Mon, 7 Dec 2009 13:29:45 -0500 Subject: Generators. In-Reply-To: <4b1c8cc3$1@dnews.tpgi.com.au> References: <4b1c8cc3$1@dnews.tpgi.com.au> Message-ID: <51d803a90912071029o549b9740q234634b1e801ea1@mail.gmail.com> 2009/12/7 Lie Ryan : > On 12/7/2009 7:22 AM, Jorge Cardona wrote: >> >> Hi, >> >> I was trying to create a function that receive a generator and return >> a list but that each elements were computed in a diferent core of my >> machine. I start using islice function in order to split the job in a >> way that if there is "n" cores each "i" core will compute the elements >> i,i+n,i+2n,..., but islice has a weird (to me) behavior, look: > > it's nothing weird, python just do what you're telling it to: > > transform all x in X with f(x) >> >> g = (f(x) for x in X) > > then slice the result of that >> >> print(list(x for x in islice(g,0,None,2))) > When i wrote that first line of code i thought that i was creating a generator that will later compute the elements of X with function f, if i will like to transform them immediately i would use [] instead (), so, the result is not where i want to slice, even so, is exactly the same to slice, after or before, the only difference is that after the compute i'm losing 5 in unnecessary execution of the function f. > what you want to do is to slice before you transform: >>>> g = (x for x in islice(X, 0, None, 2)) >>>> print(list(f(x) for x in g)) > eval: 0 > eval: 2 > eval: 4 > eval: 6 > eval: 8 > [0, 2, 4, 6, 8] > What i want to do is a function that receive any kind of generator and execute it in several cores (after a fork) and return the data, so, i can't slice the set X before create the generator. >> islice execute the function at the generator and drop the elements >> that aren't in the slice. I found that pretty weird, the way that i >> see generators is like an association between and indexing set (an >> iterator or another generator) and a computation that is made indexed >> by the indexing set, and islice is like a "transformation" on the >> indexing set,it doesn't matter the result of the function, the slice >> should act only on the indexing set, some other "transformation" like >> takewhile act on the result so, the execution it has to be made, but >> in the islice, or other "transformation" that act only in the indexing >> set, the function shouldn't be executed at each element, but only on >> that new set that result of the application of the "transformation" on >> the original set. > > that seems like an extremely lazy evaluation, I don't know if even a true > lazy language do that. Python is a strict language, with a few laziness > provided by generators, in the end it's still a strict language. > Yes, it looks like lazy evaluation, but, i don't see why there is not a better control over the iterable associated to a generator, even with Python that is a strict language, it will increase the functionality of it, and the performance too, imagine that you pass a function that takes 1 sec in run, and for several reason you can't slice before (as the smp function that i want to create), the final performance with the actual islice it gets really reduced Just creating the separation between those transformation that act on the index(islice, or tee) on those that act on the result(dropwhile, takewhile, etc.) the control could be fine enough to increase usability (that's the way i think right now), and you will be able to combine generator without lose performance. >> Well, it works for what i need, but is not very neat, and i think that >> there it should be a formal way to act on the base indexing iterator, >> such way exists? Is there a better approach to get what i need? > > Reverse your operation. > -- > http://mail.python.org/mailman/listinfo/python-list > -- Jorge Eduardo Cardona jorgeecardona at gmail.com jorgeecardona.blogspot.com ------------------------------------------------ Linux registered user #391186 Registered machine #291871 ------------------------------------------------ From dbd at ieee.org Mon Dec 7 13:53:31 2009 From: dbd at ieee.org (dbd) Date: Mon, 7 Dec 2009 10:53:31 -0800 (PST) Subject: Float precision and float equality References: <2f0dee67-6fda-47c0-8266-d2d6b02ed655@e4g2000prn.googlegroups.com> <574bd33c-a38b-4af5-802e-fc081965a230@g23g2000vbr.googlegroups.com> <6624fc07-c6d5-40e1-a899-6eb73603a980@u8g2000prd.googlegroups.com> <335cb11d-e862-4daa-aec6-8f96b56bc28a@u1g2000pre.googlegroups.com> <79c41269-2b84-4fb1-8694-c7212f92be62@d9g2000prh.googlegroups.com> <49d04d6f-551b-46a9-8a11-7abe308a0154@f10g2000vbl.googlegroups.com> Message-ID: <8477d937-f44a-4e78-aa35-d97cb1ab5c06@f20g2000prn.googlegroups.com> On Dec 7, 4:28?am, sturlamolden wrote: > ... > > You don't understand this at all do you? > > If you have a sine wave with an amplitude less than the truncation > error, it will always be approximately equal to zero. > > Numerical maths is about approximations, not symbolic equalities. > > > 1.0 + eps is the smallest value greater than 1.0, distinguishable from > > 1.0. > > Which is the reason 0.5*eps*sin(x) is never distinguishable from 0. > ... A calculated value of 0.5*eps*sin(x) has a truncation error on the order of eps squared. 0.5*eps and 0.495*eps are readily distinguished (well, at least for values of eps << 0.01 :). At least one of us doesn't understand floating point. Dale B. Dalrymple From dfnsonfsduifb at gmx.de Mon Dec 7 14:16:38 2009 From: dfnsonfsduifb at gmx.de (Johannes Bauer) Date: Mon, 07 Dec 2009 20:16:38 +0100 Subject: Python3: Sane way to deal with broken encodings In-Reply-To: <4b1c1bea$0$9415$426a74cc@news.free.fr> References: <7o2ibkF3o3ddhU1@mid.dfncis.de> <4b1c1bea$0$9415$426a74cc@news.free.fr> Message-ID: <7o52kgF3n2kg0U1@mid.dfncis.de> Bruno Desthuilliers schrieb: >> Is that possible? If so, how? > > This might get you started: > > """ >>>> help(str.decode) > decode(...) > S.decode([encoding[,errors]]) -> object Hmm, this would work nicely if I called "decode" explicitly - but what I'm doing is: #!/usr/bin/python3 for line in open("broken", "r"): pass Which still raises the UnicodeDecodeError when I do not even do any decoding explicitly. How can I achieve this? Kind regards, Johannes -- "Aus starken Potentialen k?nnen starke Erdbeben resultieren; es k?nnen aber auch kleine entstehen - und "du" wirst es nicht f?r m?glich halten (!), doch sieh': Es k?nnen dabei auch gar keine Erdbeben resultieren." -- "R?diger Thomas" alias Thomas Schulz in dsa ?ber seine "Vorhersagen" <1a30da36-68a2-4977-9eed-154265b17d28 at q14g2000vbi.googlegroups.com> From benjamin.kaplan at case.edu Mon Dec 7 14:42:13 2009 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Mon, 7 Dec 2009 14:42:13 -0500 Subject: Python3: Sane way to deal with broken encodings In-Reply-To: <7o52kgF3n2kg0U1@mid.dfncis.de> References: <7o2ibkF3o3ddhU1@mid.dfncis.de> <4b1c1bea$0$9415$426a74cc@news.free.fr> <7o52kgF3n2kg0U1@mid.dfncis.de> Message-ID: On Mon, Dec 7, 2009 at 2:16 PM, Johannes Bauer wrote: > Bruno Desthuilliers schrieb: > >>> Is that possible? If so, how? >> >> This might get you started: >> >> """ >>>>> help(str.decode) >> decode(...) >> ? ? S.decode([encoding[,errors]]) -> object > > Hmm, this would work nicely if I called "decode" explicitly - but what > I'm doing is: > > #!/usr/bin/python3 > for line in open("broken", "r"): > ? ? ? ?pass > > Which still raises the UnicodeDecodeError when I do not even do any > decoding explicitly. How can I achieve this? > > Kind regards, > Johannes > Looking at the python 3 docs, it seems that open takes the encoding and errors parameters as optional arguments. So you can call open('broken', 'r',errors='replace') > -- > "Aus starken Potentialen k?nnen starke Erdbeben resultieren; es k?nnen > aber auch kleine entstehen - und "du" wirst es nicht f?r m?glich halten > (!), doch sieh': Es k?nnen dabei auch gar keine Erdbeben resultieren." > -- "R?diger Thomas" alias Thomas Schulz in dsa ?ber seine "Vorhersagen" > <1a30da36-68a2-4977-9eed-154265b17d28 at q14g2000vbi.googlegroups.com> > -- > http://mail.python.org/mailman/listinfo/python-list > From roy at panix.com Mon Dec 7 14:46:47 2009 From: roy at panix.com (Roy Smith) Date: Mon, 7 Dec 2009 11:46:47 -0800 (PST) Subject: unittest buffing output on windows? Message-ID: <55763b02-4d4e-4ef6-acd2-18f00a26464f@9g2000yqa.googlegroups.com> I'm running 2.5.1. I've got a test suite that takes about 15 minutes to complete. On my unix boxes, as each test case executes, it prints out a line (I'm using unittest.TextTestRunner(verbosity=2)) of status, but on my windows box (running under cygwin), it buffers everything until the entire test suite is completed. I can stick sys.stdout.flush() and sys.stderr.flush() in my tearDown() method, which gets me output, but that doesn't seem like the right solution. Is there a better way to get the test runner to flush output after every test case? From vicente.soler at gmail.com Mon Dec 7 14:48:24 2009 From: vicente.soler at gmail.com (vsoler) Date: Mon, 7 Dec 2009 11:48:24 -0800 (PST) Subject: Where is my namespace? References: Message-ID: <5424c82c-cb1b-4994-8b36-15b5aad1da13@m25g2000yqc.googlegroups.com> On Dec 7, 5:39?pm, Benjamin Kaplan wrote: > On Mon, Dec 7, 2009 at 11:10 AM, vsoler wrote: > > I take the example from Mark Lutz's excellent book "Learning Python". > > > *** In nested1.py ?I have: > > X=99 > > def printer(): print X > > > *** In nested2.py ?I have: > > from nested1 import X, printer > > X=88 > > printer() > > > What is amazing is that running nested2.py prints 99 and not 88. > > > My questions are: > > > 1. Using statement "from" instead of "import" should not create a > > namespace, at least that's what I think. However, the printer() > > function is able to find 99 which is residing in... ?a namespace? > > It doesn't create a namespace. But printer is still in nested1. When > you do a "from ... import ...", the objects are imported into the > current namespace. However, they are different names for what is > currently the same object. They still follow Python's object > semantics. Here's a simplified overview of what happens > > you run nested2.py > > 1 namespace: nested2, nothing in it (except for the special stuff) > > you run "from nested1 import X, printer". This executes everything in > nested1 (because def and class are just executable statements in > Python) and binds X and printer in nested2 to the objects in nested1. > Note that these are now different names for the same objects. > > nested1: X = 99, printer = > nested2: X = 99 printer = > > you call X = 88. Because you are rebinding the object, this name > (nested2.X) is the only one that gets changed. Rebinding doesn't touch > the object in nested1. > > nested1: X=99, printer = > nested2: x=88 printer = > > Notice how the name "printer" in nested2 still refers to an object in > nested1. It is simply another reference, not a new object. When you > call printer, it's still sitting in nested1 and only sees nested1's X. > > > 2. I have tried to access the 88 by qualification from nested2.py. > > However, I cannot. If using "print nested1.X" in nested2.py I get an > > error > > that's because when you do "from ... import ..." it doesn't import the > module itself. There's a totally different behavior between from ... > import and import. Here's what you're trying to do > > nested2.py : > > import nested1 > > nested1.X = 88 > nested1.printer() > > > > > 3. Mark says: The from statement is really an assignment to names in > > the importer's scope--a name-copy operation, not a name aliasing. ? I > > don't fully understand what he means. Could anybody explain? > > Like I showed before, when you change the unqualified "X" in nested2, > the X in nested1 doesn't change. Using from import is identical to > doing something like this > > a = 1 > b = a > b = 5 > a == 1 #True > > a is a name that temporarily referred to the same object as a. > However, when you reassign b, it makes the name "b" refer to a > different object. It doesn't change the object that a and b both refer > to. When you import using ?from ... import, you end up with 2 > different names that, at the start refer to the same object. Mutation > (if you're using a mutable object) will show up in both namespaces, > since they are referring to the same object, but assignment does not. > > > Thank you very much for your time. > > > Vicente Soler > > -- > >http://mail.python.org/mailman/listinfo/python-list > > I appreciate the preciseness and clearness of your explanations. Thank you very much indeed. Vicente Soler From mal at egenix.com Mon Dec 7 14:51:15 2009 From: mal at egenix.com (M.-A. Lemburg) Date: Mon, 07 Dec 2009 20:51:15 +0100 Subject: Graph library for Python (was: Re: python bijection) In-Reply-To: References: <4B17A960.1090700@egenix.com> <4B17FBFE.8070903@egenix.com> <4B18F685.8050102@egenix.com> <4B1CFA36.9060805@egenix.com> <4B1D35BC.5000002@egenix.com> Message-ID: <4B1D5CB3.8030805@egenix.com> geremy condra wrote: > How interested are you in a C port of graphine? I haven't had > any specific requests for it, but if its something you need I > can shuffle it towards the top of the to do pile. There are two main reasons for a C implementation: 1. performance 2. memory footprint These are important when using graphs with lots of nodes or when using lots of graphs or operations on graphs in tight loops. However, to get such a new type into the core, you need to start a PEP process and hash out the API some more, esp. with respect to integration with the other core types, such as dictionaries and lists of tuples for both creation and as alternative representation. Some other comments (in no particular order): * the "name" default of using id(node) is not ideal, since id(node) will return the address of the object and that can be subject to reuse within the lifetime of the process; using a global (thread-safe) counter would be safer * Graph.__init__ should be able to take a list or set of nodes and edges as initializer * Graph.__setitem__ could be mapped to .add_node() for convenience * Graph.__length__ could be mapped to .size() for convenience * Graph.__iter__ could be mapped to an iterator using the fastest traversal method for the graph nodes (ie. order does not matter, it's only important that all nodes are found as fast as possible) * Graph could also benefit from some bulk update methods, e.g. to update weights on all edges or nodes by passing in a dictionary mapping names to attribute values * Graph could benefit from some bulk query methods, such as .get_node_attributes() and .add_edges(). * Node.__getitem__ could be mapped to .data.__getitem__ (following the approach taken by ElementTree); same for Edge.__getitem__ * Node.__setitem__ could be mapped to .data.__setitem__ (following the approach taken by ElementTree); same for Edge.__setitem__ * I'd add a DirectedEdge alias for Edge and a new UndirectedEdge as subclass which has is_directed=False; makes code more readable -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Dec 07 2009) >>> 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 our new mxODBC.Connect Python Database Interface 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 http://www.egenix.com/company/contact/ From tjreedy at udel.edu Mon Dec 7 14:51:39 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 07 Dec 2009 14:51:39 -0500 Subject: dict.fromkeys strange behavior In-Reply-To: <8a0588790912070042j5954f48u360f3cfabf19bf12@mail.gmail.com> References: <8a0588790912070042j5954f48u360f3cfabf19bf12@mail.gmail.com> Message-ID: Tsviki Hirsh wrote: > >>>dict.fromkeys('at',50) > {'a': 50, 't': 50} > > This is obviously not what I wanted. Not obvious at all. It is precisely what you asked for ;-) Please read the doc: 5.8. Mapping Types ? dict "classmethod fromkeys(seq[, value]) Create a new dictionary with keys from seq and values set to value." The purpose of .fromkeys is to create a dict with multiple keys initially mapped to the one and same value (None by default). If you do not want that, do not use it. or nearly as clear: >>> help(dict.fromkeys) fromkeys(...) dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v. v defaults to None. I *strongly* recommend that all beginners peruse the Library Reference up through Chapter 5. It you are puzzled by the behavior of a builtin object, go back and look up the specific doc. > What are the alternatives? If you want {'at':50}, say that. Terry Jan Reedy From tjreedy at udel.edu Mon Dec 7 15:07:58 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 07 Dec 2009 15:07:58 -0500 Subject: Two questions ( Oracle and modules ) In-Reply-To: References: Message-ID: Gabor Urban wrote: > Hi guys, > 2. We have tp write a module that will be imported a couple of places. > Though we must be sure, this module's initialization is performed only > once. How can we implement this? I do not know what to google for..... There are two ways to have one file executed twice to create two module objects with two different names. 1) run it as the main file and also import it; 2) import with sufficiently different import statements. (I do not know all the ways to 'accomplish' the latter, but I know it can be done.) So, if you do not execute that module as the main script and you use the exact same import statement everywhere, so that the resulting module is given the exact same name, then it will be created once and subsequent imports will return the same object. This is the normal situation. The two cases above are typically accidents. If you have doubts, put print("Hello, module xxx being initialized.") at the top of the module. tjr From davea at ieee.org Mon Dec 7 15:20:16 2009 From: davea at ieee.org (Dave Angel) Date: Mon, 07 Dec 2009 15:20:16 -0500 Subject: unittest buffing output on windows? In-Reply-To: <55763b02-4d4e-4ef6-acd2-18f00a26464f@9g2000yqa.googlegroups.com> References: <55763b02-4d4e-4ef6-acd2-18f00a26464f@9g2000yqa.googlegroups.com> Message-ID: <4B1D6380.8000701@ieee.org> Roy Smith wrote: > I'm running 2.5.1. I've got a test suite that takes about 15 minutes > to complete. On my unix boxes, as each test case executes, it prints > out a line (I'm using unittest.TextTestRunner(verbosity=2)) of status, > but on my windows box (running under cygwin), it buffers everything > until the entire test suite is completed. > > I can stick sys.stdout.flush() and sys.stderr.flush() in my tearDown() > method, which gets me output, but that doesn't seem like the right > solution. Is there a better way to get the test runner to flush > output after every test case? > > You could try starting Python with the -u switch, which says don't buffer stdout. or stderr (at least on Python 2.6). Try running python -? to see the commandline options. On the other hand, if it's specifically a cygwin problem, I have no idea. DaveA From pavlovevidence at gmail.com Mon Dec 7 15:58:50 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 7 Dec 2009 12:58:50 -0800 (PST) Subject: Float precision and float equality References: <2f0dee67-6fda-47c0-8266-d2d6b02ed655@e4g2000prn.googlegroups.com> <574bd33c-a38b-4af5-802e-fc081965a230@g23g2000vbr.googlegroups.com> <6624fc07-c6d5-40e1-a899-6eb73603a980@u8g2000prd.googlegroups.com> <335cb11d-e862-4daa-aec6-8f96b56bc28a@u1g2000pre.googlegroups.com> <79c41269-2b84-4fb1-8694-c7212f92be62@d9g2000prh.googlegroups.com> <49d04d6f-551b-46a9-8a11-7abe308a0154@f10g2000vbl.googlegroups.com> <8477d937-f44a-4e78-aa35-d97cb1ab5c06@f20g2000prn.googlegroups.com> Message-ID: <81fcae23-ed2c-4a48-b9d5-dae1002df848@z35g2000prh.googlegroups.com> On Dec 7, 10:53?am, dbd wrote: > On Dec 7, 4:28?am, sturlamolden wrote: > > > ... > > > You don't understand this at all do you? > > > If you have a sine wave with an amplitude less than the truncation > > error, it will always be approximately equal to zero. > > > Numerical maths is about approximations, not symbolic equalities. > > > > 1.0 + eps is the smallest value greater than 1.0, distinguishable from > > > 1.0. > > > Which is the reason 0.5*eps*sin(x) is never distinguishable from 0. > > ... > > A calculated value of 0.5*eps*sin(x) has a truncation error on the > order of eps squared. 0.5*eps and 0.495*eps are readily distinguished > (well, at least for values of eps << 0.01 :). > > At least one of us doesn't understand floating point. You're talking about machine epsilon? I think everyone else here is talking about a number that is small relative to the expected smallest scale of the calculation. Carl Banks From dreadpiratejeff at gmail.com Mon Dec 7 16:13:25 2009 From: dreadpiratejeff at gmail.com (J) Date: Mon, 7 Dec 2009 16:13:25 -0500 Subject: question about imports in a class Message-ID: <36dec4ff0912071313rc6f95e1g683d851232c388f7@mail.gmail.com> Just a little newbie confusion about OS imports... Why does this give me an error: class Windows: def __init__(self): ''' Constructor ''' import os self.dmidecodePath="" #final path to dmidecode binary def parseDMI(self): # First, find dmidecode.exe for root,dirs,files in os.walk('C:\\'): for file in files: if file == "dmidecode.exe": self.dmidecodePath=[os.path.normcase(os.path.join(root,file))] return "Found DMIDecode.exe at %s" % self.dmidecodePath break Keep in mind that this is very early stage code and does nothing so far other than telling me where to find dmidecode.exe... But why does importing in the init not make os available to every other function in the class? Do I have to import OS into every function like this: class ClassA(): def func1(self): import os def func2(self): import os Also, when I DO have the import statement inside the function definition, I'm screwing up the join and getting this: "C:\\dmidecod\\sbin\\dmidecode.exe" What am I doing that's creating the two \ characters?? Anyway, the first question I'm just asking because I'm still trying to figure out the heirarchy and how classes work in Python, the other is because I'm just annoyed... Also, that brings up a third question: So in my class, I import OS. Now, in my calling script, do I also import OS, or will I inheirit OS as part of the class object? IOW: script.py thisclass=myclass(): #where myclass imports os for r,d,f in os.walk(path) or would I have to do something like: for r,d,f in thisclass.os.wall(path) Or do I just have to also import OS into script.py?? Thanks! I know enough to be dangerous, so trying to become less so now... Jeff -- Ogden Nash - "The trouble with a kitten is that when it grows up, it's always a cat." - http://www.brainyquote.com/quotes/authors/o/ogden_nash.html From rhodri at wildebst.demon.co.uk Mon Dec 7 16:43:49 2009 From: rhodri at wildebst.demon.co.uk (Rhodri James) Date: Mon, 07 Dec 2009 21:43:49 -0000 Subject: python proxy checker ,change to threaded version In-Reply-To: References: Message-ID: On Mon, 07 Dec 2009 18:21:23 -0000, Terry Reedy wrote: > r0g wrote: > >> The trick to threads is to create a subclass of threading.Thread, define >> the 'run' function and call the 'start()' method. I find threading quite >> generally useful so I created this simple generic function for running >> things in threads... > > Great idea. Thanks for posting this. > >> def run_in_thread( func, func_args=[], callback=None, callback_args=[] >> ): I'm might wary of having mutable defaults for parameters. They make for the most annoying errors. Even though they're actually safe here, I'd still write: def run_in_thread(func, func_args=(), callback=None, callback_args=()): out of sheer paranoia. >> import threading >> class MyThread ( threading.Thread ): >> def run ( self ): >> # Call function >> if function_args: >> result = function(*function_args) >> else: >> result = function() > > The check is not necessary. by design, f(*[]) == f() > Names do not match param names ;=) > >> # Call callback >> if callback: >> if callback_args: >> callback(result, *callback_args) >> else: >> callback(result) > > Ditto. g(x,*[]) == g(x) > > def run(self): > result = func(*func_args) # matching run_in_thread param names > callback(result, *callback_args) Neat, but I think you mean if callback is not None: callback(result, *callback_args) for that last line. > > >> MyThread().start() > > This is one of the best uses I have seen for a nested class definition. Ditto! -- Rhodri James *-* Wildebeest Herder to the Masses From deets at nospam.web.de Mon Dec 7 16:45:19 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 07 Dec 2009 22:45:19 +0100 Subject: question about imports in a class In-Reply-To: References: Message-ID: <7o5bbhF3ofkbpU1@mid.uni-berlin.de> J schrieb: > Just a little newbie confusion about OS imports... > > Why does this give me an error: > > class Windows: > > def __init__(self): > ''' > Constructor > ''' > import os > self.dmidecodePath="" #final path to dmidecode binary > > def parseDMI(self): > # First, find dmidecode.exe > > for root,dirs,files in os.walk('C:\\'): > for file in files: > if file == "dmidecode.exe": > > self.dmidecodePath=[os.path.normcase(os.path.join(root,file))] > return "Found DMIDecode.exe at %s" % self.dmidecodePath > break > > Keep in mind that this is very early stage code and does nothing so > far other than telling me where to find dmidecode.exe... > > But why does importing in the init not make os available to every > other function in the class? Do I have to import OS into every > function like this: > > class ClassA(): > > def func1(self): > import os > > def func2(self): > import os No, you don't have to - you just import it once at the module level. > Also, when I DO have the import statement inside the function > definition, I'm screwing up the join and getting this: > "C:\\dmidecod\\sbin\\dmidecode.exe" > > What am I doing that's creating the two \ characters?? No, you don't screw it up, "\\" is escape-codes for backslash, and I guess what you see is because you work in the interactive interpreter that calls repr() on a string when it's displayed - like this: >>> "\\" '\\' >>> print "\\" \ >>> print repr("\\") '\\' > > Anyway, the first question I'm just asking because I'm still trying to > figure out the heirarchy and how classes work in Python, the other is > because I'm just annoyed... > > Also, that brings up a third question: > > So in my class, I import OS. Now, in my calling script, do I also > import OS, or will I inheirit OS as part of the class object? No, it doesn't, and I'd say you better forget about importing inside functions (methods or normal ones) until you have firmer grasp on how python namespaces work. > > IOW: > > script.py > > thisclass=myclass(): #where myclass imports os > > for r,d,f in os.walk(path) > > or would I have to do something like: > > for r,d,f in thisclass.os.wall(path) > > Or do I just have to also import OS into script.py?? Yes, you do. Diez From dreadpiratejeff at gmail.com Mon Dec 7 16:53:46 2009 From: dreadpiratejeff at gmail.com (J) Date: Mon, 7 Dec 2009 16:53:46 -0500 Subject: question about imports in a class In-Reply-To: <36dec4ff0912071313rc6f95e1g683d851232c388f7@mail.gmail.com> References: <36dec4ff0912071313rc6f95e1g683d851232c388f7@mail.gmail.com> Message-ID: <36dec4ff0912071353j4b42b371h556367ab3b95c40b@mail.gmail.com> On Mon, Dec 7, 2009 at 16:13, J wrote: > But why does importing in the init not make os available to every > other function in the class? ?Do I have to import OS into every > function like this: > > class ClassA(): > > ? ?def func1(self): > ? ? ? ?import os > > ? ?def func2(self): > ? ? ? ?import os A little more education and playing around and I'm still not quite sure how to do this... for the class i'm writing, I want to import os, sys and wmi globally for the class... if I put the import at the beginning of the class, it just dawned on me that perhaps I still have to explicitly call the function by class: sysinfo.py class myclass(): import os def findDMIDecode(self): for r,d,f in myclass.os.walk(args) is that correct? How about if I have two classes in sysinfo.py and want to import os globally for BOTH classes to use? Same thing? > Also, when I DO have the import statement inside the function > definition, I'm screwing up the join and getting this: > "C:\\dmidecod\\sbin\\dmidecode.exe" Still not sure about this, but I DO know where I glaringly screwed up. Originally, the function that finds the dmidecode executable was doing this: return dmidecodePath # dmidecodePath is, I learned, a list that contains the results of # self.dmidecodePath=[os.path.normcase(os.path.join(root,file))] which is wrong, because on the calling side, I was just using the whole return, which was actually a list, not a string, so this was fixed simply by: return dmidecodePath[0] which now returns simply: c:\dmidecode\sbin\dmidecode.exe So that seems correct. Also, I apologize if my code examples are incomplete. If they are not complete "enough" please let me know. I'm doing this for work, and not sure just how much I can really post without violating any obligations on my end.. so I'm trying to provide generic examples based on the code I'm actually trying to write. -- Stephen Leacock - "I detest life-insurance agents: they always argue that I shall some day die, which is not so." - http://www.brainyquote.com/quotes/authors/s/stephen_leacock.html From deets at nospam.web.de Mon Dec 7 16:57:22 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 07 Dec 2009 22:57:22 +0100 Subject: question about imports in a class In-Reply-To: References: <36dec4ff0912071313rc6f95e1g683d851232c388f7@mail.gmail.com> Message-ID: <7o5c23F3o5rkgU1@mid.uni-berlin.de> J schrieb: > On Mon, Dec 7, 2009 at 16:13, J wrote: > >> But why does importing in the init not make os available to every >> other function in the class? Do I have to import OS into every >> function like this: >> >> class ClassA(): >> >> def func1(self): >> import os >> >> def func2(self): >> import os > > A little more education and playing around and I'm still not quite > sure how to do this... > > for the class i'm writing, I want to import os, sys and wmi globally > for the class... > if I put the import at the beginning of the class, it just dawned on > me that perhaps I still have to explicitly call the function by class: > > sysinfo.py > > class myclass(): > import os > def findDMIDecode(self): > for r,d,f in myclass.os.walk(args) > > is that correct? It is correct in the sense that it works, but it is by no means good practice. > > How about if I have two classes in sysinfo.py and want to import os > globally for BOTH classes to use? Same thing? import os class A(): ... class B(): ... That's it. Diez From rhodri at wildebst.demon.co.uk Mon Dec 7 17:14:52 2009 From: rhodri at wildebst.demon.co.uk (Rhodri James) Date: Mon, 07 Dec 2009 22:14:52 -0000 Subject: question about imports in a class In-Reply-To: <36dec4ff0912071313rc6f95e1g683d851232c388f7@mail.gmail.com> References: <36dec4ff0912071313rc6f95e1g683d851232c388f7@mail.gmail.com> Message-ID: On Mon, 07 Dec 2009 21:13:25 -0000, J wrote: > Just a little newbie confusion about OS imports... > > Why does this give me an error: It's generally helpful to say *what* error you get, including the traceback. Fortunately the source code is enough this time. > class Windows: > > def __init__(self): > ''' > Constructor > ''' > import os [snip the rest] This is a bad idea for the reasons you explained yourself. This import statement goes off and loads the module "os" and binds it to the name "os". That name is local to Windows.__init__, just like any other name you'd bind here that wasn't explicitly declared to be global. What you actually want is for "os" to be a global name; there are a whole bunch of insane ways of doing that, but the usual and least confusing thing to do is: import os class Windows: def __init__(self): # Do stuff... [the next function was] > def parseDMI(self): > # First, find dmidecode.exe > for root,dirs,files in os.walk('C:\\'): > for file in files: > if file == "dmidecode.exe": >self.dmidecodePath=[os.path.normcase(os.path.join(root,file))] > return "Found DMIDecode.exe at %s" % > self.dmidecodePath > break I assume the formatting is the fault of some mailer somewhere trying to wrap the long line. Such is life. The break after the return statement is a bit pointless, though. It's never going to get executed. > Also, when I DO have the import statement inside the function > definition, I'm screwing up the join and getting this: > "C:\\dmidecod\\sbin\\dmidecode.exe" > > What am I doing that's creating the two \ characters?? At a guess, nothing. Would I be right in thinking that what you actually get is ['C:\\dmidecod\\sbin\\dmidecode.exe'] ? When you use string formatting with a list argument, the list turns itself into a string by calling repr() on its elements. repr() on a string produces something that you could cut and paste into code as a string literal; to do that without changing the meaning of the string, it escapes the backslashes with another backslash. You can play with this for yourself in the interactive shell: rhodri at gnudebst:~$ python Python 2.6.4 (r264:75706, Nov 2 2009, 14:44:17) [GCC 4.4.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> print r"hello \ world" hello \ world >>> s = r"hello \ world" >>> print s hello \ world >>> print str(s) hello \ world >>> print repr(s) 'hello \\ world' >>> a = [r"hello \ world"] >>> a ['hello \\ world'] >>> print a ['hello \\ world'] >>> print "message = %s" % a message = ['hello \\ world'] >>> > So in my class, I import OS. Now, in my calling script, do I also > import OS, or will I inheirit OS as part of the class object? Since you don't bind the name "os" into your class (and you shouldn't, since that would definitely be a code smell), you aren't going to inherit it. Just import it where you need to and stop trying to make your life difficult! It doesn't in fact cost you anything, since Python caches the module the first time you load it precisely to avoid having to go back to the disc every time you want to reload it. -- Rhodri James *-* Wildebeest Herder to the Masses From steve at REMOVE-THIS-cybersource.com.au Mon Dec 7 17:17:16 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 07 Dec 2009 22:17:16 GMT Subject: Where is my namespace? References: Message-ID: <00a7037c$0$15659$c3e8da3@news.astraweb.com> On Mon, 07 Dec 2009 16:25:39 +0000, Simon Brunning wrote: > 2009/12/7 vsoler : [...] > If you do "from blah import" the imported module itself isn't bound to > any name in the importing module - you can't get at it at all. Not quite -- you can get to it if you're willing to do some more work. >>> from math import sin >>> mod = __import__(sin.__module__) >>> mod Alternatively, you can fetch it from sys.modules directly, but that's probably an implementation-specific trick. >> 3. Mark says: The from statement is really an assignment to names in >> the importer's scope--a name-copy operation, not a name aliasing. ? I >> don't fully understand what he means. Could anybody explain? I'm not sure what Mark means by that either. It certainly isn't a copy operation, it doesn't duplicate the object you imported. I don't know what he means by aliasing, but if he means what I mean by aliasing, then I'd say the from statement *is* an aliasing operation: it creates a new name that refers to an existing object found by name. from module import name is roughly equivalent to: import module name = module.name del module -- Steven From tjreedy at udel.edu Mon Dec 7 17:18:48 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 07 Dec 2009 17:18:48 -0500 Subject: python proxy checker ,change to threaded version In-Reply-To: References: Message-ID: Rhodri James wrote: > On Mon, 07 Dec 2009 18:21:23 -0000, Terry Reedy wrote: >> def run(self): >> result = func(*func_args) # matching run_in_thread param names >> callback(result, *callback_args) > Neat, but I think you mean > > if callback is not None: > callback(result, *callback_args) > > for that last line. yes [blush] I forgot to add 'untested ;-) From dreadpiratejeff at gmail.com Mon Dec 7 17:18:49 2009 From: dreadpiratejeff at gmail.com (J) Date: Mon, 7 Dec 2009 17:18:49 -0500 Subject: question about imports in a class In-Reply-To: <7o5c23F3o5rkgU1@mid.uni-berlin.de> References: <36dec4ff0912071313rc6f95e1g683d851232c388f7@mail.gmail.com> <7o5c23F3o5rkgU1@mid.uni-berlin.de> Message-ID: <36dec4ff0912071418t1759cb49h98aec6df15f8820c@mail.gmail.com> On Mon, Dec 7, 2009 at 16:57, Diez B. Roggisch wrote: >> if I put the import at the beginning of the class, it just dawned on >> me that perhaps I still have to explicitly call the function by class: >> >> sysinfo.py >> >> class myclass(): >> ? ?import os >> ? ?def findDMIDecode(self): >> ? ? ? ?for r,d,f in myclass.os.walk(args) >> >> is that correct? > > It is correct in the sense that it works, but it is by no means good > practice. So good practice (I'm doing this for real as well as for my own education) would be: sysinfo.py: import os class ClassA(): sysinfo.os.walk() class ClassB(): sysinfo.os.walk() Sorry for the incredibly entry-level questions... I'm a more senior member on a few Linux related lists/groups, and I can certainly understand if questions as basic as these are annoying, so I'm really trying to not ask them unless I'm just really confused about something. OTOH, if there's something more akin to a python newbies kind of list where this kind of basic thing is more appropriate, please let me know, because really, I don't want to clutter up python-list with stuff that would be better off elsewhere. -- Marie von Ebner-Eschenbach - "Even a stopped clock is right twice a day." - http://www.brainyquote.com/quotes/authors/m/marie_von_ebnereschenbac.html From debatem1 at gmail.com Mon Dec 7 17:23:24 2009 From: debatem1 at gmail.com (geremy condra) Date: Mon, 7 Dec 2009 17:23:24 -0500 Subject: Graph library for Python (was: Re: python bijection) In-Reply-To: <4B1D5CB3.8030805@egenix.com> References: <4B17FBFE.8070903@egenix.com> <4B18F685.8050102@egenix.com> <4B1CFA36.9060805@egenix.com> <4B1D35BC.5000002@egenix.com> <4B1D5CB3.8030805@egenix.com> Message-ID: On Mon, Dec 7, 2009 at 2:51 PM, M.-A. Lemburg wrote: > geremy condra wrote: >> How interested are you in a C port of graphine? I haven't had >> any specific requests for it, but if its something you need I >> can shuffle it towards the top of the to do pile. > > There are two main reasons for a C implementation: > > ?1. performance > > ?2. memory footprint > > These are important when using graphs with lots of nodes or > when using lots of graphs or operations on graphs in tight > loops. > > However, to get such a new type into the core, you need to start > a PEP process and hash out the API some more, esp. with respect > to integration with the other core types, such as dictionaries > and lists of tuples for both creation and as alternative > representation. I'm happy to start the PEP process, but will need some guidance, as I've never written a PEP before. > Some other comments (in no particular order): > > ?* the "name" default of using id(node) is not ideal, since > ? id(node) will return the address of the object and that > ? can be subject to reuse within the lifetime of the process; > ? using a global (thread-safe) counter would be safer Good idea. I'm going to start a branch on the repo to handle the changes you mention. > ?* Graph.__init__ should be able to take a list or set > ? of nodes and edges as initializer The format of this will need to be thought all the way through before being implemented. To date, we haven't come up with anything completely satisfactory, but AFAIK everybody involved is still open to suggestions on this. > ?* Graph.__setitem__ could be mapped to .add_node() for > ? convenience This may be a question of playing around with it. ATM I'm not sold on the idea, but I'll implement it and see how it turns out in practice. > ?* Graph.__length__ could be mapped to .size() for > ? convenience We decided not to do this due to the ambiguity between whether .size() or .order() was the intended operation, and looking back I'm not sure that was entirely unjustified. Do you see there being any confusion on that score? > ?* Graph.__iter__ could be mapped to an iterator using > ? the fastest traversal method for the graph nodes > ? (ie. order does not matter, it's only important that > ? all nodes are found as fast as possible) Again, it seems ambiguous as to whether nodes or edges are the intended target here, and while the API can obviously dictate that, it seems a bit like a case of "in the face of ambiguity, refuse the temptation to guess" to me. > ?* Graph could also benefit from some bulk update methods, > ? e.g. to update weights on all edges or nodes by passing > ? in a dictionary mapping names to attribute values Sounds good. Again, the format will need some careful thought, but you're right that this would improve it greatly. > ?* Graph could benefit from some bulk query methods, > ? such as .get_node_attributes() and .add_edges(). I'm not sure how the first is different from the existing .data, what did you have in mind? > ?* Node.__getitem__ could be mapped to .data.__getitem__ > ? (following the approach taken by ElementTree); same > ? for Edge.__getitem__ > ?* Node.__setitem__ could be mapped to .data.__setitem__ > ? (following the approach taken by ElementTree); same > ? for Edge.__setitem__ .data is just a property that returns a dictionary of non private members right now, so if you're wanting to just say node.this = 'stuff', you can already do that. Or am I misreading your intent? > ?* I'd add a DirectedEdge alias for Edge and a new > ? UndirectedEdge as subclass which has is_directed=False; > ? makes code more readable Sounds good, and thanks for the advice! Geremy Condra From rhodri at wildebst.demon.co.uk Mon Dec 7 17:26:16 2009 From: rhodri at wildebst.demon.co.uk (Rhodri James) Date: Mon, 07 Dec 2009 22:26:16 -0000 Subject: question about imports in a class In-Reply-To: <36dec4ff0912071418t1759cb49h98aec6df15f8820c@mail.gmail.com> References: <36dec4ff0912071313rc6f95e1g683d851232c388f7@mail.gmail.com> <7o5c23F3o5rkgU1@mid.uni-berlin.de> <36dec4ff0912071418t1759cb49h98aec6df15f8820c@mail.gmail.com> Message-ID: On Mon, 07 Dec 2009 22:18:49 -0000, J wrote: > On Mon, Dec 7, 2009 at 16:57, Diez B. Roggisch > wrote: > >>> if I put the import at the beginning of the class, it just dawned on >>> me that perhaps I still have to explicitly call the function by class: >>> >>> sysinfo.py >>> >>> class myclass(): >>> import os >>> def findDMIDecode(self): >>> for r,d,f in myclass.os.walk(args) >>> >>> is that correct? >> >> It is correct in the sense that it works, but it is by no means good >> practice. > > So good practice (I'm doing this for real as well as for my own > education) would be: > > sysinfo.py: > > import os > > class ClassA(): > sysinfo.os.walk() > > class ClassB(): > sysinfo.os.walk() Nope. Good practice would be: import os class ClassA(object): os.walk() class ClassB(object): os.walk() -- Rhodri James *-* Wildebeest Herder to the Masses From steve at REMOVE-THIS-cybersource.com.au Mon Dec 7 17:37:03 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 07 Dec 2009 22:37:03 GMT Subject: question about imports in a class References: <36dec4ff0912071313rc6f95e1g683d851232c388f7@mail.gmail.com> Message-ID: <00a7081e$0$15659$c3e8da3@news.astraweb.com> On Mon, 07 Dec 2009 16:53:46 -0500, J wrote: > A little more education and playing around and I'm still not quite sure > how to do this... > > for the class i'm writing, I want to import os, sys and wmi globally for > the class... The best advice is Do Not Do It That Way. Just do your imports at the top level of the module: import os class MyClass(): def findDMIDecode(self): for r,d,f in os.walk(args): ... (Aside: it is traditional to write class names in Python using initial capitals.) > if I put the import at the beginning of the class, it just dawned on me > that perhaps I still have to explicitly call the function by class: > > class myclass(): > import os > def findDMIDecode(self): > for r,d,f in myclass.os.walk(args) > > is that correct? As Diez says, that works but it's not recommended. It's considered bad form. It may help if you understand what import does: it does two basic functions: it loads a module, and it creates a name in the current namespace. So when you put: import os in the module, it loads os and creates a name 'os' that is now available to everything in the current module without qualification. But when you do this: class MyClass(): import os ... the name 'os' is placed in the MyClass namespace, not the global namespace. So it is only available inside the MyClass namespace. That is precisely the same as if you had done this: class MyClass(): os = "something goes here" ... Having done that, you have created a class attribute named 'os', so in your methods you have to do this: class MyClass(): import os def findDMIDecode(self): for r,d,f in self.os.walk(args): ... This isn't exactly wrong, but it is terribly unusual and almost certainly unnecessary. The only reason I'd do it that way would be if: (1) I needed to hide the os name from other classes or functions in the module; or (2) I wanted the ability to replace the os module in MyClass with a different module at runtime, without affecting other classes or functions. E.g.: inst = MyClass() inst.os = my_fake_os_module inst.findDMIDecode() # calls my_fake_os_module.walk instead of os.walk Both of these use-cases are very, very unusual. (I've never done needed to do this in real code.) Unless you have one of those rare cases, stick to the standard idiom of importing the module at the top level of the class. If you're not sure whether or not you need this, you almost certainly don't. > How about if I have two classes in sysinfo.py and want to import os > globally for BOTH classes to use? Same thing? If one class inherits from the other, then self.os will work via the normal inheritance mechanism. If they are independent classes, then you will need to import os in both of them, or just import it at the module level. -- Steven From benmarinic at googlemail.com Mon Dec 7 17:38:42 2009 From: benmarinic at googlemail.com (shocks) Date: Mon, 7 Dec 2009 14:38:42 -0800 (PST) Subject: How decoupled are the Python frameworks? Message-ID: <6316c8e5-34a0-43e3-92ad-966d95e84108@j24g2000yqa.googlegroups.com> Hi I'm getting back into Python after a long break. I've been developing large enterprise apps solely with Adobe Flex (ActionScript) for the past couple years. During that time I've used a number of 'MVC' frameworks to glue the bits together - among them Cairngorm, a modified implementation of Cairngorm using the Presentation Model pattern, PureMVC, Mate (an IOC container but with an MVC implementation) and Parsley (IOC but you have to roll-you-own MVC). During that time I've been in large teams (30 Flex + 30 Java) to small teams (2 Flex + 1 Java). The motivation of these frameworks is the decouple your concerns, allowing your apps to be more scalable, easier to test, and supposedly easier to maintain. Some do the decoupling better job than others, but there is also the question of "how decoupled is your code from the framework"? It's all well and good having something clever working behind the scenes wiring and routing everything together, but I wonder where this leaves the code base if the framework, which was selected at the beginning of the project, is replaced with something else months or years later (i.e. the framework just doesn't scale as expected, the community involvement dies and it's no longer maintained properly, etc). I've seen it happen and I've been experienced the pain of detangling massive amounts of code which is full of framework specific imports, methods and boilerplate code. And then there's updating the unit tests! My question is how good are the current crop of Python frameworks? I've used Django twice in production and didn't like that much. The implementation is Django specific for starters. I've picked up Pylons and I'm trying that out. I'm not sure how well it fares? I do feel a bit uneasy about the code generation that some of the Python frameworks do. Pylons creates something like 20 files for a 'helloworld'. It does do some great things out of the box, but I wonder where that leaves your own code. After spending 3-6 months on your Pylons webapp, how easy is it to move to something else? Maybe one of the Python IOC once they mature. What are some good techniques people are using to future (framework) proof their apps? I'm interested to hear people experiences with the various frameworks and how decoupled their code is from them. The best of the current Flex frameworks for me is Parsley. The only noticeable Parlsey code is an '[Inject]' meta tag here and there and a couple import statements. All the complicated object creation and messaging is done higher up the chain. Cheers, Ben From deets at nospam.web.de Mon Dec 7 17:44:20 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 07 Dec 2009 23:44:20 +0100 Subject: question about imports in a class In-Reply-To: References: <36dec4ff0912071313rc6f95e1g683d851232c388f7@mail.gmail.com> <7o5c23F3o5rkgU1@mid.uni-berlin.de> Message-ID: <7o5eq5F3krihnU1@mid.uni-berlin.de> J schrieb: > On Mon, Dec 7, 2009 at 16:57, Diez B. Roggisch wrote: > >>> if I put the import at the beginning of the class, it just dawned on >>> me that perhaps I still have to explicitly call the function by class: >>> >>> sysinfo.py >>> >>> class myclass(): >>> import os >>> def findDMIDecode(self): >>> for r,d,f in myclass.os.walk(args) >>> >>> is that correct? >> It is correct in the sense that it works, but it is by no means good >> practice. > > So good practice (I'm doing this for real as well as for my own > education) would be: > > sysinfo.py: > > import os > > class ClassA(): > sysinfo.os.walk() > > class ClassB(): > sysinfo.os.walk() No, no sysinfo. Just import os class A(): def foo(self): os.path.walk("/") > > Sorry for the incredibly entry-level questions... I'm a more senior > member on a few Linux related lists/groups, and I can certainly > understand if questions as basic as these are annoying, so I'm really > trying to not ask them unless I'm just really confused about > something. > > OTOH, if there's something more akin to a python newbies kind of list > where this kind of basic thing is more appropriate, please let me > know, because really, I don't want to clutter up python-list with > stuff that would be better off elsewhere. I'm not annoyed. I just wonder from what you got the impression that import statements are something that belongs inside functions - even if python allows it. I don't know of any other language (I don't do ruby & perl) that allows this, C/C++, java, Pascal, Haskell, ML - all of them declare their intended use of a library on the beginning of a file. You seem to really be really determined to place them everywhere else... Diez From simon at brunningonline.net Mon Dec 7 17:45:12 2009 From: simon at brunningonline.net (Simon Brunning) Date: Mon, 7 Dec 2009 22:45:12 +0000 Subject: Where is my namespace? In-Reply-To: <00a7037c$0$15659$c3e8da3@news.astraweb.com> References: <00a7037c$0$15659$c3e8da3@news.astraweb.com> Message-ID: <8c7f10c60912071445k213cf3b7qeaf0e4a86f6ef3b9@mail.gmail.com> 2009/12/7 Steven D'Aprano : > On Mon, 07 Dec 2009 16:25:39 +0000, Simon Brunning wrote: >> If you do "from blah import" the imported module itself isn't bound to >> any name in the importing module - you can't get at it at all. > > Not quite -- you can get to it if you're willing to do some more work. "A little inaccuracy sometimes saves tons of explanation." - Saki, The Square Egg, 1924 -- Cheers, Simon B. From steve at REMOVE-THIS-cybersource.com.au Mon Dec 7 17:48:22 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 07 Dec 2009 22:48:22 GMT Subject: Graph library for Python (was: Re: python bijection) References: <4B17FBFE.8070903@egenix.com> <4B18F685.8050102@egenix.com> <4B1CFA36.9060805@egenix.com> <4B1D35BC.5000002@egenix.com> <4B1D5CB3.8030805@egenix.com> Message-ID: <00a70ac5$0$15659$c3e8da3@news.astraweb.com> On Mon, 07 Dec 2009 17:23:24 -0500, geremy condra wrote: >> ?* Graph.__iter__ could be mapped to an iterator using >> ? the fastest traversal method for the graph nodes (ie. order does not >> ? matter, it's only important that all nodes are found as fast as >> ? possible) > > Again, it seems ambiguous as to whether nodes or edges are the intended > target here, and while the API can obviously dictate that, it seems a > bit like a case of "in the face of ambiguity, refuse the temptation to > guess" to me. Consider dicts. They have methods that iterates over keys, values, and (key, value) pairs, but if you just iterate over the dict itself, you get the keys. This was a deliberate design decision. It's not a matter of guessing in the face of ambiguity, but giving an easy way to get the most common case. Assuming that iteration over nodes is more common than iteration over edges, then iter(graph) should yield nodes in some unspecified order. If you need the nodes in a particular order, then you will call some method that guarantees the order, and if you want the edges, you call a method that gives edges. If you're not sure whether wanting nodes or edges will be more common, then you should wait until you, or the community, has more real-world experience with the module. Python had dicts for something approaching a decade before they became directly iterable. -- Steven From ben+python at benfinney.id.au Mon Dec 7 18:16:15 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Tue, 08 Dec 2009 10:16:15 +1100 Subject: Duplicates of third-party libraries (was: When will Python 3 be fully deployed) References: Message-ID: <877hsygytc.fsf_-_@benfinney.id.au> "Martin P. Hellwig" writes: > If the fear of customers disatification prevents you from using a > certain version of X, you should consider a deployment strategy that > cuts out dependencies as much as possible. Although this will result > in a larger end package and possible high amount of duplication, it is > still preferable to just stop supporting popular platforms or be > swamped away with bugs due to version mismatches. Along with the duplication this introduces, it also means that any bug fixes ? even severe security fixes ? in the third-party code will not be addressed in your duplicate. This defeats one of the many benefits of a package management operating system: that libraries, updated once, will benefit any other package depending on them. Please reconsider policies like including duplicates of third-party code. Don't Repeat Yourself is a good principle not just within source code, but has important security implications within the operating system packages too. -- \ ?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 debatem1 at gmail.com Mon Dec 7 18:16:58 2009 From: debatem1 at gmail.com (geremy condra) Date: Mon, 7 Dec 2009 18:16:58 -0500 Subject: Graph library for Python (was: Re: python bijection) In-Reply-To: <00a70ac5$0$15659$c3e8da3@news.astraweb.com> References: <4B18F685.8050102@egenix.com> <4B1CFA36.9060805@egenix.com> <4B1D35BC.5000002@egenix.com> <4B1D5CB3.8030805@egenix.com> <00a70ac5$0$15659$c3e8da3@news.astraweb.com> Message-ID: On Mon, Dec 7, 2009 at 5:48 PM, Steven D'Aprano wrote: > On Mon, 07 Dec 2009 17:23:24 -0500, geremy condra wrote: > > >>> ?* Graph.__iter__ could be mapped to an iterator using >>> ? the fastest traversal method for the graph nodes (ie. order does not >>> ? matter, it's only important that all nodes are found as fast as >>> ? possible) >> >> Again, it seems ambiguous as to whether nodes or edges are the intended >> target here, and while the API can obviously dictate that, it seems a >> bit like a case of "in the face of ambiguity, refuse the temptation to >> guess" to me. > > Consider dicts. They have methods that iterates over keys, values, and > (key, value) pairs, but if you just iterate over the dict itself, you get > the keys. This was a deliberate design decision. > > It's not a matter of guessing in the face of ambiguity, but giving an > easy way to get the most common case. Assuming that iteration over nodes > is more common than iteration over edges, then iter(graph) should yield > nodes in some unspecified order. If you need the nodes in a particular > order, then you will call some method that guarantees the order, and if > you want the edges, you call a method that gives edges. > > If you're not sure whether wanting nodes or edges will be more common, > then you should wait until you, or the community, has more real-world > experience with the module. Python had dicts for something approaching a > decade before they became directly iterable. I don't have a problem with adding this if there's a strong desire for it, but at the moment I'm leaning towards a wait-and-see approach, for all the reasons you described. Geremy Condra From mal at egenix.com Mon Dec 7 18:28:49 2009 From: mal at egenix.com (M.-A. Lemburg) Date: Tue, 08 Dec 2009 00:28:49 +0100 Subject: Graph library for Python In-Reply-To: References: <4B17FBFE.8070903@egenix.com> <4B18F685.8050102@egenix.com> <4B1CFA36.9060805@egenix.com> <4B1D35BC.5000002@egenix.com> <4B1D5CB3.8030805@egenix.com> Message-ID: <4B1D8FB1.5010703@egenix.com> geremy condra wrote: > On Mon, Dec 7, 2009 at 2:51 PM, M.-A. Lemburg wrote: >> geremy condra wrote: >>> How interested are you in a C port of graphine? I haven't had >>> any specific requests for it, but if its something you need I >>> can shuffle it towards the top of the to do pile. >> >> There are two main reasons for a C implementation: >> >> 1. performance >> >> 2. memory footprint >> >> These are important when using graphs with lots of nodes or >> when using lots of graphs or operations on graphs in tight >> loops. >> >> However, to get such a new type into the core, you need to start >> a PEP process and hash out the API some more, esp. with respect >> to integration with the other core types, such as dictionaries >> and lists of tuples for both creation and as alternative >> representation. > > I'm happy to start the PEP process, but will need some > guidance, as I've never written a PEP before. Some pointers to get you started: PEPs in general: http://www.python.org/dev/peps/pep-0001/ http://www.python.org/dev/peps/pep-0009/ Adding modules to the standard lib: http://www.python.org/dev/peps/pep-0002/ (though, in reality, you'd probably only be patching the collections.py module, I guess) >> Some other comments (in no particular order): >> >> * the "name" default of using id(node) is not ideal, since >> id(node) will return the address of the object and that >> can be subject to reuse within the lifetime of the process; >> using a global (thread-safe) counter would be safer > > Good idea. I'm going to start a branch on the repo to > handle the changes you mention. > >> * Graph.__init__ should be able to take a list or set >> of nodes and edges as initializer > > The format of this will need to be thought all the way > through before being implemented. To date, we haven't > come up with anything completely satisfactory, but > AFAIK everybody involved is still open to suggestions > on this. I wasn't thinking of anything clever :-) ... g = Graph( [Node("a"), Node("b"), Node("c")], [Edge(Node("a"), Node("b"), "ab"), Edge(Node("a"), Node("c"), "ac"), Edge(Node("b"), Node("c"), "bc"), ]) The main motivation here is to get lists, sets and dicts play nice together. >> * Graph.__setitem__ could be mapped to .add_node() for >> convenience > > This may be a question of playing around with it. ATM I'm > not sold on the idea, but I'll implement it and see how it > turns out in practice. Thinking about it some more, I agree, it's not all that useful. >> * Graph.__length__ could be mapped to .size() for >> convenience > > We decided not to do this due to the ambiguity between > whether .size() or .order() was the intended operation, > and looking back I'm not sure that was entirely unjustified. > Do you see there being any confusion on that score? There is an ambiguity here, indeed. My thinking was that the edges define the graph and can be mapped to a dictionary, e.g. d = {"ab": ("a", "b"), "ac": ("a", "c"), "bc": ("b", "c")} len(d) == 3 len(g) == 3 A graph without edges is also what you typically call an empty graph, ie. if not g: print 'empty' http://mathworld.wolfram.com/EmptyGraph.html Still, perhaps it's better to just not go down this route. >> * Graph.__iter__ could be mapped to an iterator using >> the fastest traversal method for the graph nodes >> (ie. order does not matter, it's only important that >> all nodes are found as fast as possible) > > Again, it seems ambiguous as to whether nodes or > edges are the intended target here, and while the > API can obviously dictate that, it seems a bit like > a case of "in the face of ambiguity, refuse the > temptation to guess" to me. Right, but sometimes "practicalty beats purity" ;-) We had the same situation for dictionaries and then decided that iteration over keys would be more natural than iterating over items (key, value) or values. It's also important to note that: for n in g: print n and n in g match up in terms of semantics. Since n in g already uses the "node in graph" approach, the for-loop should use the same logic. >> * Graph could also benefit from some bulk update methods, >> e.g. to update weights on all edges or nodes by passing >> in a dictionary mapping names to attribute values > > Sounds good. Again, the format will need some careful > thought, but you're right that this would improve it > greatly. This is only an optimization, but could lead to some great performance improvements by avoiding function call overhead. >> * Graph could benefit from some bulk query methods, >> such as .get_node_attributes() and .add_edges(). > > I'm not sure how the first is different from the existing > .data, what did you have in mind? The second one was a typo. It should have been .get_edge_attributes(). In both cases I was thinking of being able to quickly extract a number of node/edge attributes, e.g. >>> g.get_edge_attributes('weight', 'color') {"ab": {"weight": 3, "color": "blue"}, "ac": {"weight": 2, "color": "green"}, "bc": {"weight": 1, "color": "red"}} Again, the idea is to reduce call overhead and later on be able to move these lookups to C. >> * Node.__getitem__ could be mapped to .data.__getitem__ >> (following the approach taken by ElementTree); same >> for Edge.__getitem__ > >> * Node.__setitem__ could be mapped to .data.__setitem__ >> (following the approach taken by ElementTree); same >> for Edge.__setitem__ > > .data is just a property that returns a dictionary of non > private members right now, so if you're wanting to just say > node.this = 'stuff', you can already do that. Or am I > misreading your intent? Right, but with attributes you are restricted to Python identifiers, e.g. keywords (e.g. "from", "pass") are not allowed. The above approach bypasses this restriction. >> * I'd add a DirectedEdge alias for Edge and a new >> UndirectedEdge as subclass which has is_directed=False; >> makes code more readable > > Sounds good, and thanks for the advice! Thanks, -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Dec 07 2009) >>> 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 our new mxODBC.Connect Python Database Interface 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 http://www.egenix.com/company/contact/ From aioe.org at technicalbloke.com Mon Dec 7 18:30:50 2009 From: aioe.org at technicalbloke.com (r0g) Date: Mon, 07 Dec 2009 23:30:50 +0000 Subject: python proxy checker ,change to threaded version References: Message-ID: Terry Reedy wrote: > r0g wrote: > >> The trick to threads is to create a subclass of threading.Thread, define >> the 'run' function and call the 'start()' method. I find threading quite >> generally useful so I created this simple generic function for running >> things in threads... > > Great idea. Thanks for posting this. > >> def run_in_thread( func, func_args=[], callback=None, callback_args=[] ): >> import threading >> class MyThread ( threading.Thread ): >> def run ( self ): >> >> # Call function >> if function_args: >> result = function(*function_args) >> else: >> result = function() > > The check is not necessary. by design, f(*[]) == f() Excellent, thanks Terry :) I knew it would be simpler than I thought! I've been writing a lot of PHP and AS3 recently and it's easy to forget how python often just works without needing the same level of hand holding, error checking & defensive coding as other languages! > Names do not match param names ;=) Oops yeah! Thought I'd refactor my painfully verbose variable names before posting in a 70 char wide medium but it looks like I missed one! *blush* Roger. From tmohr at s.netic.de Mon Dec 7 18:39:13 2009 From: tmohr at s.netic.de (Torsten Mohr) Date: Tue, 08 Dec 2009 00:39:13 +0100 Subject: test if an input string starts with a python expression Message-ID: Hi, i'd like to test if an input string starts with a python expression and also where that expression ends. An example: a_func(3*7, '''abc''') +5 pls some more The first part until (inclusive) the 5 should be found as an expression and the length of that string should also be detected. Background is that i want to embed some python expressions in a text and i want to evaluate them later. It is possible that the embedded expressions span several lines. Alternatively, is it possible to define a start- and an end-marker that define the embedded expression and find the expression using a regular expression? If the expression contains strings, these strings could contain the end-marker which should not be found inside strings. Example: start: < end: > < some_func(r">")> Can anybody tell me how to do this best? Can i do this using just modules from the python library? Thanks for any hints, Torsten. From aioe.org at technicalbloke.com Mon Dec 7 18:49:04 2009 From: aioe.org at technicalbloke.com (r0g) Date: Mon, 07 Dec 2009 23:49:04 +0000 Subject: python proxy checker ,change to threaded version References: Message-ID: Terry Reedy wrote: > r0g wrote: > >> The trick to threads is to create a subclass of threading.Thread, define >> the 'run' function and call the 'start()' method. I find threading quite >> generally useful so I created this simple generic function for running >> things in threads... > > Great idea. Thanks for posting this. > >> def run_in_thread( func, func_args=[], callback=None, callback_args=[] ): Okay, so here's the more concise version for posterity / future googlers... import threading def run_in_thread( func, func_args=[], callback=None, callback_args=[] ): class MyThread ( threading.Thread ): def run ( self ): result = func(*func_args) if callback: callback(result, *callback_args) MyThread().start() Roger. From aioe.org at technicalbloke.com Mon Dec 7 18:59:28 2009 From: aioe.org at technicalbloke.com (r0g) Date: Mon, 07 Dec 2009 23:59:28 +0000 Subject: python proxy checker ,change to threaded version References: Message-ID: Rhodri James wrote: > On Mon, 07 Dec 2009 18:21:23 -0000, Terry Reedy wrote: > >> r0g wrote: >> >>> The trick to threads is to create a subclass of threading.Thread, define >>> the 'run' function and call the 'start()' method. I find threading quite >>> generally useful so I created this simple generic function for running >>> things in threads... >> >> Great idea. Thanks for posting this. >> >>> def run_in_thread( func, func_args=[], callback=None, >>> callback_args=[] ): > > I'm might wary of having mutable defaults for parameters. They make for > the most annoying errors. Even though they're actually safe here, I'd > still write: > > def run_in_thread(func, func_args=(), callback=None, callback_args=()): > > out of sheer paranoia. > > Excellent point, thanks :) I'm starting to suspect this is the highest quality group in all of usenet! Roger. From zephjc at gmail.com Mon Dec 7 19:10:45 2009 From: zephjc at gmail.com (zeph) Date: Mon, 7 Dec 2009 16:10:45 -0800 (PST) Subject: test if an input string starts with a python expression References: Message-ID: <079b85a7-6be1-4820-82f3-4d4cde7a66b3@u25g2000prh.googlegroups.com> It sort of sounds like you want a templating system: http://wiki.python.org/moin/Templating From aioe.org at technicalbloke.com Mon Dec 7 19:30:03 2009 From: aioe.org at technicalbloke.com (r0g) Date: Tue, 08 Dec 2009 00:30:03 +0000 Subject: question about imports in a class References: <36dec4ff0912071313rc6f95e1g683d851232c388f7@mail.gmail.com> <7o5c23F3o5rkgU1@mid.uni-berlin.de> <7o5eq5F3krihnU1@mid.uni-berlin.de> Message-ID: Diez B. Roggisch wrote: > J schrieb: >> On Mon, Dec 7, 2009 at 16:57, Diez B. Roggisch >> wrote: >> >>>> if I put the import at the beginning of the class, it just dawned on >>>> me that perhaps I still have to explicitly call the function by class: >>>> > I'm not annoyed. I just wonder from what you got the impression that > import statements are something that belongs inside functions - even if > python allows it. > > I don't know of any other language (I don't do ruby & perl) that allows > this, C/C++, java, Pascal, Haskell, ML - all of them declare their > intended use of a library on the beginning of a file. > > You seem to really be really determined to place them everywhere else... > > > > > Diez I have found one good use for using import within functions. I maintain a module of useful miscellaneous python functions I have written over the years, it's quite the hodgepodge though and it's not something I would really want to package and distribute in its entirety, especially as there are many uses of modules outside the standard lib. I use it 'as is' during initial development with each function importing what it needs at the top of the function definition. This doesn't seem to affect performance and even if it did it would only be on my dev box. When it's time to bundle an app for distribution I copy the few functions that are actually used to a new module and refactor it so the imports are all at the top. Having the imports within the functions makes it very easy to keep track of these dependencies so I don't have to sift through a list of 50 different imports, weeding out the ones I don't need whenever I do this. Roger. From withblessings at gmail.com Mon Dec 7 19:59:42 2009 From: withblessings at gmail.com (74yrs old) Date: Tue, 8 Dec 2009 06:29:42 +0530 Subject: Fwd: Request for solution In-Reply-To: <4B1D4903.8010500@acm.org> References: <7b87ecb70912070809x5d9b9853xdc62ed86759bfe78@mail.gmail.com> <4B1D4903.8010500@acm.org> Message-ID: <7b87ecb70912071659v43739710ma291c142cd6994c2@mail.gmail.com> ---------- Forwarded message ---------- From: Sjoerd Mullender Date: Mon, Dec 7, 2009 at 11:57 PM Subject: Re: Request for solution To: 74yrs old Cc: python-list-owner at python.org Please send this to python-list at python.org, not to python-list-owner at python.org. The latter address is only to send messages to the administrator of the mailing list. On 2009-12-07 17:09, 74yrs old wrote: > Hello experts, > For Kannada project .txt(not .doc) is used, my requirement is to have > one space between two characters in Notepad file. In MSword there is > provision to make space between two characters under "Font" and can be > saved as _.doc_ But when tried to save as_ .txt_ all formatting will > disappear. I could not understand how to do in notepad. Even tried copy > and paste from doc to notepad but failed. > > In this context, I request you kindly for small Python program - to make > or insert space between two characters in the _text_ file. (I have > installed Fedora-11 and also ubuntu9.04) > > example: *F o r K a n n a d a p r o j e c t . t x t(n o t .d o c) i > s u s e d, m y r e q u i r e m e n t i s t o h a v e o n e s p > a c e b e t w e e n t w o c h a r a c t e r s i n t h e t e x t.* > *? ??? ? ? ???? ? ?? ?? ?? > With regards, > -sriranga(77yrsold) > * -- Sjoerd Mullender -------------- next part -------------- An HTML attachment was scrubbed... URL: From aioe.org at technicalbloke.com Mon Dec 7 20:22:23 2009 From: aioe.org at technicalbloke.com (r0g) Date: Tue, 08 Dec 2009 01:22:23 +0000 Subject: test if an input string starts with a python expression References: Message-ID: Torsten Mohr wrote: > Hi, > > i'd like to test if an input string starts with a python expression > and also where that expression ends. An example: > > a_func(3*7, '''abc''') +5 pls some more > > The first part until (inclusive) the 5 should be found as an expression > and the length of that string should also be detected. > > > Background is that i want to embed some python expressions in a text > and i want to evaluate them later. > It is possible that the embedded expressions span several lines. > > Alternatively, is it possible to define a start- and an end-marker > that define the embedded expression and find the expression using > a regular expression? That's the easy way and will work for most cases if you use uncommon delimiters. I tend to use '<<<' and '>>>' for things like this but you can make them as obscure as you like. > If the expression contains strings, these strings could contain > the end-marker which should not be found inside strings. You could build in escaping but that complicates things quite quickly, assuming this is for your own private use and you won't be dealing with huge rafts of data from elsewhere or using this to control radiotherapy machines etc, that's probably overkill. The re module should do everything you need and is part of the standard lib. >>> import re >>> regex = re.compile(r'<<<(.{1,500}?)>>>', re.DOTALL) >>> regex.findall("the cat <<>> on the <<>>") ['sat', 'mat'] Hope this helps, Roger. From tsutton125 at gmail.com Mon Dec 7 20:58:18 2009 From: tsutton125 at gmail.com (Taylor) Date: Mon, 7 Dec 2009 17:58:18 -0800 (PST) Subject: Generators. References: <4b1c8cc3$1@dnews.tpgi.com.au> Message-ID: <5c6260a0-cde1-4791-a73c-d299fe38f42d@v25g2000yqk.googlegroups.com> On Dec 7, 1:29?pm, Jorge Cardona wrote: > 2009/12/7 Lie Ryan : > > > > > On 12/7/2009 7:22 AM, Jorge Cardona wrote: > > >> Hi, > > >> I was trying to create a function that receive a generator and return > >> a list but that each elements were computed in a diferent core of my > >> machine. I start using islice function in order to split the job in a > >> way that if there is "n" cores each "i" core will compute the elements > >> i,i+n,i+2n,..., but islice has a weird (to me) behavior, look: > > > it's nothing weird, python just do what you're telling it to: > > > transform all x in X with f(x) > > >> g = (f(x) for x in X) > > > then slice the result of that > > >> print(list(x for x in islice(g,0,None,2))) > > When i wrote that first line of code i thought that i was creating a > generator that will later compute ?the elements of X with function f, > if i will like to transform them immediately i would use [] instead > (), so, the result is not where i want to slice, even so, is exactly > the same to slice, after or before, the only difference is that after > the compute i'm losing 5 in unnecessary execution of the function f. > > > what you want to do is to slice before you transform: > >>>> g = (x for x in islice(X, 0, None, 2)) > >>>> print(list(f(x) for x in g)) > > eval: 0 > > eval: 2 > > eval: 4 > > eval: 6 > > eval: 8 > > [0, 2, 4, 6, 8] > > What i want to do is a function that receive any kind of generator and > execute it in several cores (after a fork) and return the data, so, i > can't slice the set X before create the generator. > > > > >> islice execute the function at the generator and drop the elements > >> that aren't in the slice. I found that pretty weird, the way that i > >> see generators is like an association between and indexing set (an > >> iterator or another generator) and a computation that is made indexed > >> by the indexing set, and islice is like a "transformation" on the > >> indexing set,it doesn't matter the result of the function, the slice > >> should act only on the indexing set, some other "transformation" like > >> takewhile act on the result so, the execution it has to be made, but > >> in the islice, or other "transformation" that act only in the indexing > >> set, the function shouldn't be executed at each element, but only on > >> that new set that result of the application of the "transformation" on > >> the original set. > > > that seems like an extremely lazy evaluation, I don't know if even a true > > lazy language do that. Python is a strict language, with a few laziness > > provided by generators, in the end it's still a strict language. > > Yes, it looks like lazy evaluation, but, i don't see why there is not > a better control over the iterable associated to a generator, even > with Python that is a strict language, it will increase the > functionality of it, and the performance too, imagine that you pass a > function that takes 1 sec in run, and for several reason you can't > slice before (as the smp function that i want to create), the final > performance with the actual islice it gets really reduced > Just creating the separation between those transformation that act on > the index(islice, or tee) on those that act on the result(dropwhile, > takewhile, etc.) the control could be fine enough to increase > usability (that's the way i think right now), and you will be able to > combine generator without lose performance. > > >> Well, it works for what i need, but is not very neat, and i think that > >> there it should be a formal way to act on the base indexing iterator, > >> such way exists? Is there a better approach to get what i need? > > > Reverse your operation. > > -- > >http://mail.python.org/mailman/listinfo/python-list > > -- > Jorge Eduardo Cardona > jorgeecard... at gmail.com > jorgeecardona.blogspot.com > ------------------------------------------------ > Linux registered user ?#391186 > Registered machine ? ?#291871 > ------------------------------------------------ What would you have your islice do for the following generator? def fib(n): a,b=0,1 for x in range(n): a,b=b,a+b yield a In order for some value it yields to be correct, it needs execute all the previous times. If it happens that some of the results aren't used, they are thrown out. As is, using your islice (on, say, fib(10)) gives a KeyError for the key '.0'. Point is, generators don't work that way. You aren't guaranteed to be able to jump around, only to find the next value. If you need to split a particular generator up into parts that can be computed separately, your best bet is probably to rewrite that generator. From withblessings at gmail.com Mon Dec 7 21:54:26 2009 From: withblessings at gmail.com (74yrs old) Date: Tue, 8 Dec 2009 08:24:26 +0530 Subject: Request for solution Message-ID: <7b87ecb70912071854l208aaa44jf35d11b4a1aba5c1@mail.gmail.com> Python experts, Please find attached file "Tesseractindic-Trainer-GUI-0- 1-3.tar.gz for perusal.("if you like to help, I can send you the program off-list") The said tesseractindic-trainer works well in Linux viz Ubuntu-9.04 and fedora-11 without any problem. But when I tried to run in CMD.exe of WinXP it fails. In WinXP, I have already installed Python2.6 and python3.0 as well as GTK under C:\drive. When run c:\GTK> gtk-demo it will open "ApplicationMainwindow." Is it possible to test the said trainer and modified relevant source code accordingly, to run in WinXP successfully - for which I shall be thankful to you. Since I am newbie to python, I am seeking valuable guidance as special case. With regards, -sriranga(77yrsold) -------------- next part -------------- An HTML attachment was scrubbed... URL: From chardster at gmail.com Mon Dec 7 21:56:26 2009 From: chardster at gmail.com (Richard Thomas) Date: Mon, 7 Dec 2009 18:56:26 -0800 (PST) Subject: test if an input string starts with a python expression References: Message-ID: <0334b6e4-6522-4832-8c27-c0a0fbc02381@f16g2000yqm.googlegroups.com> On Dec 8, 1:22?am, r0g wrote: > Torsten Mohr wrote: > > Hi, > > > i'd like to test if an input string starts with a python expression > > and also where that expression ends. ?An example: > > > a_func(3*7, '''abc''') +5 pls some more > > > The first part until (inclusive) the 5 should be found as an expression > > and the length of that string should also be detected. > > > Background is that i want to embed some python expressions in a text > > and i want to evaluate them later. > > It is possible that the embedded expressions span several lines. > > > Alternatively, is it possible to define a start- and an end-marker > > that define the embedded expression and find the expression using > > a regular expression? > > That's the easy way and will work for most cases if you use uncommon > delimiters. I tend to use '<<<' and '>>>' for things like this but you > can make them as obscure as you like. > > > If the expression contains strings, these strings could contain > > the end-marker which should not be found inside strings. > > You could build in escaping but that complicates things quite quickly, > assuming this is for your own private use and you won't be dealing with > huge rafts of data from elsewhere or using this to control radiotherapy > machines etc, that's probably overkill. > > The re module should do everything you need and is part of the standard lib. > > >>> import re > >>> regex = re.compile(r'<<<(.{1,500}?)>>>', re.DOTALL) > >>> regex.findall("the cat <<>> on the <<>>") > > ['sat', 'mat'] > > Hope this helps, > > Roger. Use the parser module. >>> parser.expr('func(a+1)') >>> parser.expr('print a') ... SyntaxError: invalid syntax Quite intensive as you have to compile every initial substring to find the longest one but at least you use Python's own definition of an expression. Chard. From withblessings at gmail.com Mon Dec 7 21:56:58 2009 From: withblessings at gmail.com (74yrs old) Date: Tue, 8 Dec 2009 08:26:58 +0530 Subject: Request for py program to insert space between two characters and saved as text? Message-ID: <7b87ecb70912071856k10ad366du2b07ce92b94e50e3@mail.gmail.com> For Kannada project .txt(not .doc) is used, my requirement is to have one space between two characters in Notepad file. In MSword there is provision to make space between two characters under "Font" and can be saved as *.doc * But when tried to save as* .txt* all formatting will disappear. I could not understand how to do in notepad. Even tried copy and paste from doc to notepad but failed. In this context, I request you kindly for small python program - to make or insert space between two characters in the text file. (I have installed FFedora-11 also ubuntu9.04) example: *F o r K a n n a d a p r o j e c t . t x t(n o t .d o c) i s u s e d, m y r e q u i r e m e n t i s t o h a v e o n e s p a c e b e t w e e n t w o c h a r a c t e r s i n t h e t e x t.* *? ??? ? ? ???? ? ?? ?? ?? * -------------- next part -------------- An HTML attachment was scrubbed... URL: From pfeldman at verizon.net Mon Dec 7 22:07:47 2009 From: pfeldman at verizon.net (Dr. Phillip M. Feldman) Date: Mon, 7 Dec 2009 19:07:47 -0800 (PST) Subject: how to convert string function to string method? In-Reply-To: <4b1cc0e6$0$14670$426a74cc@news.free.fr> References: <26673209.post@talk.nabble.com> <4b1cc0e6$0$14670$426a74cc@news.free.fr> Message-ID: <26688035.post@talk.nabble.com> Bruno- You've made some excellent suggestions, and I'm always grateful for the opportunity to learn. My revised code appears below. Philllip def strip_pairs(s, open='([{\'"', close=')]}\'"'): """ OVERVIEW This function strips matching pairs of characters from the beginning and end of the input string `s`. If `s` begins with a character in `open` and ends with the corresponding character in `close` (see below), both are removed from the string. This process continues until no further matching pairs can be removed. INPUTS `open` and `close`: These arguments, which must be equal-length strings, specify matching start-of-scope and end-of-scope characters. The same character may appear in both `open` and `close`; single and double quotes conventionally match themselves. By default, `open` contains a left parenthesis, left square bracket, left curly bracket, single quote, and double quote), and `close` contains the corresponding characters.""" if not isinstance(s,(str,unicode)): raise TypeError, '`s` must be a string (str or unicode).' if not isinstance(open,(str,unicode)) or not isinstance(close,(str,unicode)): raise TypeError, '`open` and `close` must be strings (str or unicode).' if len(open) != len(close): raise ValueError, \ '\'open\' and \'close\' arguments must be equal-length strings.' while len(s) >= 2: # Check whether first character of `s` is in `open`: i= open.find(s[0]) # If `s` does not begin with a character from `open`, there are no more # pairs to be stripped: if i == -1: break # If `s` does not begin and end with matching characters, there are no # more pairs to be stripped: if s[-1] != close[i]: break # Strip the first and last character from `s`: s= s[1:-1] return s -- View this message in context: http://old.nabble.com/how-to-convert-string-function-to-string-method--tp26673209p26688035.html Sent from the Python - python-list mailing list archive at Nabble.com. From james at agentultra.com Mon Dec 7 22:12:48 2009 From: james at agentultra.com (J Kenneth King) Date: Mon, 07 Dec 2009 22:12:48 -0500 Subject: How decoupled are the Python frameworks? References: <6316c8e5-34a0-43e3-92ad-966d95e84108@j24g2000yqa.googlegroups.com> Message-ID: <85638irwen.fsf@agentultra.com> shocks writes: > Hi > > I'm getting back into Python after a long break. I've been developing > large enterprise apps solely with Adobe Flex (ActionScript) for the > past couple years. During that time I've used a number of 'MVC' > frameworks to glue the bits together - among them Cairngorm, a > modified implementation of Cairngorm using the Presentation Model > pattern, PureMVC, Mate (an IOC container but with an MVC > implementation) and Parsley (IOC but you have to roll-you-own MVC). > During that time I've been in large teams (30 Flex + 30 Java) to small > teams (2 Flex + 1 Java). The motivation of these frameworks is the > decouple your concerns, allowing your apps to be more scalable, easier > to test, and supposedly easier to maintain. Some do the decoupling > better job than others, but there is also the question of "how > decoupled is your code from the framework"? It's all well and good > having something clever working behind the scenes wiring and routing > everything together, but I wonder where this leaves the code base if > the framework, which was selected at the beginning of the project, is > replaced with something else months or years later (i.e. the framework > just doesn't scale as expected, the community involvement dies and > it's no longer maintained properly, etc). I've seen it happen and > I've been experienced the pain of detangling massive amounts of code > which is full of framework specific imports, methods and boilerplate > code. And then there's updating the unit tests! > > My question is how good are the current crop of Python frameworks? > I've used Django twice in production and didn't like that much. The > implementation is Django specific for starters. I've picked up Pylons > and I'm trying that out. I'm not sure how well it fares? I do feel a > bit uneasy about the code generation that some of the Python > frameworks do. Pylons creates something like 20 files for a > 'helloworld'. It does do some great things out of the box, but I > wonder where that leaves your own code. After spending 3-6 months on > your Pylons webapp, how easy is it to move to something else? Maybe > one of the Python IOC once they mature. What are some good techniques > people are using to future (framework) proof their apps? > > I'm interested to hear people experiences with the various frameworks > and how decoupled their code is from them. The best of the current > Flex frameworks for me is Parsley. The only noticeable Parlsey code > is an '[Inject]' meta tag here and there and a couple import > statements. All the complicated object creation and messaging is done > higher up the chain. > > Cheers, > Ben I've stayed away from the Java world at least professionally... but I think I understand where you're getting. I'm not a huge fan of web development. Which is rather counter-intuitive for me to say since it's been the bulk of my work for the past four years. It's because there's no easy way to get around the warts. Websites are one thing but to try and think of these things as "applications" becomes an expensive illusion to maintain. The problem with thinking about these things as applications with an interface, a controller, and a model is: statelessness! Oh also serialization. Getting around these issues are pretty much the raison d'etre for web frameworks. Without them we end up with PHP. As far as swappable Python web frameworks... NONE. AFAIK, they all require some commitment to tying your application to them. However, there are a crop of frameworks that do minimize the pain of such a decision: web.py and bobo are two that I've been working with (though it sounds like cherrypy would be very good at separating dispatching from application code). You could of course write your stuff closer to the "metal" so to speak... WSGI would be about as low as I go. From martin.hellwig at dcuktec.org Mon Dec 7 23:25:28 2009 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Tue, 08 Dec 2009 04:25:28 +0000 Subject: Duplicates of third-party libraries In-Reply-To: <877hsygytc.fsf_-_@benfinney.id.au> References: <877hsygytc.fsf_-_@benfinney.id.au> Message-ID: Ben Finney wrote: > "Martin P. Hellwig" writes: > > Along with the duplication this introduces, it also means that any bug > fixes ? even severe security fixes ? in the third-party code will not be > addressed in your duplicate. I disagree, what you need is: - An automated build system for your deliveries, something you should have anyway - An method of tracking versions of your dependencies, again something you should have anyway - And a policy that you incorporate bug fixes from your dependencies in your deliveries, something you should do anyway if you are serious about your product. -- MPH http://blog.dcuktec.com 'If consumed, best digested with added seasoning to own preference.' From debatem1 at gmail.com Mon Dec 7 23:28:05 2009 From: debatem1 at gmail.com (geremy condra) Date: Mon, 7 Dec 2009 23:28:05 -0500 Subject: Graph library for Python In-Reply-To: <4B1D8FB1.5010703@egenix.com> References: <4B18F685.8050102@egenix.com> <4B1CFA36.9060805@egenix.com> <4B1D35BC.5000002@egenix.com> <4B1D5CB3.8030805@egenix.com> <4B1D8FB1.5010703@egenix.com> Message-ID: On Mon, Dec 7, 2009 at 6:28 PM, M.-A. Lemburg wrote: > geremy condra wrote: >> On Mon, Dec 7, 2009 at 2:51 PM, M.-A. Lemburg wrote: >>> geremy condra wrote: >>>> How interested are you in a C port of graphine? I haven't had >>>> any specific requests for it, but if its something you need I >>>> can shuffle it towards the top of the to do pile. >>> >>> There are two main reasons for a C implementation: >>> >>> ?1. performance >>> >>> ?2. memory footprint >>> >>> These are important when using graphs with lots of nodes or >>> when using lots of graphs or operations on graphs in tight >>> loops. >>> >>> However, to get such a new type into the core, you need to start >>> a PEP process and hash out the API some more, esp. with respect >>> to integration with the other core types, such as dictionaries >>> and lists of tuples for both creation and as alternative >>> representation. >> >> I'm happy to start the PEP process, but will need some >> guidance, as I've never written a PEP before. > > Some pointers to get you started: > > PEPs in general: > http://www.python.org/dev/peps/pep-0001/ > http://www.python.org/dev/peps/pep-0009/ > > Adding modules to the standard lib: > http://www.python.org/dev/peps/pep-0002/ > > (though, in reality, you'd probably only be patching the > collections.py module, I guess) Thanks, I'll go over these a little later. >>> Some other comments (in no particular order): >>> >>> ?* the "name" default of using id(node) is not ideal, since >>> ? id(node) will return the address of the object and that >>> ? can be subject to reuse within the lifetime of the process; >>> ? using a global (thread-safe) counter would be safer >> >> Good idea. I'm going to start a branch on the repo to >> handle the changes you mention. >> >>> ?* Graph.__init__ should be able to take a list or set >>> ? of nodes and edges as initializer >> >> The format of this will need to be thought all the way >> through before being implemented. To date, we haven't >> come up with anything completely satisfactory, but >> AFAIK everybody involved is still open to suggestions >> on this. > > I wasn't thinking of anything clever :-) ... > > g = Graph( > ? ? ?[Node("a"), Node("b"), Node("c")], > ? ? ?[Edge(Node("a"), Node("b"), "ab"), > ? ? ? Edge(Node("a"), Node("c"), "ac"), > ? ? ? Edge(Node("b"), Node("c"), "bc"), > ? ? ?]) > > The main motivation here is to get lists, sets and dicts > play nice together. Generally, we've tried to discourage people from instantiating nodes and edges directly, in favor of having them controlled through the graph. Maybe something along the lines of: g = Graph(nodes=['a', 'b', 'c'], edges=[('a', 'b'), ('a', 'c'), ('b', 'c')]) ? >>> ?* Graph.__setitem__ could be mapped to .add_node() for >>> ? convenience >> >> This may be a question of playing around with it. ATM I'm >> not sold on the idea, but I'll implement it and see how it >> turns out in practice. > > Thinking about it some more, I agree, it's not all that useful. > >>> ?* Graph.__length__ could be mapped to .size() for >>> ? convenience >> >> We decided not to do this due to the ambiguity between >> whether .size() or .order() was the intended operation, >> and looking back I'm not sure that was entirely unjustified. >> Do you see there being any confusion on that score? > > There is an ambiguity here, indeed. My thinking was that > the edges define the graph and can be mapped to a dictionary, > e.g. > > d = {"ab": ("a", "b"), > ? ? "ac": ("a", "c"), > ? ? "bc": ("b", "c")} > > len(d) == 3 > len(g) == 3 > > A graph without edges is also what you typically call an empty > graph, ie. > > if not g: > ? ?print 'empty' > > http://mathworld.wolfram.com/EmptyGraph.html > > Still, perhaps it's better to just not go down this route. I'd rather avoid it if possible, since there are many potential interpretations of this in different contexts. Again, I'm open to to the idea, but not convinced. >>> ?* Graph.__iter__ could be mapped to an iterator using >>> ? the fastest traversal method for the graph nodes >>> ? (ie. order does not matter, it's only important that >>> ? all nodes are found as fast as possible) >> >> Again, it seems ambiguous as to whether nodes or >> edges are the intended target here, and while the >> API can obviously dictate that, it seems a bit like >> a case of "in the face of ambiguity, refuse the >> temptation to guess" to me. > > Right, but sometimes "practicalty beats purity" ;-) We had > the same situation for dictionaries and then decided that > iteration over keys would be more natural than iterating over > items (key, value) or values. > > It's also important to note that: > > ? ? ? ?for n in g: print n > > and > > ? ? ? ?n in g > > match up in terms of semantics. > > Since n in g already uses the "node in graph" approach, > the for-loop should use the same logic. Beware, that doesn't just match nodes. g = Graph() g.add_node('a') g.add_node('b') g.add_edge('a', 'b', 'ab') 'ab' in g # returns true >>> ?* Graph could also benefit from some bulk update methods, >>> ? e.g. to update weights on all edges or nodes by passing >>> ? in a dictionary mapping names to attribute values >> >> Sounds good. Again, the format will need some careful >> thought, but you're right that this would improve it >> greatly. > > This is only an optimization, but could lead to some great > performance improvements by avoiding function call overhead. Agreed. >>> ?* Graph could benefit from some bulk query methods, >>> ? such as .get_node_attributes() and .add_edges(). >> >> I'm not sure how the first is different from the existing >> .data, what did you have in mind? > > The second one was a typo. It should have been > .get_edge_attributes(). > > In both cases I was thinking of being able to quickly > extract a number of node/edge attributes, e.g. > >>>> g.get_edge_attributes('weight', 'color') > {"ab": {"weight": 3, "color": "blue"}, > ?"ac": {"weight": 2, "color": "green"}, > ?"bc": {"weight": 1, "color": "red"}} > > Again, the idea is to reduce call overhead and later > on be able to move these lookups to C. Entirely doable, but I'm not sure I see the use case. Would you mind providing a more realistic example? >>> ?* Node.__getitem__ could be mapped to .data.__getitem__ >>> ? (following the approach taken by ElementTree); same >>> ? for Edge.__getitem__ >> >>> ?* Node.__setitem__ could be mapped to .data.__setitem__ >>> ? (following the approach taken by ElementTree); same >>> ? for Edge.__setitem__ >> >> .data is just a property that returns a dictionary of non >> private members right now, so if you're wanting to just say >> node.this = 'stuff', you can already do that. Or am I >> misreading your intent? > > Right, but with attributes you are restricted to Python > identifiers, e.g. keywords (e.g. "from", "pass") are not allowed. > The above approach bypasses this restriction. Hmm. Sounds like a plausible use case to me, although I'm not sure its one that should be encouraged. The bigger question in my mind is whether all attribute lookups should have to pay the extra lookup cost to support a somewhat narrow need. I'll definitely have to talk with the other devs about this one, and run a little bit of timing besides. Geremy Condra From ben+python at benfinney.id.au Tue Dec 8 00:09:17 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Tue, 08 Dec 2009 16:09:17 +1100 Subject: Duplicates of third-party libraries References: <877hsygytc.fsf_-_@benfinney.id.au> Message-ID: <87tyw2f3wi.fsf@benfinney.id.au> "Martin P. Hellwig" writes: > Ben Finney wrote: > > Along with the duplication this introduces, it also means that any bug > > fixes ? even severe security fixes ? in the third-party code will not be > > addressed in your duplicate. > I disagree, what you need is: > - An automated build system for your deliveries, something you should > have anyway > - An method of tracking versions of your dependencies, again something > you should have anyway Those are orthogonal issues. They're good practice, but don't address the problem I'm describing. > - And a policy that you incorporate bug fixes from your dependencies > in your deliveries, something you should do anyway if you are serious > about your product. This omits the heart of the problem: There is an extra delay between release and propagation of the security fix. When the third-party code is released with a security fix, and is available in the operating system, the duplicate in your application will not gain the advantage of that fix until you release a new version of your application *and* that new version makes its way onto the affected computer. That is an additional delay, that only occurs because the hypothetical security bug exists in a duplicate copy of the third party code. That delay is entirely eradicated if your application instead uses a system-installed library; your application then gains the security fix immediately when they upgrade the system-installed library, without the user having to upgrade the application at all. -- \ ?I took it easy today. I just pretty much layed around in my | `\ underwear all day. ? Got kicked out of quite a few places, | _o__) though.? ?Bug-Eyed Earl, _Red Meat_ | Ben Finney From martin.hellwig at dcuktec.org Tue Dec 8 02:20:58 2009 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Tue, 08 Dec 2009 07:20:58 +0000 Subject: Duplicates of third-party libraries In-Reply-To: <87tyw2f3wi.fsf@benfinney.id.au> References: <877hsygytc.fsf_-_@benfinney.id.au> <87tyw2f3wi.fsf@benfinney.id.au> Message-ID: Ben Finney wrote: > This omits the heart of the problem: There is an extra delay between > release and propagation of the security fix. When the third-party code > is released with a security fix, and is available in the operating > system, the duplicate in your application will not gain the advantage of > that fix until you release a new version of your application *and* that > new version makes its way onto the affected computer. > > That is an additional delay, that only occurs because the hypothetical > security bug exists in a duplicate copy of the third party code. That > delay is entirely eradicated if your application instead uses a > system-installed library; your application then gains the security fix > immediately when they upgrade the system-installed library, without the > user having to upgrade the application at all. > I fully agree with your reasoning and I think you raised a valid point. However, for me (as in YMMV), I have observed the following behaviour: - Distribution security fixes are time wise at best on-par with my releases. - Although some distribution (like ubuntu) offer updates on third party dependencies (like the Python interpreter), most of them don't (windows). - A user is more likely to update a program he uses than a third party dependency he doesn't think he uses, especially if that program has an auto-update feature and the dependency doesn't. - In the ideal world, a upgrade of a dependency won't break your program, in reality users fear upgrading dependencies because they don't know for sure it won't result in a dll hell type of problem. With these observations in mind and that it gives me more control on what I am delivering, I made the trade off that I send platform specific fully self contained (as far as possible) executables. But you are right that it does give me the obligation to provide a way to the customer to get updates ASAP if there is a security issue in my program, whether this comes originally from a third party library or not is in the users perspective, rightfully so, beside the point. -- MPH http://blog.dcuktec.com 'If consumed, best digested with added seasoning to own preference.' From lie.1296 at gmail.com Tue Dec 8 02:51:45 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Tue, 08 Dec 2009 18:51:45 +1100 Subject: Generators. In-Reply-To: References: <4b1c8cc3$1@dnews.tpgi.com.au> Message-ID: <4b1e0617@dnews.tpgi.com.au> First, I apologize for rearranging your message out of order. On 12/8/2009 5:29 AM, Jorge Cardona wrote: >>> islice execute the function at the generator and drop the elements >>> that aren't in the slice. I found that pretty weird, the way that i >>> see generators is like an association between and indexing set (an >>> iterator or another generator) and a computation that is made indexed >>> by the indexing set, and islice is like a "transformation" on the >>> indexing set,it doesn't matter the result of the function, the slice >>> should act only on the indexing set, some other "transformation" like >>> takewhile act on the result so, the execution it has to be made, but >>> in the islice, or other "transformation" that act only in the indexing >>> set, the function shouldn't be executed at each element, but only on >>> that new set that result of the application of the "transformation" on >>> the original set. >> >> that seems like an extremely lazy evaluation, I don't know if even a true >> lazy language do that. Python is a strict language, with a few laziness >> provided by generators, in the end it's still a strict language. >> > > Yes, it looks like lazy evaluation, but, i don't see why there is not > a better control over the iterable associated to a generator, even > with Python that is a strict language, it will increase the > functionality of it, and the performance too, imagine that you pass a > function that takes 1 sec in run, and for several reason you can't > slice before (as the smp function that i want to create), the final > performance with the actual islice it gets really reduced > Just creating the separation between those transformation that act on > the index(islice, or tee) on those that act on the result(dropwhile, > takewhile, etc.) the control could be fine enough to increase > usability (that's the way i think right now), and you will be able to > combine generator without lose performance. Theoretically yes, but the semantic of generators in python is they work on an Iterable (i.e. objects that have __iter__), instead of a Sequence (i.e. objects that have __getitem__). That means semantically, generators would call obj.__iter__() and call the iter.__next__() and do its operation for each items returned by the iterator's iterable's __next__(). The lazy semantic would be hard to fit the current generator model without changing the semantics of generator to require a Sequence that supports indexing. > Yes, it looks like lazy evaluation, but, i don't see why there is not > a better control over the iterable associated to a generator, even > with Python that is a strict language You can control the laziness by making it explicitly lazy: from functools import partial def f(x): print("eval: %d"%x) return x X = range(10) g = (partial(f, x) for x in X) print(list(x() for x in islice(g,0,None,2))) # # or without partial: # g = ((lambda: f(x)) for x in X) # print(list(f() for f in islice(g,0,None,2))) In a default-strict language, you have to explicitly say if you want lazy execution. > What i want to do is a function that receive any kind of generator and > execute it in several cores (after a fork) and return the data, so, i > can't slice the set X before create the generator. beware that a generator's contract is to return a valid iterator *once* only. You can use itertools.tee() to create more generators, but tee built a list of the results internally. From gh at ghaering.de Tue Dec 8 03:04:22 2009 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Tue, 08 Dec 2009 09:04:22 +0100 Subject: Why Doesn't XP Pro Show Size, Time and Date Mod of a Created File? In-Reply-To: References: Message-ID: W. eWatson wrote: > I created a folder, and wrote a file to it. When I look at what files > are in it, they are correct. However, The Size, Type, and Date Mod are > not shown. Why am I missing those columns? I'm writing files with a > suffix of dat, which seem only to match up with video CD movie. That's probably a Windows Explorer thing. The column may be hidden or moved away to the far right. As far as Python is concerned, you can fetch this kind of information with the stat() function of the os module. import os, time stat_info = os.stat("x") print "size:", stat_info.st_size print "modification time:", time.strftime("%Y-%m-%d %H:%M", time.localtime(stat_info.st_mtime)) -- Gerhard From debatem1 at gmail.com Tue Dec 8 03:06:29 2009 From: debatem1 at gmail.com (geremy condra) Date: Tue, 8 Dec 2009 03:06:29 -0500 Subject: Graph library for Python In-Reply-To: References: <4B1CFA36.9060805@egenix.com> <4B1D35BC.5000002@egenix.com> <4B1D5CB3.8030805@egenix.com> <4B1D8FB1.5010703@egenix.com> Message-ID: On Mon, Dec 7, 2009 at 11:28 PM, geremy condra wrote: > On Mon, Dec 7, 2009 at 6:28 PM, M.-A. Lemburg wrote: >> geremy condra wrote: >>> On Mon, Dec 7, 2009 at 2:51 PM, M.-A. Lemburg wrote: >>>> geremy condra wrote: >>>>> How interested are you in a C port of graphine? I haven't had >>>>> any specific requests for it, but if its something you need I >>>>> can shuffle it towards the top of the to do pile. >>>> >>>> There are two main reasons for a C implementation: >>>> >>>> ?1. performance >>>> >>>> ?2. memory footprint >>>> >>>> These are important when using graphs with lots of nodes or >>>> when using lots of graphs or operations on graphs in tight >>>> loops. >>>> >>>> However, to get such a new type into the core, you need to start >>>> a PEP process and hash out the API some more, esp. with respect >>>> to integration with the other core types, such as dictionaries >>>> and lists of tuples for both creation and as alternative >>>> representation. >>> >>> I'm happy to start the PEP process, but will need some >>> guidance, as I've never written a PEP before. >> >> Some pointers to get you started: >> >> PEPs in general: >> http://www.python.org/dev/peps/pep-0001/ >> http://www.python.org/dev/peps/pep-0009/ >> >> Adding modules to the standard lib: >> http://www.python.org/dev/peps/pep-0002/ >> >> (though, in reality, you'd probably only be patching the >> collections.py module, I guess) > > Thanks, I'll go over these a little later. > >>>> Some other comments (in no particular order): >>>> >>>> ?* the "name" default of using id(node) is not ideal, since >>>> ? id(node) will return the address of the object and that >>>> ? can be subject to reuse within the lifetime of the process; >>>> ? using a global (thread-safe) counter would be safer >>> >>> Good idea. I'm going to start a branch on the repo to >>> handle the changes you mention. >>> >>>> ?* Graph.__init__ should be able to take a list or set >>>> ? of nodes and edges as initializer >>> >>> The format of this will need to be thought all the way >>> through before being implemented. To date, we haven't >>> come up with anything completely satisfactory, but >>> AFAIK everybody involved is still open to suggestions >>> on this. >> >> I wasn't thinking of anything clever :-) ... >> >> g = Graph( >> ? ? ?[Node("a"), Node("b"), Node("c")], >> ? ? ?[Edge(Node("a"), Node("b"), "ab"), >> ? ? ? Edge(Node("a"), Node("c"), "ac"), >> ? ? ? Edge(Node("b"), Node("c"), "bc"), >> ? ? ?]) >> >> The main motivation here is to get lists, sets and dicts >> play nice together. > > Generally, we've tried to discourage people from instantiating > nodes and edges directly, in favor of having them controlled > through the graph. Maybe something along the lines of: > > g = Graph(nodes=['a', 'b', 'c'], edges=[('a', 'b'), ('a', 'c'), ('b', 'c')]) > > ? > >>>> ?* Graph.__setitem__ could be mapped to .add_node() for >>>> ? convenience >>> >>> This may be a question of playing around with it. ATM I'm >>> not sold on the idea, but I'll implement it and see how it >>> turns out in practice. >> >> Thinking about it some more, I agree, it's not all that useful. >> >>>> ?* Graph.__length__ could be mapped to .size() for >>>> ? convenience >>> >>> We decided not to do this due to the ambiguity between >>> whether .size() or .order() was the intended operation, >>> and looking back I'm not sure that was entirely unjustified. >>> Do you see there being any confusion on that score? >> >> There is an ambiguity here, indeed. My thinking was that >> the edges define the graph and can be mapped to a dictionary, >> e.g. >> >> d = {"ab": ("a", "b"), >> ? ? "ac": ("a", "c"), >> ? ? "bc": ("b", "c")} >> >> len(d) == 3 >> len(g) == 3 >> >> A graph without edges is also what you typically call an empty >> graph, ie. >> >> if not g: >> ? ?print 'empty' >> >> http://mathworld.wolfram.com/EmptyGraph.html >> >> Still, perhaps it's better to just not go down this route. > > I'd rather avoid it if possible, since there are many > potential interpretations of this in different contexts. > Again, I'm open to to the idea, but not convinced. > >>>> ?* Graph.__iter__ could be mapped to an iterator using >>>> ? the fastest traversal method for the graph nodes >>>> ? (ie. order does not matter, it's only important that >>>> ? all nodes are found as fast as possible) >>> >>> Again, it seems ambiguous as to whether nodes or >>> edges are the intended target here, and while the >>> API can obviously dictate that, it seems a bit like >>> a case of "in the face of ambiguity, refuse the >>> temptation to guess" to me. >> >> Right, but sometimes "practicalty beats purity" ;-) We had >> the same situation for dictionaries and then decided that >> iteration over keys would be more natural than iterating over >> items (key, value) or values. >> >> It's also important to note that: >> >> ? ? ? ?for n in g: print n >> >> and >> >> ? ? ? ?n in g >> >> match up in terms of semantics. >> >> Since n in g already uses the "node in graph" approach, >> the for-loop should use the same logic. > > Beware, that doesn't just match nodes. > > g = Graph() > g.add_node('a') > g.add_node('b') > g.add_edge('a', 'b', 'ab') > 'ab' in g # returns true > >>>> ?* Graph could also benefit from some bulk update methods, >>>> ? e.g. to update weights on all edges or nodes by passing >>>> ? in a dictionary mapping names to attribute values >>> >>> Sounds good. Again, the format will need some careful >>> thought, but you're right that this would improve it >>> greatly. >> >> This is only an optimization, but could lead to some great >> performance improvements by avoiding function call overhead. > > Agreed. > >>>> ?* Graph could benefit from some bulk query methods, >>>> ? such as .get_node_attributes() and .add_edges(). >>> >>> I'm not sure how the first is different from the existing >>> .data, what did you have in mind? >> >> The second one was a typo. It should have been >> .get_edge_attributes(). >> >> In both cases I was thinking of being able to quickly >> extract a number of node/edge attributes, e.g. >> >>>>> g.get_edge_attributes('weight', 'color') >> {"ab": {"weight": 3, "color": "blue"}, >> ?"ac": {"weight": 2, "color": "green"}, >> ?"bc": {"weight": 1, "color": "red"}} >> >> Again, the idea is to reduce call overhead and later >> on be able to move these lookups to C. > > Entirely doable, but I'm not sure I see the use case. > Would you mind providing a more realistic example? > >>>> ?* Node.__getitem__ could be mapped to .data.__getitem__ >>>> ? (following the approach taken by ElementTree); same >>>> ? for Edge.__getitem__ >>> >>>> ?* Node.__setitem__ could be mapped to .data.__setitem__ >>>> ? (following the approach taken by ElementTree); same >>>> ? for Edge.__setitem__ >>> >>> .data is just a property that returns a dictionary of non >>> private members right now, so if you're wanting to just say >>> node.this = 'stuff', you can already do that. Or am I >>> misreading your intent? >> >> Right, but with attributes you are restricted to Python >> identifiers, e.g. keywords (e.g. "from", "pass") are not allowed. >> The above approach bypasses this restriction. > > Hmm. Sounds like a plausible use case to me, although I'm > not sure its one that should be encouraged. The bigger > question in my mind is whether all attribute lookups should > have to pay the extra lookup cost to support a somewhat > narrow need. I'll definitely have to talk with the other devs > about this one, and run a little bit of timing besides. > > Geremy Condra > Just as a note, I've made some of the changes we've been talking about in a new branch over at graphine.org. Geremy Condra From sjmachin at lexicon.net Tue Dec 8 03:49:16 2009 From: sjmachin at lexicon.net (John Machin) Date: Tue, 8 Dec 2009 00:49:16 -0800 (PST) Subject: Request for py program to insert space between two characters and saved as text? References: <7b87ecb70912071856k10ad366du2b07ce92b94e50e3@mail.gmail.com> Message-ID: <79f477fa-770b-417d-89ee-445c9c9cc6ef@a10g2000pre.googlegroups.com> On Dec 8, 6:56?pm, Dennis Lee Bieber wrote: > On Tue, 8 Dec 2009 08:26:58 +0530, 74yrs old > declaimed the following in gmane.comp.python.general: > > > For Kannada project .txt(not .doc) is used, my requirement is to have one > > space between two characters in Notepad file. ?In MSword there is provision > > to make space between two characters under "Font" and ?can be saved as *.doc > > * ?But when tried to save as* .txt* ?all formatting will disappear. I could > > not understand how to do in notepad. Even tried copy and paste from doc to > > notepad but failed. > > > In this context, I request you kindly for small python program - to make or > > ? ? ? ? Excuse me -- you want one of US to supply you with a program that > will be used for YOUR entry to some job site? (At least, that's what I > seem to be finding for "Kannada project") http://en.wikipedia.org/wiki/Kannada_script I think "project" means any piece of software ... > > > insert space between two characters in the text file. > > ? ? ? ? How difficult is it to read a file character by character, and write > a file containing that character and a space? Perhaps there are some subtleties of which we are unaware ... I would be very surprised if the OP could not find on a forum much closer to home more people who know more about using Indic scripts on computers than here. From wadienil at gmail.com Tue Dec 8 04:26:00 2009 From: wadienil at gmail.com (wadi wadi) Date: Tue, 8 Dec 2009 09:26:00 +0000 Subject: whitespace in xml output Message-ID: <3282bd0c0912080126y3ebd70bejb80e9924d82879cb@mail.gmail.com> Hi all, I am creating some xml output using minidom and saving it to a file using doc.writexml() The output however is as follows: bill catman Is there a way to save xml output in a file such as xml is formatted the right way? I mean with the right indentation and the elements values with no white spaces? bill catman Thanks for your help. WN From bruno.42.desthuilliers at websiteburo.invalid Tue Dec 8 04:42:27 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 08 Dec 2009 10:42:27 +0100 Subject: how to convert string function to string method? In-Reply-To: References: <26673209.post@talk.nabble.com> <4b1cc0e6$0$14670$426a74cc@news.free.fr> Message-ID: <4b1e1f83$0$11557$426a34cc@news.free.fr> Dr. Phillip M. Feldman a ?crit : > Bruno- You've made some excellent suggestions, and I'm always grateful for > the opportunity to learn. Glad to know I've been of any help !-) > My revised code appears below. Philllip > > def strip_pairs(s, open='([{\'"', close=')]}\'"'): > """ > OVERVIEW > > This function strips matching pairs of characters from the beginning and > end of the input string `s`. If `s` begins with a character in `open` > and > ends with the corresponding character in `close` (see below), both are > removed from the string. This process continues until no further matching > pairs can be removed. > > INPUTS > > `open` and `close`: These arguments, which must be equal-length strings, > specify matching start-of-scope and end-of-scope characters. The same > character may appear in both `open` and `close`; single and double quotes > conventionally match themselves. By default, `open` contains a left > parenthesis, left square bracket, left curly bracket, single quote, and > double quote), and `close` contains the corresponding characters.""" > > if not isinstance(s,(str,unicode)): > raise TypeError, '`s` must be a string (str or unicode).' Might be a bit more helpful (for the programmer using your function) to specify what 's' actually is. Also, the recommanded way to raise exceptions is to use the 'call' syntax, ie: if not isinstance(s,(str,unicode)): raise TypeError("'s' must be a str or unicode, got '%s'" % type(s)) > if not isinstance(open,(str,unicode)) or not > isinstance(close,(str,unicode)): > raise TypeError, '`open` and `close` must be strings (str or > unicode).' Mmmm.... I still wonder why you wouldn't accept a tuple or list of chars here. > if len(open) != len(close): raise ValueError, \ > '\'open\' and \'close\' arguments must be equal-length strings.' > > while len(s) >= 2: > > # Check whether first character of `s` is in `open`: > i= open.find(s[0]) > > # If `s` does not begin with a character from `open`, there are no > more > # pairs to be stripped: > if i == -1: break wrt/ readability, it might be better to put the break statement on it's own line - but you can probably count this one as more of a personnal preference than a guideline !-) > # If `s` does not begin and end with matching characters, there are no > # more pairs to be stripped: > if s[-1] != close[i]: break > > # Strip the first and last character from `s`: > s= s[1:-1] > return s Steven (D'Aprano) posted a possibly interesting implementation. Might be worth timeit'ing both. From steve at holdenweb.net Tue Dec 8 05:02:53 2009 From: steve at holdenweb.net (Steve Holden) Date: Tue, 08 Dec 2009 05:02:53 -0500 Subject: Upcoming Python Classes in New York Message-ID: <4B1E244D.1050608@holdenweb.net> Holden Web is pleased to announce three upcoming classes in New York city the week of January 18. Jan 18-20 Introduction to Python (3 days) - Steve Holden http://holdenweb.com/py/introclass/ Jan 21 .NET: IronPython from the Ground Up (1 day) - Michael Foord http://holdenweb.com/py/ironpython/ Jan 22 Practical Django Skills (1 day) - Jacob Kaplan-Moss http://holdenweb.com/py/practicaldjango/ Our current course offerings are always listed at http:/holdenweb.com/py/training/ We also present on-site and/or custom classes - please contact us for further information. regards Steve From lutz.horn at fastmail.fm Tue Dec 8 05:05:04 2009 From: lutz.horn at fastmail.fm (Lutz Horn) Date: Tue, 8 Dec 2009 10:05:04 +0000 (UTC) Subject: whitespace in xml output References: Message-ID: Hi, wadi wadi wrote: > I am creating some xml output using minidom and saving it to a file > using doc.writexml() Could you please add some code of *how* you add the content "bill catman" to the "Author" element? It seems as if whitespace is an issue here. Lutz From msc at es.aau.dk Tue Dec 8 05:11:52 2009 From: msc at es.aau.dk (Martin Sand Christensen) Date: Tue, 08 Dec 2009 11:11:52 +0100 Subject: How decoupled are the Python frameworks? References: <6316c8e5-34a0-43e3-92ad-966d95e84108@j24g2000yqa.googlegroups.com> <85638irwen.fsf@agentultra.com> Message-ID: J Kenneth King writes: > [...] (though it sounds like cherrypy would be very good at separating > dispatching from application code). True. In CherryPy, each page is represented by one method (the 'default' method is an exception, but that's not for this discussion). This method is expected to return a string representing the page/resource that the user requested. At this simple level, CherryPy can be considered more or less just a HTTP server and dispatcher. However, we all know that this isn't where it ends. When we want to handle cookies, we need framework-specific code. When we want to return something other than HTML, we need framework-specific code. The list goes on. However, with a reasonable coding style, it can be quite practical to separate strict application code from the framework-specific code. Here the one-method,-one-page principle is a great help. For instance, we quite often use decorators for such things as authentication and role checking, which is both very practical and technically elegant. For instance, if a user must have a CAS single sign-on identity AND, say, the administrator role, we'd do as follows: @cas @role('administrator') def protectedpage(self, ...): # stuff If the user isn't currently signed in to our CAS, he'll be redirected to the sign-in page and, after signing in, is returned to the page he originally requested. The role decorator checks his privileges (based on his CAS credentials) and either allows or denies him access. This adds up to a LOT of framework-specific code that's been very easily factored out. The CAS and role modules behind the decorators are, in turn, generic frameworks that we've merely specialised for CherryPy. At some point we'll get around to releasing some code. :-) As a slight aside, allow me to recommend Meld3 as a good templating library. It's basically ElementTree with a lot of practical templating stuff on top, so it's not a mini-language unto itself, and you don't embed your code in the page. -- Martin Sand Christensen IT Services, Dept. of Electronic Systems From steve at lonetwin.net Tue Dec 8 05:42:25 2009 From: steve at lonetwin.net (steve) Date: Tue, 08 Dec 2009 16:12:25 +0530 Subject: Request for py program to insert space between two characters and saved as text? In-Reply-To: <79f477fa-770b-417d-89ee-445c9c9cc6ef@a10g2000pre.googlegroups.com> References: <7b87ecb70912071856k10ad366du2b07ce92b94e50e3@mail.gmail.com> <79f477fa-770b-417d-89ee-445c9c9cc6ef@a10g2000pre.googlegroups.com> Message-ID: <4B1E2D91.2000005@lonetwin.net> On 12/08/2009 02:19 PM, John Machin wrote: >> [...snip...] > Perhaps there are some subtleties of which we are unaware ... > > I would be very surprised if the OP could not find on a forum much > closer to home more people who know more about using Indic scripts on > computers than here. That's true. I'd recommend that the original poster, posts the query at the bangalore python user group mailing list: http://mail.python.org/mailman/listinfo/bangpypers ...alongwith some additional details of the requirements. I am sure they wouldn't mind reading and replying to the question in kannada itself. After all Kannada is the language of the sate of Karnataka, of which Bangalore (or Bengaluru as it is known these days) is the capital city. cheers, - steve -- random non tech spiel: http://lonetwin.blogspot.com/ tech randomness: http://lonehacks.blogspot.com/ what i'm stumbling into: http://lonetwin.stumbleupon.com/ From withblessings at gmail.com Tue Dec 8 06:02:10 2009 From: withblessings at gmail.com (74yrs old) Date: Tue, 8 Dec 2009 16:32:10 +0530 Subject: Request for py program to insert space between two characters and saved as text? In-Reply-To: <4B1E2D91.2000005@lonetwin.net> References: <7b87ecb70912071856k10ad366du2b07ce92b94e50e3@mail.gmail.com> <79f477fa-770b-417d-89ee-445c9c9cc6ef@a10g2000pre.googlegroups.com> <4B1E2D91.2000005@lonetwin.net> Message-ID: <7b87ecb70912080302h3c626fbaw31c135b09155d3e5@mail.gmail.com> Steve, Thanks for the recommendation. In fact, I was not aware of Bangalore Python User Group till I received your email. I am very much thankful to you Sir, With Regards, -sriranga(77yrsold) On Tue, Dec 8, 2009 at 4:12 PM, steve wrote: > > On 12/08/2009 02:19 PM, John Machin wrote: > >> [...snip...] >>> >> Perhaps there are some subtleties of which we are unaware ... >> >> I would be very surprised if the OP could not find on a forum much >> closer to home more people who know more about using Indic scripts on >> computers than here. >> > > That's true. I'd recommend that the original poster, posts the query at the > bangalore python user group mailing list: > > http://mail.python.org/mailman/listinfo/bangpypers > > ...alongwith some additional details of the requirements. I am sure they > wouldn't mind reading and replying to the question in kannada itself. > > After all Kannada is the language of the sate of Karnataka, of which > Bangalore (or Bengaluru as it is known these days) is the capital city. > > cheers, > - steve > -- > random non tech spiel: http://lonetwin.blogspot.com/ > tech randomness: http://lonehacks.blogspot.com/ > what i'm stumbling into: http://lonetwin.stumbleupon.com/ > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From lie.1296 at gmail.com Tue Dec 8 06:09:37 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Tue, 08 Dec 2009 22:09:37 +1100 Subject: How decoupled are the Python frameworks? In-Reply-To: References: <6316c8e5-34a0-43e3-92ad-966d95e84108@j24g2000yqa.googlegroups.com> <85638irwen.fsf@agentultra.com> Message-ID: <4b1e3477$1@dnews.tpgi.com.au> On 12/8/2009 9:11 PM, Martin Sand Christensen wrote: > If the user isn't currently signed in to our CAS, he'll be redirected to > the sign-in page and, after signing in, is returned to the page he > originally requested. The role decorator checks his privileges (based on > his CAS credentials) and either allows or denies him access. This adds > up to a LOT of framework-specific code that's been very easily factored > out. The CAS and role modules behind the decorators are, in turn, > generic frameworks that we've merely specialised for CherryPy. At some > point we'll get around to releasing some code. :-) In the end, it is the developer's responsibility not to write something too tightly coupled with their framework, isn't it? (or at least to minimize the framework-specific code to a certain area) From deets at nospam.web.de Tue Dec 8 06:19:32 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 08 Dec 2009 12:19:32 +0100 Subject: How decoupled are the Python frameworks? References: <6316c8e5-34a0-43e3-92ad-966d95e84108@j24g2000yqa.googlegroups.com> Message-ID: <7o6r24F3oruumU1@mid.uni-berlin.de> shocks wrote: > Hi > > I'm getting back into Python after a long break. I've been developing > large enterprise apps solely with Adobe Flex (ActionScript) for the > past couple years. During that time I've used a number of 'MVC' > frameworks to glue the bits together - among them Cairngorm, a > modified implementation of Cairngorm using the Presentation Model > pattern, PureMVC, Mate (an IOC container but with an MVC > implementation) and Parsley (IOC but you have to roll-you-own MVC). > During that time I've been in large teams (30 Flex + 30 Java) to small > teams (2 Flex + 1 Java). The motivation of these frameworks is the > decouple your concerns, allowing your apps to be more scalable, easier > to test, and supposedly easier to maintain. Some do the decoupling > better job than others, but there is also the question of "how > decoupled is your code from the framework"? It's all well and good > having something clever working behind the scenes wiring and routing > everything together, but I wonder where this leaves the code base if > the framework, which was selected at the beginning of the project, is > replaced with something else months or years later (i.e. the framework > just doesn't scale as expected, the community involvement dies and > it's no longer maintained properly, etc). I've seen it happen and > I've been experienced the pain of detangling massive amounts of code > which is full of framework specific imports, methods and boilerplate > code. And then there's updating the unit tests! > > My question is how good are the current crop of Python frameworks? > I've used Django twice in production and didn't like that much. The > implementation is Django specific for starters. I've picked up Pylons > and I'm trying that out. I'm not sure how well it fares? I do feel a > bit uneasy about the code generation that some of the Python > frameworks do. Pylons creates something like 20 files for a > 'helloworld'. It does do some great things out of the box, but I > wonder where that leaves your own code. After spending 3-6 months on > your Pylons webapp, how easy is it to move to something else? Maybe > one of the Python IOC once they mature. What are some good techniques > people are using to future (framework) proof their apps? > > I'm interested to hear people experiences with the various frameworks > and how decoupled their code is from them. The best of the current > Flex frameworks for me is Parsley. The only noticeable Parlsey code > is an '[Inject]' meta tag here and there and a couple import > statements. All the complicated object creation and messaging is done > higher up the chain. I think the Pylons and maybe even TurboGears2 stack are pretty good regarding decoupling. This stems from them bundling "best-of-breed" solutions for e.g. ORM (SQLAlchemy), session-handling, HTML-widgets, templating and so forth together. So in theory, and to a large extend in practice, you can rip out individual components and replace them with ones you prefer, and of course this overall design makes things more decoupled. *However* there is only so much a framework can and does do when it's supposed to stay out of your way. I for one think that e.g. the repoze.who/what stack is an example of an over-generalization that leads to much more hassle than it's worth it, all for the alledged advantages of total decoupling and pluggability. Mark Christensen wrote a blog-post about the whole coupling/de-coupling issue: http://compoundthinking.com/blog/index.php/2009/11/28/coupling-django-style/ Essentially, getting things *done* now is very important, and making developers permanently jump through hoops just so they avoid coupling leads eventually to something that is your own webframework - without the benefit of participating on evolution of a common one that occasionally forces you to adapt. Diez From msc at es.aau.dk Tue Dec 8 06:50:24 2009 From: msc at es.aau.dk (Martin Sand Christensen) Date: Tue, 08 Dec 2009 12:50:24 +0100 Subject: How decoupled are the Python frameworks? References: <6316c8e5-34a0-43e3-92ad-966d95e84108@j24g2000yqa.googlegroups.com> <85638irwen.fsf@agentultra.com> <4b1e3477$1@dnews.tpgi.com.au> Message-ID: Lie Ryan writes: > In the end, it is the developer's responsibility not to write > something too tightly coupled with their framework, isn't it? (or at > least to minimize the framework-specific code to a certain area) That's a good summary of my point. However, I have very little experience with other frameworks than CherryPy, so I do not want to draw any general conclusions. My programmer's instincts say that it's true, though. -- Martin Sand Christensen IT Services, Dept. of Electronic Systems From lie.1296 at gmail.com Tue Dec 8 07:02:38 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Tue, 08 Dec 2009 23:02:38 +1100 Subject: Duplicates of third-party libraries In-Reply-To: References: <877hsygytc.fsf_-_@benfinney.id.au> Message-ID: <4b1e40e4$1@dnews.tpgi.com.au> On 12/8/2009 3:25 PM, Martin P. Hellwig wrote: > Ben Finney wrote: >> "Martin P. Hellwig" writes: > >> >> Along with the duplication this introduces, it also means that any bug >> fixes ? even severe security fixes ? in the third-party code will not be >> addressed in your duplicate. > > I disagree, what you need is: > - An automated build system for your deliveries, something you should > have anyway > - An method of tracking versions of your dependencies, again something > you should have anyway > - And a policy that you incorporate bug fixes from your dependencies in > your deliveries, something you should do anyway if you are serious about > your product. I disagree, what you should have is an Operating System with a package management system that addresses those issues. The package management must update your software and your dependencies, and keep track of incompatibilities between you and your dependencies. The package management systems have in many popular Linux distro is close to it. The point is, those issues should not be your issue in the first place; the OS is the one in charge of coordination between multiple software (or else why would we have an OS for?). In the Windows\b\b\b\b\b\b\b Real world, some OS let off *their responsibility* and told their users to manage dependency by their own. Obviously most users don't have the knowledge to do so, and the undue burden then goes to software developers. A software ideally shouldn't need to care about how the machine is configured ("Separation of Concern"). I never liked the idea of each software to have its own software updater, they are sign of bloated software. There should ideally be one software updater in the system ("Don't Repeat Yourself"). Many automatic updater by big companies is configured to run on computer startup and doesn't shutdown without an order from the Task Manager. They then reinstall their autorun entry in the registry when the user deletes them, trying to outsmart the user since they think the user is just ain't smart enough. In my Windows computer, the only software I give my blessing to auto-update is the antivirus; anything else just bloats the system. A good-behaviored software would just notify me about update (e.g. OpenOffice and Pidgin), and even then only when I'm using the software (not every time you open your computer). I'm glad I don't have such chaos when using my Gentoo or Ubuntu, the system software updater handles all those just fine. From robin at reportlab.com Tue Dec 8 07:27:55 2009 From: robin at reportlab.com (Robin Becker) Date: Tue, 08 Dec 2009 12:27:55 +0000 Subject: Graph library for Python In-Reply-To: References: <4B18F685.8050102@egenix.com> <4B1CFA36.9060805@egenix.com> <4B1D35BC.5000002@egenix.com> <4B1D5CB3.8030805@egenix.com> <00a70ac5$0$15659$c3e8da3@news.astraweb.com> Message-ID: <4B1E464B.6090408@chamonix.reportlab.co.uk> geremy condra wrote: ........... > > I don't have a problem with adding this if there's a strong desire for it, > but at the moment I'm leaning towards a wait-and-see approach, for > all the reasons you described. > > Geremy Condra I don't want to sound pessimistic, but graph and digraph theory has a lot of history, especially in computer science. There are already very many implementations eg http://code.google.com/p/igraph http://www.boost.org/doc/libs/release/libs/graph http://ernst-schroeder.uni.lu/Digraph/doc/ http://code.google.com/p/python-graph http://compbio.washington.edu/~zach/py_graph/doc/html/public/py_graph-module.html and many others......some of the above already seem to be very useful. Is there reason to suppose that any one representation of graphs or digraphs is so good we need to add it to python? Even for fairly common algorithms eg Dijkstra's shortest path there doesn't seem to be complete agreement on how to implement them; for the details of how nodes/edges/paths should be stored and efficiently manipulated there is huge variety. Wait seems like a good policy. -- Robin Becker From martin.hellwig at dcuktec.org Tue Dec 8 07:35:44 2009 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Tue, 08 Dec 2009 12:35:44 +0000 Subject: Duplicates of third-party libraries In-Reply-To: <4b1e40e4$1@dnews.tpgi.com.au> References: <877hsygytc.fsf_-_@benfinney.id.au> <4b1e40e4$1@dnews.tpgi.com.au> Message-ID: Lie Ryan wrote: Yes from an argumentative perspective you are right. But given the choice of being right and alienate the fast majority of my potential user base, I rather be wrong. For me the 'Although practicality beats purity' is more important than trying to beat a dead horse that is a platform independent package manager actively supported by all mayor operating systems. But hey if it works for you, great! -- MPH http://blog.dcuktec.com 'If consumed, best digested with added seasoning to own preference.' From sjmachin at lexicon.net Tue Dec 8 07:53:48 2009 From: sjmachin at lexicon.net (John Machin) Date: Tue, 8 Dec 2009 04:53:48 -0800 (PST) Subject: Request for py program to insert space between two characters and saved as text? References: <7b87ecb70912071856k10ad366du2b07ce92b94e50e3@mail.gmail.com> <79f477fa-770b-417d-89ee-445c9c9cc6ef@a10g2000pre.googlegroups.com> Message-ID: <5c6d0249-014b-4ace-b446-f75514738869@u8g2000prd.googlegroups.com> On Dec 8, 9:42?pm, steve wrote: > On 12/08/2009 02:19 PM, John Machin wrote: > > >> [...snip...] > > Perhaps there are some subtleties of which we are unaware ... > > > I would be very surprised if the OP could not find on a forum much > > closer to home more people who know more about using Indic scripts on > > computers than here. > > That's true. I'd recommend that the original poster, posts the query at the > bangalore python user group mailing list: > > http://mail.python.org/mailman/listinfo/bangpypers > > ...alongwith some additional details of the requirements. I am sure they > wouldn't mind reading and replying to the question in kannada itself. > > After all Kannada is the language of the sate of Karnataka, of which Bangalore > (or Bengaluru as it is known these days) is the capital city. Off-list, I've already solicited assistance for the OP from a prominent bangpyper. Cheers, John From lie.1296 at gmail.com Tue Dec 8 07:58:13 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Tue, 08 Dec 2009 23:58:13 +1100 Subject: python proxy checker ,change to threaded version In-Reply-To: References: Message-ID: <4b1e4deb$1@dnews.tpgi.com.au> On 12/8/2009 8:43 AM, Rhodri James wrote: >> >> def run(self): >> result = func(*func_args) # matching run_in_thread param names >> callback(result, *callback_args) > Neat, but I think you mean > > if callback is not None: > callback(result, *callback_args) > > for that last line. how about: import threading def run_in_thread( func, func_args=[], callback=lambda r,*a: None, callback_args=[] ): class MyThread ( threading.Thread ): def run ( self ): result = func(*func_args) callback(result, *callback_args) MyThread().start() (and for me, I'd ) From cournape at gmail.com Tue Dec 8 08:02:18 2009 From: cournape at gmail.com (David Cournapeau) Date: Tue, 8 Dec 2009 22:02:18 +0900 Subject: Duplicates of third-party libraries In-Reply-To: <4b1e40e4$1@dnews.tpgi.com.au> References: <877hsygytc.fsf_-_@benfinney.id.au> <4b1e40e4$1@dnews.tpgi.com.au> Message-ID: <5b8d13220912080502u4209ec0awd7d35aa104467a27@mail.gmail.com> On Tue, Dec 8, 2009 at 9:02 PM, Lie Ryan wrote: > > I disagree, what you should have is an Operating System with a package > management system that addresses those issues. The package management must > update your software and your dependencies, and keep track of > incompatibilities between you and your dependencies. This has many problems as well: you cannot install/update softwares without being root, there are problems when you don't have the right version, when the library/code is not packaged, etc... Don't get me wrong, I am glad that things like debian, rpm exist, but it is no panacea. There are simply no silver bullet to the deployment problem, and difference cases/user target may require different solutions. David From eckhardt at satorlaser.com Tue Dec 8 08:06:58 2009 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Tue, 08 Dec 2009 14:06:58 +0100 Subject: IO Gurus: what are the differences between these two methods? References: <75da8a5f-857b-4fab-bfb9-8d03b1cadf1a@u1g2000pre.googlegroups.com> Message-ID: dpapathanasiou wrote: > I have two methods for writing binaries files: the first works with > data received by a server corresponding to a file upload, and the > second works with data sent as email attachments. Hmmm, no. Looking at your code, the first of your functions actually treats its argument as a stream, while the second one treats it like a byte buffer (as str object, to be precise). > The odd thing is, they're not interchangeable: if I use the first one > to saved data parsed from an email attachment, it fails; similarly, > the second function fails when dealing with an uploaded file data. There is nothing odd about that, they are different functions working with different things. > What are the critical differences? > > def write_binary_file (folder, filename, f, chunk_size=4096): [...] > for file_chunk in read_buffer(f, chunk_size): > file_obj.write(file_chunk) [...] > def write_binary_file (folder, filename, filedata): [...] > file_obj.write(filedata) BTW: You could have reduced the code yourself before posting. You might have seen the difference yourself then! Further, I'm curious, do you have any non-binary files anywhere? =) Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From pierre.gaillard at gmail.com Tue Dec 8 08:36:24 2009 From: pierre.gaillard at gmail.com (Pierre) Date: Tue, 8 Dec 2009 05:36:24 -0800 (PST) Subject: SUB-MATRIX extraction Message-ID: <5b2cc641-fb23-43af-ba23-bae61eceb4de@j24g2000yqa.googlegroups.com> Hello, let b = array([ [0,1,2] , [3,4,5] , [6,7,8] ]) How can I easily extract the submatrix [ [0 ,1], [3, 4]] ? One possiblity is : b[[0,1],:][:,[0,1]] but it is not really easy ! Thanks. From aioe.org at technicalbloke.com Tue Dec 8 08:55:16 2009 From: aioe.org at technicalbloke.com (r0g) Date: Tue, 08 Dec 2009 13:55:16 +0000 Subject: Request for py program to insert space between two characters and saved as text? References: <7b87ecb70912071856k10ad366du2b07ce92b94e50e3@mail.gmail.com> Message-ID: Dennis Lee Bieber wrote: > On Tue, 8 Dec 2009 08:26:58 +0530, 74yrs old > declaimed the following in gmane.comp.python.general: > >> For Kannada project .txt(not .doc) is used, my requirement is to have one >> In this context, I request you kindly for small python program - to make or > > Excuse me -- you want one of US to supply you with a program that > will be used for YOUR entry to some job site? (At least, that's what I > seem to be finding for "Kannada project") > Well it is only a 2 line program and he did ask nicely after all, if you begrudge him it then feel free to not answer, righteous indignation rarely helps anyone. Dear OP... Put the following 2 lines into a file and save it as spacer.py import sys print ' '.join([e for e in open(sys.argv[1], 'r').read()]) Then open a terminal window and 'cd' to the same folder you just saved the spacer.py file in. Type... python spacer.py inputfile.txt > outputfile.txt This will run inputfile.txt through the space adding program we have just saved and then 'pipe' the output of that into a new file outputfile.txt Hope this helps, Roger Heathcote. From lie.1296 at gmail.com Tue Dec 8 08:56:40 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Wed, 09 Dec 2009 00:56:40 +1100 Subject: Duplicates of third-party libraries In-Reply-To: References: <877hsygytc.fsf_-_@benfinney.id.au> <4b1e40e4$1@dnews.tpgi.com.au> Message-ID: <4b1e5b9d$1@dnews.tpgi.com.au> On 12/9/2009 12:02 AM, David Cournapeau wrote: > On Tue, Dec 8, 2009 at 9:02 PM, Lie Ryan wrote: > >> I disagree, what you should have is an Operating System with a package >> management system that addresses those issues. The package management must >> update your software and your dependencies, and keep track of >> incompatibilities between you and your dependencies. > > This has many problems as well: you cannot install/update softwares > without being root, A package manager with setuid, though dangerous, can run without being root. Some package manager (e.g. Gentoo's Portage w/ prefix) allow user to set to install in a non-default directory (one that doesn't require root access). > there are problems when you don't have the right version, That's the whole point of package management system! A package management system are not just plain software installers (like MSI and NSIS), they go beyond and figure out the "right version" of your dependencies. In many package management system, bleeding edge packages are run by testers that will figure out the dependency your software requires. If you are nice (it is your responsibility anyway), you can save them some work by telling them the dependency version you've tested your software with. > when the library/code is not packaged, etc... Don't worry, the majority of users are willing to wait a few weeks until the library/code gets packaged. Some even _refuses_ to use anything younger than a couple of years. > Don't get me wrong, I am glad that things like debian, rpm exist, > but it is no panacea They're not; but software developers should maximize functionality provided by package managers rather than trying to build their own ad-hoc updater and dependency manager. > There are simply no silver bullet to the > deployment problem, and difference cases/user target may require > different solutions. The only thing that package managers couldn't provide is for the extremist bleeding edge; those that want the latest and the greatest in the first few seconds the developers releases them. The majority of users don't fall into that category, most users are willing to wait a few weeks to let all the just-released bugs sorted out and wait till the package (and their dependencies) stabilize. From steve at REMOVE-THIS-cybersource.com.au Tue Dec 8 09:47:44 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 08 Dec 2009 14:47:44 GMT Subject: Graph library for Python References: <4B1CFA36.9060805@egenix.com> <4B1D35BC.5000002@egenix.com> <4B1D5CB3.8030805@egenix.com> <4B1D8FB1.5010703@egenix.com> Message-ID: <00a7eba2$0$15659$c3e8da3@news.astraweb.com> On Tue, 08 Dec 2009 03:06:29 -0500, geremy condra wrote: [snip 215 lines of quoted-quoted-quoted-quoted-quoted text] In the future, would you mind trimming the unneeded quoting from your post? There's no need to duplicate the *entire* conversation in *every* post, and it is awfully AOL-like of you to have 215 lines of text, with up to five levels of quotation, followed by two lines of new content. Thank you. -- Steven From aioe.org at technicalbloke.com Tue Dec 8 09:48:47 2009 From: aioe.org at technicalbloke.com (r0g) Date: Tue, 08 Dec 2009 14:48:47 +0000 Subject: python proxy checker ,change to threaded version References: <4b1e4deb$1@dnews.tpgi.com.au> Message-ID: Lie Ryan wrote: > On 12/8/2009 8:43 AM, Rhodri James wrote: >>> >>> def run(self): >>> result = func(*func_args) # matching run_in_thread param names >>> callback(result, *callback_args) >> Neat, but I think you mean >> >> if callback is not None: >> callback(result, *callback_args) >> >> for that last line. > > how about: > import threading > > def run_in_thread( func, func_args=[], callback=lambda r,*a: None, > callback_args=[] ): > class MyThread ( threading.Thread ): > def run ( self ): > result = func(*func_args) > callback(result, *callback_args) > MyThread().start() > > > (and for me, I'd ) Cool, that's a neat trick I'd never have thought of. I think the 2 line alternative might be a little more pythonic though, in terms of readability & simplicity... if callback: callback(result, *callback_args) That could be because I'm not terribly au fait with the whole lambda calculus thing though. What say those who are comfortable with it? Obvious or oblique? Roger. From invalid at invalid.invalid Tue Dec 8 10:08:22 2009 From: invalid at invalid.invalid (Grant Edwards) Date: Tue, 8 Dec 2009 15:08:22 +0000 (UTC) Subject: Duplicates of third-party libraries References: <877hsygytc.fsf_-_@benfinney.id.au> <87tyw2f3wi.fsf@benfinney.id.au> Message-ID: On 2009-12-08, Martin P. Hellwig wrote: > - In the ideal world, a upgrade of a dependency won't break > your program, in reality users fear upgrading dependencies > because they don't know for sure it won't result in a dll > hell type of problem. In my experience with binary-based distros (RedHat, Windows, Debian, etc.), upgrading libraries broke things as often as not. I've had significantly better results with Gentoo. However, were I shipping a significant product that dependended up updates to external libraries, I'd be very worried. It also seems like a lot of work to provide the product in all of the different package-management formats used by customers. Even considering the extra updates that might be required for library fixes, shipping a single stand-alone system sounds like a lot less work. -- Grant Edwards grante Yow! JAPAN is a WONDERFUL at planet -- I wonder if we'll visi.com ever reach their level of COMPARATIVE SHOPPING ... From invalid.emal at at.address Tue Dec 8 10:08:36 2009 From: invalid.emal at at.address (Joe) Date: Tue, 08 Dec 2009 09:08:36 -0600 Subject: no module named error Message-ID: I am trying to write/run a python script which imports from another script which is located in my /usr/lib64/python2.6/site-packages/ dir, but getting the following error. $ python ./mytest.py Traceback (most recent call last): File "./mytest.py", line 45, in from moda import * File "/usr/lib64/python2.6/site-packages/moda.py", line 7, in import _moda ImportError: No module named _moda The script moda.py exists. My script is: #!/usr/bin/python import sys from moda import * def main(args = sys.argv[1:]): print 'test' if __name__ == '__main__' : main() Any idea what I'm doing wrong? From Nikolaus at rath.org Tue Dec 8 10:10:41 2009 From: Nikolaus at rath.org (Nikolaus Rath) Date: Tue, 08 Dec 2009 10:10:41 -0500 Subject: Determine PyArg_ParseTuple parameters at runtime? Message-ID: <877hsxwlfy.fsf@vostro.rath.org> Hello, I want to create an extension module that provides an interface to a couple of C functions that take arguments of type struct iovec, struct stat, struct flock, etc (the FUSE library, in case it matters). Now the problem is that these structures contain attributes of type fsid_t, off_t, dev_t etc. Since I am receiving the values for these attributes from the Python caller, I have to convert them to the correct type using PyArg_ParseTuple. However, since the structs are defined in a system-dependent header file, when writing the code I do not know if on the target system, e.g. off_t will be of type long, long long or unsigned long, so I don't know which format string to pass to PyArg_ParseTuple. Are there any best practices for handling this kind of situation? I'm at a loss right now. The only thing that comes to my mind is to, e.g., to compare sizeof(off_t) to sizeof(long) and sizeof(long long) and thereby determine the correct bit length at runtime. But this does not help me to figure out if it is signed or unsigned, or (in case of other attributes than off_t) if it is an integer at all. Best, -Nikolaus -- ?Time flies like an arrow, fruit flies like a Banana.? PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6 02CF A9AD B7F8 AE4E 425C From sccolbert at gmail.com Tue Dec 8 10:10:45 2009 From: sccolbert at gmail.com (Chris Colbert) Date: Tue, 8 Dec 2009 16:10:45 +0100 Subject: relative imports with the __import__ function Message-ID: <7f014ea60912080710i2249961dk7b6c33e044d8a74@mail.gmail.com> I have package tree that looks like this: main.py package ----__init__.py ----configuration.ini ----server --------__init__.py --------xmlrpc_server.py --------controller.py --------reco ------------ ----segmentation --------__init__.py --------red_objects.py ---- main.py launches an instance of xmlrpc_server.py which, in turn, imports controller.py. controller.py reads configuration.ini to determine which module/function to import from the segmentation directory and subsequently use. that config file specifies the module as 'red_objects' and the function as 'segment_red'. I am trying to dynamically import that module and func using the __import__ statement but keep getting empty module errors. In the following code segment, the failing code is uncommented, but the commented code works fine: seg_mod = 'red_objects' smod = __import__('..segmentation.%s' % seg_mod, fromlist=[seg_func], level=-1) #from ..segmentation import red_objects #smod = red_objects I have tried all sorts of values for the 'level' kwarg as well as everywhich variation of the dotted relative notation. I'm assuming i'm missing something fundamental on the import resolution... As an aside, I would like to move main.py inside of the package directory, but I dont know if that is possible with what i'm trying to do here. Thanks for any help. Cheers! Chris From deets at nospam.web.de Tue Dec 8 10:11:26 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 08 Dec 2009 16:11:26 +0100 Subject: no module named error References: Message-ID: <7o78kuF3p45l7U1@mid.uni-berlin.de> Joe wrote: > I am trying to write/run a python script which imports from another > script which is located in my /usr/lib64/python2.6/site-packages/ dir, > but getting the following error. > > $ python ./mytest.py > Traceback (most recent call last): > File "./mytest.py", line 45, in > from moda import * > File "/usr/lib64/python2.6/site-packages/moda.py", line 7, in > > import _moda > ImportError: No module named _moda > > > The script moda.py exists. My script is: But it's searching for _moda.*, most probably a binary extension. Does that exist, and if yes, has it the proper architecture or is it maybe 32 bit? Diez From invalid.emal at at.address Tue Dec 8 10:21:56 2009 From: invalid.emal at at.address (Joe) Date: Tue, 08 Dec 2009 09:21:56 -0600 Subject: no module named error In-Reply-To: <7o78kuF3p45l7U1@mid.uni-berlin.de> References: <7o78kuF3p45l7U1@mid.uni-berlin.de> Message-ID: > But it's searching for _moda.*, most probably a binary extension. Does that > exist, and if yes, has it the proper architecture or is it maybe 32 bit? I'm just going by an example script. moda is a package I was given that is written in C and has some python bindings and does run 64-bit. I'm on gentoo. I'm not sure it's installed correctly, but it did come w/ a setup.py, and I ran 'setup.py install' and it seemed to have installed correctly. $ sudo python ./setup.py install running install running build running build_py running install_lib running install_egg_info Removing /usr/lib64/python2.6/site-packages/moda-2.1-py2.6.egg-info Writing /usr/lib64/python2.6/site-packages/moda-2.1-py2.6.egg-info From martin.hellwig at dcuktec.org Tue Dec 8 10:22:17 2009 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Tue, 08 Dec 2009 15:22:17 +0000 Subject: Duplicates of third-party libraries In-Reply-To: <4b1e5b9d$1@dnews.tpgi.com.au> References: <877hsygytc.fsf_-_@benfinney.id.au> <4b1e40e4$1@dnews.tpgi.com.au> <4b1e5b9d$1@dnews.tpgi.com.au> Message-ID: Lie Ryan wrote: > > The only thing that package managers couldn't provide is for the > extremist bleeding edge; those that want the latest and the greatest in > the first few seconds the developers releases them. The majority of > users don't fall into that category, most users are willing to wait a > few weeks to let all the just-released bugs sorted out and wait till the > package (and their dependencies) stabilize. Well you majority of your users still fall into my category of minority, as most of my paid support clients use windows, although I use Ubuntu as my main developer machine. -- MPH http://blog.dcuktec.com 'If consumed, best digested with added seasoning to own preference.' From deets at nospam.web.de Tue Dec 8 10:26:54 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 08 Dec 2009 16:26:54 +0100 Subject: no module named error References: <7o78kuF3p45l7U1@mid.uni-berlin.de> Message-ID: <7o79huF3l4v9uU1@mid.uni-berlin.de> Joe wrote: >> But it's searching for _moda.*, most probably a binary extension. Does >> that exist, and if yes, has it the proper architecture or is it maybe 32 >> bit? > > I'm just going by an example script. moda is a package I was given that > is written in C and has some python bindings and does run 64-bit. I'm on > gentoo. I'm not sure it's installed correctly, but it did come w/ a > setup.py, and I ran 'setup.py install' and it seemed to have installed > correctly. > > $ sudo python ./setup.py install > running install > running build > running build_py > running install_lib > running install_egg_info > Removing /usr/lib64/python2.6/site-packages/moda-2.1-py2.6.egg-info > Writing /usr/lib64/python2.6/site-packages/moda-2.1-py2.6.egg-info You didn't answer my question. Did it install the _moda.* file the moda.py is searching for? Diez From joncle at googlemail.com Tue Dec 8 10:29:55 2009 From: joncle at googlemail.com (Jon Clements) Date: Tue, 8 Dec 2009 07:29:55 -0800 (PST) Subject: SUB-MATRIX extraction References: <5b2cc641-fb23-43af-ba23-bae61eceb4de@j24g2000yqa.googlegroups.com> Message-ID: <8e29b5aa-b93d-4d51-9c71-b3ba3912d728@r40g2000yqn.googlegroups.com> On Dec 8, 1:36?pm, Pierre wrote: > Hello, > > let b = array([ [0,1,2] , [3,4,5] , [6,7,8] ]) > > How can I easily extract the submatrix [ [0 ,1], [3, 4]] ? > > One possiblity is : b[[0,1],:][:,[0,1]] but it is not really easy ! > > Thanks. x = numpy.array([ [0,1,2], [3,4,5], [6,7,8] ]) print x[0:2,:2] >>> array([[0, 1], [3, 4]]) Check out http://www.scipy.org/Tentative_NumPy_Tutorial hth, Jon. From jorgeecardona at gmail.com Tue Dec 8 10:43:09 2009 From: jorgeecardona at gmail.com (Jorge Cardona) Date: Tue, 8 Dec 2009 10:43:09 -0500 Subject: Generators. In-Reply-To: <5c6260a0-cde1-4791-a73c-d299fe38f42d@v25g2000yqk.googlegroups.com> References: <4b1c8cc3$1@dnews.tpgi.com.au> <5c6260a0-cde1-4791-a73c-d299fe38f42d@v25g2000yqk.googlegroups.com> Message-ID: <51d803a90912080743v3213d109y6ff5c3457b74e5ba@mail.gmail.com> 2009/12/7 Taylor : > On Dec 7, 1:29?pm, Jorge Cardona wrote: >> 2009/12/7 Lie Ryan : >> >> >> >> > On 12/7/2009 7:22 AM, Jorge Cardona wrote: >> >> >> Hi, >> >> >> I was trying to create a function that receive a generator and return >> >> a list but that each elements were computed in a diferent core of my >> >> machine. I start using islice function in order to split the job in a >> >> way that if there is "n" cores each "i" core will compute the elements >> >> i,i+n,i+2n,..., but islice has a weird (to me) behavior, look: >> >> > it's nothing weird, python just do what you're telling it to: >> >> > transform all x in X with f(x) >> >> >> g = (f(x) for x in X) >> >> > then slice the result of that >> >> >> print(list(x for x in islice(g,0,None,2))) >> >> When i wrote that first line of code i thought that i was creating a >> generator that will later compute ?the elements of X with function f, >> if i will like to transform them immediately i would use [] instead >> (), so, the result is not where i want to slice, even so, is exactly >> the same to slice, after or before, the only difference is that after >> the compute i'm losing 5 in unnecessary execution of the function f. >> >> > what you want to do is to slice before you transform: >> >>>> g = (x for x in islice(X, 0, None, 2)) >> >>>> print(list(f(x) for x in g)) >> > eval: 0 >> > eval: 2 >> > eval: 4 >> > eval: 6 >> > eval: 8 >> > [0, 2, 4, 6, 8] >> >> What i want to do is a function that receive any kind of generator and >> execute it in several cores (after a fork) and return the data, so, i >> can't slice the set X before create the generator. >> >> >> >> >> islice execute the function at the generator and drop the elements >> >> that aren't in the slice. I found that pretty weird, the way that i >> >> see generators is like an association between and indexing set (an >> >> iterator or another generator) and a computation that is made indexed >> >> by the indexing set, and islice is like a "transformation" on the >> >> indexing set,it doesn't matter the result of the function, the slice >> >> should act only on the indexing set, some other "transformation" like >> >> takewhile act on the result so, the execution it has to be made, but >> >> in the islice, or other "transformation" that act only in the indexing >> >> set, the function shouldn't be executed at each element, but only on >> >> that new set that result of the application of the "transformation" on >> >> the original set. >> >> > that seems like an extremely lazy evaluation, I don't know if even a true >> > lazy language do that. Python is a strict language, with a few laziness >> > provided by generators, in the end it's still a strict language. >> >> Yes, it looks like lazy evaluation, but, i don't see why there is not >> a better control over the iterable associated to a generator, even >> with Python that is a strict language, it will increase the >> functionality of it, and the performance too, imagine that you pass a >> function that takes 1 sec in run, and for several reason you can't >> slice before (as the smp function that i want to create), the final >> performance with the actual islice it gets really reduced >> Just creating the separation between those transformation that act on >> the index(islice, or tee) on those that act on the result(dropwhile, >> takewhile, etc.) the control could be fine enough to increase >> usability (that's the way i think right now), and you will be able to >> combine generator without lose performance. >> >> >> Well, it works for what i need, but is not very neat, and i think that >> >> there it should be a formal way to act on the base indexing iterator, >> >> such way exists? Is there a better approach to get what i need? >> >> > Reverse your operation. >> > -- >> >http://mail.python.org/mailman/listinfo/python-list >> >> -- >> Jorge Eduardo Cardona >> jorgeecard... at gmail.com >> jorgeecardona.blogspot.com >> ------------------------------------------------ >> Linux registered user ?#391186 >> Registered machine ? ?#291871 >> ------------------------------------------------ > > What would you have your islice do for the following generator? > > def fib(n): > ? ?a,b=0,1 > ? ?for x in range(n): > ? ? ? ?a,b=b,a+b > ? ? ? ?yield a > > In order for some value it yields to be correct, it needs execute all > the previous times. If it happens that some of the results aren't > used, they are thrown out. As is, using your islice (on, say, fib(10)) > gives a KeyError for the key '.0'. > Point is, generators don't work that way. You aren't guaranteed to be > able to jump around, only to find the next value. If you need to split > a particular generator up into parts that can be computed separately, > your best bet is probably to rewrite that generator. yes, it doesn't work with that example, f_locals has only the n argument. Let me rewrite the islice like this: def islice(iterable, *args): s = slice(*args) # search the deepest iter (Base indexing set) it = iterable while hasattr(it, 'gi_frame') and ('.0' in it.gi_frame.f_locals): it = it.gi_frame.f_locals['.0'] # Consume the base indexing set until the first element for i in range(s.start): it.next() for e in iterable: yield e # Consume the base indexing set until the next element for i in range(s.step-1): next(it) And then: def fib(n): a,b=0,1 for x in range(n): a,b=b,a+b yield a g = fib(10) print(list(x for x in islice(g,0, None,2))) Will result in: [1, 3, 8, 21, 55] How I see that particular example is that the fibonacci generator is a base indexing set, look that you didn't define it in terms of an association with another set and a particular function, even when there is a range(n) and a sum operation, I can't think at this moment in a way to represent fibonacci in generator expression terms. The fact that there is a state that has to be preserved between each called item of the generator defined with fib(n) (in order to avoid a recursive implementation) makes impossible to define the underlying function as fib(n) because it really depends on that state (fib(state)), so, a unique indexing set couldn't be used here without maintain an auxiliary set that holds that state at each compute. Even with fibonacci there is only need to maintain the state variable, and create a full range of numbers without known a priori the n number that maps to the result, with factorial one can hold an state that represent the past factorial and call the function with a a present n. Maintain the state variables is permitted by the definition of the generator as a function with yield, and in your fib it's maintained in a and b. (((Is there any "clean" way to define a (fib(x) for x in count()) without falls in recursive errors and high memory usage?, but as a generator expression, i can't think in one right now.))) A new element is shown here (well, or I just note that at this moment), is that a generator defined as a function with yield could not be seen as an associations between an indexing set and a function, but just as an indexing set of new generators as in: g = (f(x) for x in fib(10)) print(list(x for x in islice(g,0, None,2))) that result in: eval: 1 eval: 2 eval: 5 eval: 13 eval: 34 [1, 2, 5, 13, 34] I just download the unittests for itertools from svn of python2.7: test_islice (__main__.TestGC) ... ok and adding islice above: test_islice (__main__.TestGC) ... ok > -- > http://mail.python.org/mailman/listinfo/python-list > -- Jorge Eduardo Cardona jorgeecardona at gmail.com jorgeecardona.blogspot.com ------------------------------------------------ Linux registered user #391186 Registered machine #291871 ------------------------------------------------ From invalid at invalid.invalid Tue Dec 8 11:01:28 2009 From: invalid at invalid.invalid (Grant Edwards) Date: Tue, 8 Dec 2009 16:01:28 +0000 (UTC) Subject: Duplicates of third-party libraries References: <877hsygytc.fsf_-_@benfinney.id.au> <4b1e40e4$1@dnews.tpgi.com.au> <4b1e5b9d$1@dnews.tpgi.com.au> Message-ID: On 2009-12-08, Martin P. Hellwig wrote: > Lie Ryan wrote: > >> >> The only thing that package managers couldn't provide is for the >> extremist bleeding edge; those that want the latest and the greatest in >> the first few seconds the developers releases them. The majority of >> users don't fall into that category, most users are willing to wait a >> few weeks to let all the just-released bugs sorted out and wait till the >> package (and their dependencies) stabilize. > > Well you majority of your users still fall into my category of minority, > as most of my paid support clients use windows, Does windows even _have_ a library dependancy system that lets an application specify which versions of which libraries it requires? > although I use Ubuntu as my main developer machine. -- Grant Edwards grante Yow! My life is a patio at of fun! visi.com From bruno.42.desthuilliers at websiteburo.invalid Tue Dec 8 11:25:16 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 08 Dec 2009 17:25:16 +0100 Subject: Question on Python as career In-Reply-To: <47a66571-96d2-4976-9812-5b90b6fc5271@u7g2000yqm.googlegroups.com> References: <614b8dde-324b-4d54-8e73-7a96e4c0b1cf@a21g2000yqc.googlegroups.com> <_DfRm.61945$rE5.35795@newsfe08.iad> <47a66571-96d2-4976-9812-5b90b6fc5271@u7g2000yqm.googlegroups.com> Message-ID: <4b1e7deb$0$32359$426a74cc@news.free.fr> joy99 a ?crit : (snip) > I was thinking if I need to know Django,any good RDBMS(I know only MS- > Access) Any job in IT will (well... "should") indeed require a decent knowledge of the relational thery / algebra, relational database design (normal forms etc), SQL, and working knowledge with at least one "major RDBMS (oracle or postgresql) and possibly the ubiquitous (in the web world) MySQL gizmo. Django and/or Rail might be a good idea too, but most of the "enterprise" stuff is still done in Java :( From martin.hellwig at dcuktec.org Tue Dec 8 11:35:32 2009 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Tue, 08 Dec 2009 16:35:32 +0000 Subject: Duplicates of third-party libraries In-Reply-To: References: <877hsygytc.fsf_-_@benfinney.id.au> <4b1e40e4$1@dnews.tpgi.com.au> <4b1e5b9d$1@dnews.tpgi.com.au> Message-ID: Grant Edwards wrote: > Does windows even _have_ a library dependancy system that lets > an application specify which versions of which libraries it > requires? Well you could argue that easy_install does it a bit during install. Then there is 'Windows Side By Side' (winsxs) system which sorta does it during run time. -- MPH http://blog.dcuktec.com 'If consumed, best digested with added seasoning to own preference.' From andrea.crotti.0 at gmail.com Tue Dec 8 11:39:13 2009 From: andrea.crotti.0 at gmail.com (andrea) Date: Tue, 08 Dec 2009 17:39:13 +0100 Subject: In lista infinita? Message-ID: Ho notato che i generatori anche se infiniti non si lamentano se usati in modo potenzialmente "pericoloso". Dato: m = (sum(xrange(1,x)) for x in count(1)) 10 in m -> True ma se gli passo un valore che non c'? naturalmente loopa all'infinito perch? non ha modo di sapere se prima o poi trover? il numero. Ora assumendo una sequenza non decrescente con questa funzioncina si pu? effettivamente avere una "pigrizia" a l? haskell. --8<---------------cut here---------------start------------->8--- def in_inf(gen, el): x = dropwhile(lambda x: x < el, gen) if x.next() == el: return True else: return False --8<---------------cut here---------------end--------------->8--- Che dite pu? andare? Magari si potrebbe passare la funzione di controllo come argomento per generalizzarla. Altri miglioramenti/utilizzi trasversali? From martin.hellwig at dcuktec.org Tue Dec 8 11:40:48 2009 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Tue, 08 Dec 2009 16:40:48 +0000 Subject: SUB-MATRIX extraction In-Reply-To: <8e29b5aa-b93d-4d51-9c71-b3ba3912d728@r40g2000yqn.googlegroups.com> References: <5b2cc641-fb23-43af-ba23-bae61eceb4de@j24g2000yqa.googlegroups.com> <8e29b5aa-b93d-4d51-9c71-b3ba3912d728@r40g2000yqn.googlegroups.com> Message-ID: Jon Clements wrote: > On Dec 8, 1:36 pm, Pierre wrote: >> Hello, >> >> let b = array([ [0,1,2] , [3,4,5] , [6,7,8] ]) >> >> How can I easily extract the submatrix [ [0 ,1], [3, 4]] ? >> >> One possiblity is : b[[0,1],:][:,[0,1]] but it is not really easy ! >> >> Thanks. > > x = numpy.array([ [0,1,2], [3,4,5], [6,7,8] ]) > print x[0:2,:2] >>>> array([[0, 1], > [3, 4]]) > > Check out http://www.scipy.org/Tentative_NumPy_Tutorial > > hth, > > Jon. Yeah numpy is great like that and is the most obvious and probably the most right solution, however I'd like to mention if you are going to do a lot of stuff that is going to look an awful lot like SQL, perhaps it is easier to pump it in a (in :memory:) sqlite table and use it that way. Chances are though that you are far better of with numpy. -- MPH http://blog.dcuktec.com 'If consumed, best digested with added seasoning to own preference.' From __peter__ at web.de Tue Dec 8 11:48:02 2009 From: __peter__ at web.de (Peter Otten) Date: Tue, 08 Dec 2009 17:48:02 +0100 Subject: relative imports with the __import__ function References: Message-ID: Chris Colbert wrote: > I have package tree that looks like this: > > main.py > package > ----__init__.py > ----configuration.ini > ----server > --------__init__.py > --------xmlrpc_server.py > --------controller.py > --------reco > ------------ > ----segmentation > --------__init__.py > --------red_objects.py > ---- > > > main.py launches an instance of xmlrpc_server.py which, in turn, > imports controller.py. > controller.py reads configuration.ini to determine which > module/function to import from the segmentation directory and > subsequently use. > > that config file specifies the module as 'red_objects' and the > function as 'segment_red'. > > I am trying to dynamically import that module and func using the > __import__ statement but keep getting empty module errors. > I'm assuming i'm missing something fundamental on the import resolution... After some experimentation it turns out you have to provide some context for __import__() to determine the absolute location of the requested module. The required bit of information is the current module's __name__ attribute which you can provide via the globals parameter: def import_segmentation(name): return getattr(__import__("segmentation." + name, level=2, globals=globals()), name) Peter From jorgeecardona at gmail.com Tue Dec 8 11:52:45 2009 From: jorgeecardona at gmail.com (Jorge Cardona) Date: Tue, 8 Dec 2009 11:52:45 -0500 Subject: Generators. In-Reply-To: <4b1e0617@dnews.tpgi.com.au> References: <4b1c8cc3$1@dnews.tpgi.com.au> <4b1e0617@dnews.tpgi.com.au> Message-ID: <51d803a90912080852p4074dcf2ga704bcfd4a478e92@mail.gmail.com> 2009/12/8 Lie Ryan : > First, I apologize for rearranging your message out of order. > > On 12/8/2009 5:29 AM, Jorge Cardona wrote: >>>> >>>> islice execute the function at the generator and drop the elements >>>> that aren't in the slice. I found that pretty weird, the way that i >>>> see generators is like an association between and indexing set (an >>>> iterator or another generator) and a computation that is made indexed >>>> by the indexing set, and islice is like a "transformation" on the >>>> indexing set,it doesn't matter the result of the function, the slice >>>> should act only on the indexing set, some other "transformation" like >>>> takewhile act on the result so, the execution it has to be made, but >>>> in the islice, or other "transformation" that act only in the indexing >>>> set, the function shouldn't be executed at each element, but only on >>>> that new set that result of the application of the "transformation" on >>>> the original set. >>> >>> that seems like an extremely lazy evaluation, I don't know if even a true >>> lazy language do that. Python is a strict language, with a few laziness >>> provided by generators, in the end it's still a strict language. >>> >> >> Yes, it looks like lazy evaluation, but, i don't see why there is not >> a better control over the iterable associated to a generator, even >> with Python that is a strict language, it will increase the >> functionality of it, and the performance too, imagine that you pass a >> function that takes 1 sec in run, and for several reason you can't >> slice before (as the smp function that i want to create), the final >> performance with the actual islice it gets really reduced >> Just creating the separation between those transformation that act on >> the index(islice, or tee) on those that act on the result(dropwhile, >> takewhile, etc.) the control could be fine enough to increase >> usability (that's the way i think right now), and you will be able to >> combine generator without lose performance. > > Theoretically yes, but the semantic of generators in python is they work on > an Iterable (i.e. objects that have __iter__), instead of a Sequence (i.e. > objects that have __getitem__). That means semantically, generators would > call obj.__iter__() and call the iter.__next__() and do its operation for > each items returned by the iterator's iterable's __next__(). > > The lazy semantic would be hard to fit the current generator model without > changing the semantics of generator to require a Sequence that supports > indexing. > Why? The goal is add a formal way to separate the transformation of a generator in those that act on the indexing set and those that act on the result set. Well, a little (and not so elaborated) example could be: from itertools import islice class MyGenerator: def __init__(self, function, indexing_set): self._indexing_set = (x for x in indexing_set) self._function = function def indexing_set(self): return (x for x in self._indexing_set) def result_set(self): return (self._function(x) for x in self.indexing_set()) def function(self): return self._function def f(x): print("eval: %d"%x) return x def myslice(iterable, *args): return MyGenerator(iterable.f, islice(iterable.indexing_set(),*args)) g = MyGenerator(f, xrange(10)) print(list(g.result_set())) g = MyGenerator(f, xrange(10)) new_g = myslice(g,0,None,2) print(list(new_g.result_set())) that returns: eval: 0 eval: 1 eval: 2 eval: 3 eval: 4 eval: 5 eval: 6 eval: 7 eval: 8 eval: 9 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] eval: 0 eval: 2 eval: 4 eval: 6 eval: 8 [0, 2, 4, 6, 8] I don't see why is needed add a sequence to support the indexing, but some separation feature of the base components of the generator (function, indexing_set). >> Yes, it looks like lazy evaluation, but, i don't see why there is not >> a better control over the iterable associated to a generator, even >> with Python that is a strict language > > You can control the laziness by making it explicitly lazy: > > from functools import partial > def f(x): > ? ?print("eval: %d"%x) > ? ?return x > > X = range(10) > g = (partial(f, x) for x in X) > > print(list(x() for x in islice(g,0,None,2))) > # # or without partial: > # g = ((lambda: f(x)) for x in X) > # print(list(f() for f in islice(g,0,None,2))) > I keep here the problem in that i shouldn't be able to define the original generator because the function receive the already defined generator. > In a default-strict language, you have to explicitly say if you want lazy > execution. > >> What i want to do is a function that receive any kind of generator and >> execute it in several cores (after a fork) and return the data, so, i >> can't slice the set X before create the generator. > > beware that a generator's contract is to return a valid iterator *once* > only. You can use itertools.tee() to create more generators, but tee built a > list of the results internally. Oh, yes, i used tee first, but i note then that I wasn't using the same iterator in the same process, so, when the fork is made I can use the initial generator in different processes without this problem, so tee is not necessary in this case. > -- > http://mail.python.org/mailman/listinfo/python-list > -- Jorge Eduardo Cardona jorgeecardona at gmail.com jorgeecardona.blogspot.com ------------------------------------------------ Linux registered user #391186 Registered machine #291871 ------------------------------------------------ From invalid.emal at at.address Tue Dec 8 12:12:58 2009 From: invalid.emal at at.address (Joe) Date: Tue, 08 Dec 2009 11:12:58 -0600 Subject: no module named error In-Reply-To: <7o79huF3l4v9uU1@mid.uni-berlin.de> References: <7o78kuF3p45l7U1@mid.uni-berlin.de> <7o79huF3l4v9uU1@mid.uni-berlin.de> Message-ID: Diez B. Roggisch wrote: > Joe wrote: > >>> But it's searching for _moda.*, most probably a binary extension. Does >>> that exist, and if yes, has it the proper architecture or is it maybe 32 >>> bit? >> I'm just going by an example script. moda is a package I was given that >> is written in C and has some python bindings and does run 64-bit. I'm on >> gentoo. I'm not sure it's installed correctly, but it did come w/ a >> setup.py, and I ran 'setup.py install' and it seemed to have installed >> correctly. >> >> $ sudo python ./setup.py install >> running install >> running build >> running build_py >> running install_lib >> running install_egg_info >> Removing /usr/lib64/python2.6/site-packages/moda-2.1-py2.6.egg-info >> Writing /usr/lib64/python2.6/site-packages/moda-2.1-py2.6.egg-info > > You didn't answer my question. Did it install the _moda.* file the moda.py > is searching for? > > Diez Yeah, that's what I meant when I said the file exists above. There's a moda.py in /usr/lib64/python2.6/site-packages/moda.py. From deets at nospam.web.de Tue Dec 8 12:36:22 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 08 Dec 2009 18:36:22 +0100 Subject: no module named error References: <7o78kuF3p45l7U1@mid.uni-berlin.de> <7o79huF3l4v9uU1@mid.uni-berlin.de> Message-ID: <7o7h4mF3o100mU1@mid.uni-berlin.de> Joe wrote: > Diez B. Roggisch wrote: >> Joe wrote: >> >>>> But it's searching for _moda.*, most probably a binary extension. Does >>>> that exist, and if yes, has it the proper architecture or is it maybe >>>> 32 bit? >>> I'm just going by an example script. moda is a package I was given that >>> is written in C and has some python bindings and does run 64-bit. I'm on >>> gentoo. I'm not sure it's installed correctly, but it did come w/ a >>> setup.py, and I ran 'setup.py install' and it seemed to have installed >>> correctly. >>> >>> $ sudo python ./setup.py install >>> running install >>> running build >>> running build_py >>> running install_lib >>> running install_egg_info >>> Removing /usr/lib64/python2.6/site-packages/moda-2.1-py2.6.egg-info >>> Writing /usr/lib64/python2.6/site-packages/moda-2.1-py2.6.egg-info >> >> You didn't answer my question. Did it install the _moda.* file the >> moda.py is searching for? >> >> Diez > > > Yeah, that's what I meant when I said the file exists above. There's a > moda.py in /usr/lib64/python2.6/site-packages/moda.py. Please, read my post *carefully*. moda.py imports a file _moda.* (most probably _moda.so), which seems *not* to be there. Please verify that it exists and has the proper architecture. This is your output: """ ? ? ? ? File "/usr/lib64/python2.6/site-packages/moda.py", line 7, in ? ? ? ? ? ? import _moda ? ? ? ? ? ? ImportError: No module named _moda """ ^^^^^ _moda, *not* moda. Diez From usenot at geekmail.INVALID Tue Dec 8 12:50:15 2009 From: usenot at geekmail.INVALID (Andreas Waldenburger) Date: Tue, 8 Dec 2009 18:50:15 +0100 Subject: In lista infinita? References: Message-ID: <20091208185015.3d0011e0@geekmail.INVALID> On Tue, 08 Dec 2009 17:39:13 +0100 andrea wrote: > Ho notato che i generatori anche se infiniti non si lamentano se usati > in modo potenzialmente "pericoloso". > [...] > Altri miglioramenti/utilizzi trasversali? Maybe. But I'm sure it.comp.lang.python might help you better. And from the looks of it, you seem to have started a similar thread there (called "Generatori infiniti"). Generally, you'll fare better with English (even broken English will be fine.) in this group. It's just nicer for everyone if they can understand all messages and not feel left out. Anyway, good luck with your question. I didn't understand a whole lot of it, but I guess you want to test for membership in an infinite list/generator. Yes, possible in principle, but obviously eats memory for larger generators. Also, consumes the generators, which is also a factor. /W -- INVALID? DE! From lie.1296 at gmail.com Tue Dec 8 13:07:59 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Wed, 09 Dec 2009 05:07:59 +1100 Subject: IO Gurus: what are the differences between these two methods? In-Reply-To: <75da8a5f-857b-4fab-bfb9-8d03b1cadf1a@u1g2000pre.googlegroups.com> References: <75da8a5f-857b-4fab-bfb9-8d03b1cadf1a@u1g2000pre.googlegroups.com> Message-ID: <4b1e9685@dnews.tpgi.com.au> On 12/8/2009 4:12 AM, dpapathanasiou wrote: > I have two methods for writing binaries files: the first works with > data received by a server corresponding to a file upload, and the > second works with data sent as email attachments. > > The odd thing is, they're not interchangeable: if I use the first one > to saved data parsed from an email attachment, it fails; similarly, > the second function fails when dealing with an uploaded file data. > > What are the critical differences? Those code reeks for refactoring. If you're lucky enough to be in python 2.6 or above, use the io module to wrap the string in second function in a file-like object. From invalid.emal at at.address Tue Dec 8 13:14:55 2009 From: invalid.emal at at.address (Joe) Date: Tue, 08 Dec 2009 12:14:55 -0600 Subject: no module named error In-Reply-To: <7o7h4mF3o100mU1@mid.uni-berlin.de> References: <7o78kuF3p45l7U1@mid.uni-berlin.de> <7o79huF3l4v9uU1@mid.uni-berlin.de> <7o7h4mF3o100mU1@mid.uni-berlin.de> Message-ID: > > Please verify that it exists and has the proper architecture. > Ah, ok, I thought those were one in the same. But I do have that file in another directory elsewhere and I have that directory in my LD_LIBRARY_PATH var. Shouldn't that be enough to do it? From invalid.emal at at.address Tue Dec 8 13:16:10 2009 From: invalid.emal at at.address (Joe) Date: Tue, 08 Dec 2009 12:16:10 -0600 Subject: no module named error In-Reply-To: <7o7h4mF3o100mU1@mid.uni-berlin.de> References: <7o78kuF3p45l7U1@mid.uni-berlin.de> <7o79huF3l4v9uU1@mid.uni-berlin.de> <7o7h4mF3o100mU1@mid.uni-berlin.de> Message-ID: Just to clarify, I have "_moda.la" sitting in another directory which is included in my LD_LIBRARY_PATH. And it is built for the 64bit arch. From deets at nospam.web.de Tue Dec 8 13:24:43 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 08 Dec 2009 19:24:43 +0100 Subject: no module named error References: <7o78kuF3p45l7U1@mid.uni-berlin.de> <7o79huF3l4v9uU1@mid.uni-berlin.de> <7o7h4mF3o100mU1@mid.uni-berlin.de> Message-ID: <7o7jvbF3ojs9uU1@mid.uni-berlin.de> Joe wrote: > Just to clarify, I have "_moda.la" sitting in another directory which is > included in my LD_LIBRARY_PATH. And it is built for the 64bit arch. No, the import-mechanism of python doesn't take LD_LIBRARY_PATH into account, and even if it did - _moda.la is a simple archive-file, not a shared library. It can't be dynamically loaded. Something in your build-process is not working. I suggest you - clean out the source package from everything in there except the original distribution - maybe simply removing & unpacking is the best idea. - build the package again, and post the *full* output. This might give us a clue. Alternatively, if it's possible to share the module, do that. Diez From martin at v.loewis.de Tue Dec 8 13:26:28 2009 From: martin at v.loewis.de (Martin v. Loewis) Date: Tue, 08 Dec 2009 19:26:28 +0100 Subject: Python3: Sane way to deal with broken encodings In-Reply-To: <7o2ibkF3o3ddhU1@mid.dfncis.de> References: <7o2ibkF3o3ddhU1@mid.dfncis.de> Message-ID: > Thus my Python script dies a horrible death: > > File "./update_db", line 67, in > for line in open(tempfile, "r"): > File "/usr/local/lib/python3.1/codecs.py", line 300, in decode > (result, consumed) = self._buffer_decode(data, self.errors, final) > UnicodeDecodeError: 'utf8' codec can't decode byte 0x92 in position > 3286: unexpected code byte > > This is well and ok usually, but I'd like to be able to tell Python: > "Don't worry, some idiot encoded that file, just skip over such > parts/replace them by some character sequence". > > Is that possible? If so, how? As Benjamin says: if you pass errors='replace' to open, then it will replace the faulty characters; if you pass errors='ignore', it will skip over them. Alternatively, you can open the files in binary ('rb'), so that no decoding will be attempted at all, or you can specify latin-1 as the encoding, which means that you can decode all files successfully (though possibly not correctly). Regards, Martin From gagsl-py2 at yahoo.com.ar Tue Dec 8 13:26:38 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 08 Dec 2009 15:26:38 -0300 Subject: Brent's variation of a factorization algorithm References: Message-ID: En Fri, 27 Nov 2009 12:36:29 -0300, n00m escribi?: > Maybe someone'll make use of it: > > > def gcd(x, y): > if y == 0: > return x > return gcd(y, x % y) > > def brent(n): ... A better place to publish this code would be the Python Cookbook: http://code.activestate.com -- Gabriel Genellina From debatem1 at gmail.com Tue Dec 8 13:35:26 2009 From: debatem1 at gmail.com (geremy condra) Date: Tue, 8 Dec 2009 13:35:26 -0500 Subject: Graph library for Python In-Reply-To: <4B1E464B.6090408@chamonix.reportlab.co.uk> References: <4B1CFA36.9060805@egenix.com> <4B1D35BC.5000002@egenix.com> <4B1D5CB3.8030805@egenix.com> <00a70ac5$0$15659$c3e8da3@news.astraweb.com> <4B1E464B.6090408@chamonix.reportlab.co.uk> Message-ID: On Tue, Dec 8, 2009 at 7:27 AM, Robin Becker wrote: > geremy condra wrote: > ........... >> >> I don't have a problem with adding this if there's a strong desire for it, >> but at the moment I'm leaning towards a wait-and-see approach, for >> all the reasons you described. >> >> Geremy Condra > > I don't want to sound pessimistic, but graph and digraph theory has a lot of > history, especially in computer science. Of course it does- the rich set of problem-solving tools provided by theoretical computer science and mathematical graph theory are what make graphs so useful, which is why I'm advocating that they be in the standard library. >There are already very many > implementations eg > > http://code.google.com/p/igraph > http://www.boost.org/doc/libs/release/libs/graph > http://ernst-schroeder.uni.lu/Digraph/doc/ > http://code.google.com/p/python-graph > http://compbio.washington.edu/~zach/py_graph/doc/html/public/py_graph-module.html > > and many others......some of the above already seem to be very useful. I suspect that part of the reason there are so many implementations is because graphs are a) useful and b) not in the standard library. > Is there reason to suppose that any one representation of graphs or digraphs > is so good we need to add it to python? I think there are several implementations that would meet the standards for code quality, and both graphine and python-graph are full-featured, easy to use, pure python graph libraries. Any one of them would be a credit to the standard library. > Even for fairly common algorithms eg Dijkstra's shortest path there doesn't > seem to be complete agreement on how to implement them; for the details of > how nodes/edges/paths should be stored and efficiently manipulated there is > huge variety. Of course there are. Different authors envision different use cases, and select their data structures and algorithms appropriately. That doesn't imply that none of them are appropriate for the common case, which is what we would be targeting here. Geremy Condra From python at mrabarnett.plus.com Tue Dec 8 13:51:29 2009 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 08 Dec 2009 18:51:29 +0000 Subject: Brent's variation of a factorization algorithm In-Reply-To: References: Message-ID: <4B1EA031.9010907@mrabarnett.plus.com> Gabriel Genellina wrote: > En Fri, 27 Nov 2009 12:36:29 -0300, n00m escribi?: > >> Maybe someone'll make use of it: >> >> >> def gcd(x, y): >> if y == 0: >> return x >> return gcd(y, x % y) >> >> def brent(n): ... > > A better place to publish this code would be the Python Cookbook: > http://code.activestate.com > An iterative alternative is: def gcd(x, y): while y != 0: x, y = y, x % y return x From gagsl-py2 at yahoo.com.ar Tue Dec 8 13:55:51 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 08 Dec 2009 15:55:51 -0300 Subject: can someone explain 'super' to me? References: Message-ID: En Sat, 05 Dec 2009 07:27:54 -0300, Michael escribi?: >> From the docs about the built-in function super: > > ---------------------------- > super( type[, object-or-type]) > > Return the superclass of type. [...] You won't get anywhere from the docs in this case, unfortunately. Start by reading these three articles by Michele Simionato: http://www.artima.com/weblogs/viewpost.jsp?thread=236275 and also the famous "Python super() considered harmful": http://fuhm.net/super-harmful/ > It seems like it can return either a class or an instance of a class. > Like > super( C, self) > is like casting self as superclass C. Not really - I hope you'll understand what that means after reading the above articles, feel free to ask again then. > However if you omit the second argument entirely you get a class. Those "unbound" super objects are rare; you probably won't need them. They're discussed in M.S. article, though. -- Gabriel Genellina From victorsubervi at gmail.com Tue Dec 8 14:07:58 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Tue, 8 Dec 2009 15:07:58 -0400 Subject: My Darned Image Again Message-ID: <4dc0cfea0912081107n72fe3a9arbd8f1b0d97c9522f@mail.gmail.com> Hi; I'm having trouble loading my image again. Here's my code: for pic in pics: sql = 'update %s set %s=%s where SKU=%s;' % (store, colNamesPics[i], '%s', sku) sql = sql, (MySQLdb.Binary(pics[int(i)]),) cursor.execute(sql, (MySQLdb.Binary(pics[int(i)]),)) print sql i += 1 Here's the beginning of what it prints to screen: ('update products set pic1=%s where SKU=prodSKU1;', (array('c', '\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x01\x00`\x00`\x00\x00\xff\xdb\x00C\x00\x08\x06\x06\x07\x06\x05\x08\x07\x07\x07\t\t\x08 It throws this error: /var/www/html/angrynates.com/cart/addEdit.py 102 db.commit() 103 cursor.close() 104 105 addEdit() 106 addEdit = /var/www/html/angrynates.com/cart/addEdit.py in addEdit() 88 sql = sql, (MySQLdb.Binary(pics[int(i)]),) 89 print sql 90 cursor.execute(sql, (MySQLdb.Binary(pics[int(i)]),)) 91 i += 1 92 except MySQLdb.IntegrityError: cursor = , cursor.execute = >, sql = ('update products set pic1=%s where SKU=prodSKU1;', (array('c', ['\xff', '\xd8', '\xff', '\xe0', '\x00', ...]),)), global MySQLdb = , MySQLdb.Binary = , pics = ['\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x01\x00`\x00`\x00\x00\xff\xdb\x00C\x00\x08\x06\x06\x07\x06\x05\x08\x07\x07\x07\t\t\x08\n\x0c\x14\r\x0c\x0b\x0b\x0c\x19\x12...f\x0b\xe5\xf9\x8b\xefR\xe7\xa1\xa2\xa3#"+)f8\x08EjZh\xff\x007\xcd\xde\xb5S\xc8\xdb\xf2&\xd3\xe9V!PO\xa5d\xf5W\xb8\xf9-\xb9\xff\xd9'], builtin int = , i = 0 /usr/lib64/python2.4/site-packages/MySQLdb/cursors.py in execute(self=, query=('update products set pic1=%s where SKU=prodSKU1;', (array('c', ['\xff', '\xd8', '\xff', '\xe0', '\x00', ...]),)), args=(array('c', ['\xff', '\xd8', '\xff', '\xe0', '\x00', ...]),)) 144 db = self._get_db() 145 charset = db.character_set_name() 146 query = query.encode(charset) 147 if args is not None: 148 query = query % db.literal(args) query = ('update products set pic1=%s where SKU=prodSKU1;', (array('c', ['\xff', '\xd8', '\xff', '\xe0', '\x00', ...]),)), query.encode undefined, charset = 'latin1' AttributeError: 'tuple' object has no attribute 'encode' args = ("'tuple' object has no attribute 'encode'",) What do? TIA, Victor -------------- next part -------------- An HTML attachment was scrubbed... URL: From irmen at -nospam-xs4all.nl Tue Dec 8 14:25:36 2009 From: irmen at -nospam-xs4all.nl (Irmen de Jong) Date: Tue, 08 Dec 2009 20:25:36 +0100 Subject: Pyro 3.10 released Message-ID: <4b1ea7ed$0$22913$e4fe514c@news.xs4all.nl> Hi, Pyro 3.10 has been released! Pyro is a an advanced and powerful Distributed Object Technology system written entirely in Python, that is designed to be very easy to use. Have a look at http://pyro.sourceforge.net for more information. Highlights of this release are: - improvements in the SSL configuration - uses new-style classes so super() now works in Pyro objects - various minor bugfixes As always the detailed changes are in the changes chapter in the manual. Please read this for more details and info before upgrading. You can download Pyro 3.10 from sourceforge: http://sourceforge.net/projects/pyro or from PyPI http://pypi.python.org/pypi/Pyro/ Enjoy, Irmen de Jong From python at mrabarnett.plus.com Tue Dec 8 14:28:40 2009 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 08 Dec 2009 19:28:40 +0000 Subject: My Darned Image Again In-Reply-To: <4dc0cfea0912081107n72fe3a9arbd8f1b0d97c9522f@mail.gmail.com> References: <4dc0cfea0912081107n72fe3a9arbd8f1b0d97c9522f@mail.gmail.com> Message-ID: <4B1EA8E8.4050706@mrabarnett.plus.com> Victor Subervi wrote: > Hi; > I'm having trouble loading my image again. Here's my code: > > for pic in pics: > sql = 'update %s set %s=%s where SKU=%s;' % (store, colNamesPics[i], '%s', sku) After this, 'sql' will be a string. > sql = sql, (MySQLdb.Binary(pics[int(i)]),) After this, 'sql' will be a tuple. > cursor.execute(sql, (MySQLdb.Binary(pics[int(i)]),)) [snip] You're passing 'sql', which is a tuple, as the query. What was the purpose of the previous line? From dreadpiratejeff at gmail.com Tue Dec 8 14:31:50 2009 From: dreadpiratejeff at gmail.com (J) Date: Tue, 8 Dec 2009 14:31:50 -0500 Subject: Problem using commands.getoutput() Message-ID: <36dec4ff0912081131p74ece048l775afb198570ed14@mail.gmail.com> Reading up on ways to run commands in a shell and capture output... So I was looking at os.exec*() and that's not the correct thing here. If I understand the docs correctly, the os.exec*() functions actually end the calling program and replace it with the program called by os.exec*() even as far as giving the new process the calling process's PID: "These functions all execute a new program, replacing the current process; they do not return. On Unix, the new executable is loaded into the current process, and will have the same process id as the caller. Errors will be reported as OSError exceptions." So from there, I found the commands module and getoutput() which again, if I'm right, is supposed to run a command in a shell, and return the output of that command a string. commands.getoutput() is this: def getstatusoutput(cmd): """Return (status, output) of executing cmd in a shell.""" import os pipe = os.popen('{ ' + cmd + '; } 2>&1', 'r') text = pipe.read() sts = pipe.close() if sts is None: sts = 0 if text[-1:] == '\n': text = text[:-1] return sts, text or at least it calls this function, and returns text, ignorint sts... However, when I try using it, I get this: >>> print commands.getoutput('dir') '{' is not recognized as an internal or external command, operable program or batch file. >>> Which looks like it's choking on the format of the "pipe = os.popen" line, but that's just a guess... because this works: p = os.popen('dir','r') p.read() p.close() So what's the point of the commands module, or is that one that only works in Linux, and not Windows? I can do what I want, I think, by using os.popen(), but I wanted to know if there was a better way of doing it. Cheers, Jeff -- Jonathan Swift - "May you live every day of your life." - http://www.brainyquote.com/quotes/authors/j/jonathan_swift.html From carsten.haese at gmail.com Tue Dec 8 14:34:20 2009 From: carsten.haese at gmail.com (Carsten Haese) Date: Tue, 08 Dec 2009 14:34:20 -0500 Subject: My Darned Image Again In-Reply-To: <4dc0cfea0912081107n72fe3a9arbd8f1b0d97c9522f@mail.gmail.com> References: <4dc0cfea0912081107n72fe3a9arbd8f1b0d97c9522f@mail.gmail.com> Message-ID: Victor Subervi wrote: > Hi; > I'm having trouble loading my image again. Here's my code: > > for pic in pics: > sql = 'update %s set %s=%s where SKU=%s;' % (store, > colNamesPics[i], '%s', sku) > sql = sql, (MySQLdb.Binary(pics[int(i)]),) > cursor.execute(sql, (MySQLdb.Binary(pics[int(i)]),)) > print sql > i += 1 Oh boy, programming by accident strikes again. Your immediate problem is the line <> wherein you're reassigning the name <> to become a 2-tuple consisting of the string formerly known as <> and the 1-tuple containing the picture contents. That line has no business being there. Delete it. There are also some stylistic problems in your code that aren't actually wrong, but they make my toenails curl in horror. Please allow me to improve your code. First of all, you're iterating over <>, and assigning the name <> to each one, but you're not referring to that name anywhere. Instead, you use an artificial index counter (<>), which you're then using to look up the i-th picture. Of course, you need <> to look up the i-th column name. Instead, you should do a parallel iteration that iterates over the column name and the picture simultaneously. Look in my code below for the line containing <> to see how that's done. Also, you should only use string interpolation to build the parts of the query that aren't values. In other words, only the variable table and column names should be put into the query via string interpolation. The sku should be passed as a parameter. Also, you should just use "%%s" to get a literal "%s" through the interpolation step instead of interpolating "%s" into %s markers. Putting all that together, I'd rewrite your code above as follows: for (column_name, pic) in zip(colNamesPics, pics): query = ("update %s set %s = %%s where SKU=%%s" % (store, column_name) ) parameters = (MySQLdb.Binary(pic), sku) cursor.execute(query, parameters) There, that's much less cluttered. HTH, -- Carsten Haese http://informixdb.sourceforge.net From victorsubervi at gmail.com Tue Dec 8 14:41:02 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Tue, 8 Dec 2009 15:41:02 -0400 Subject: My Darned Image Again In-Reply-To: <4B1EA8E8.4050706@mrabarnett.plus.com> References: <4dc0cfea0912081107n72fe3a9arbd8f1b0d97c9522f@mail.gmail.com> <4B1EA8E8.4050706@mrabarnett.plus.com> Message-ID: <4dc0cfea0912081141g68e510e1lb0b3c63cd1ef7d6a@mail.gmail.com> On Tue, Dec 8, 2009 at 3:28 PM, MRAB wrote: > Victor Subervi wrote: > >> Hi; >> I'm having trouble loading my image again. Here's my code: >> >> for pic in pics: >> sql = 'update %s set %s=%s where SKU=%s;' % (store, >> colNamesPics[i], '%s', sku) >> > > After this, 'sql' will be a string. > > > sql = sql, (MySQLdb.Binary(pics[int(i)]),) >> > > After this, 'sql' will be a tuple. > > > cursor.execute(sql, (MySQLdb.Binary(pics[int(i)]),)) >> > [snip] > > You're passing 'sql', which is a tuple, as the query. What was the > purpose of the previous line? > To print stuff out to screen. I don't know what happened, but when I pulled that out, it threw a familiar error that alerted me to quote the last variable (SKU="%s") and the blob went straight in. Thanks! V -------------- next part -------------- An HTML attachment was scrubbed... URL: From malaclypse2 at gmail.com Tue Dec 8 14:44:44 2009 From: malaclypse2 at gmail.com (Jerry Hill) Date: Tue, 8 Dec 2009 14:44:44 -0500 Subject: Problem using commands.getoutput() In-Reply-To: <36dec4ff0912081131p74ece048l775afb198570ed14@mail.gmail.com> References: <36dec4ff0912081131p74ece048l775afb198570ed14@mail.gmail.com> Message-ID: <16651e80912081144k131ab0fcj93e6179e42af64eb@mail.gmail.com> On Tue, Dec 8, 2009 at 2:31 PM, J wrote: > > So what's the point of the commands module, or is that one that only > works in Linux, and not Windows? At the very top of http://docs.python.org/library/commands.html it says "Platforms: Unix", so yes, it's Unix-only. > I can do what I want, I think, by > using os.popen(), but I wanted to know if there was a better way of > doing it. Also at the top of that same bit of documentation is this: "The subprocess module provides more powerful facilities for spawning new processes and retrieving their results. Using the subprocess module is preferable to using the commands module." I would start with http://docs.python.org/library/subprocess.html and http://www.doughellmann.com/PyMOTW/subprocess/ for more information about the subprocess module and how it works. -- Jerry From dreadpiratejeff at gmail.com Tue Dec 8 15:04:13 2009 From: dreadpiratejeff at gmail.com (J) Date: Tue, 8 Dec 2009 15:04:13 -0500 Subject: Problem using commands.getoutput() In-Reply-To: <16651e80912081144k131ab0fcj93e6179e42af64eb@mail.gmail.com> References: <36dec4ff0912081131p74ece048l775afb198570ed14@mail.gmail.com> <16651e80912081144k131ab0fcj93e6179e42af64eb@mail.gmail.com> Message-ID: <36dec4ff0912081204i721a5a3eo2851833b878a5023@mail.gmail.com> On Tue, Dec 8, 2009 at 14:44, Jerry Hill wrote: > At the very top of http://docs.python.org/library/commands.html it > says "Platforms: Unix", so yes, it's Unix-only. That sound you hear is me beating my head against the table now... sigh... I was too wrapped up in reading the actual code to notice the comments... > Also at the top of that same bit of documentation is this: "The > subprocess module provides more powerful facilities for spawning new > processes and retrieving their results. Using the subprocess module is > preferable to using the commands module." > > I would start with http://docs.python.org/library/subprocess.html and > http://www.doughellmann.com/PyMOTW/subprocess/ for more information > about the subprocess module and how it works. And thanks for the pointer to subprocess. I'll read over that (ALL of it) and learn some more... right now I'm doing it just using os.popen() and dumping the read() results to a list, but I'm all for learning different ways of accomplishing the task. I do appreciate the info! Jeff -- Samuel Goldwyn - "I'm willing to admit that I may not always be right, but I am never wrong." - http://www.brainyquote.com/quotes/authors/s/samuel_goldwyn.html From davea at ieee.org Tue Dec 8 15:09:37 2009 From: davea at ieee.org (Dave Angel) Date: Tue, 08 Dec 2009 15:09:37 -0500 Subject: Request for py program to insert space between two characters and saved as text? In-Reply-To: References: <7b87ecb70912071856k10ad366du2b07ce92b94e50e3@mail.gmail.com> Message-ID: <4B1EB281.1050406@ieee.org> r0g wrote: > Dennis Lee Bieber wrote: > >> On Tue, 8 Dec 2009 08:26:58 +0530, 74yrs old >> declaimed the following in gmane.comp.python.general: >> >> >>> For Kannada project .txt(not .doc) is used, my requirement is to have one >>> > > >>> In this context, I request you kindly for small python program - to make or >>> >> Excuse me -- you want one of US to supply you with a program that >> will be used for YOUR entry to some job site? (At least, that's what I >> seem to be finding for "Kannada project") >> >> > > > Well it is only a 2 line program and he did ask nicely after all, if you > begrudge him it then feel free to not answer, righteous indignation > rarely helps anyone. > > Dear OP... > > Put the following 2 lines into a file and save it as spacer.py > > import sys > print ' '.join([e for e in open(sys.argv[1], 'r').read()]) > > > Then open a terminal window and 'cd' to the same folder you just saved > the spacer.py file in. Type... > > python spacer.py inputfile.txt > outputfile.txt > > This will run inputfile.txt through the space adding program we have > just saved and then 'pipe' the output of that into a new file outputfile.txt > > Hope this helps, > > > Roger Heathcote. > > That seems a bit dangerous to give to a beginner at Python, without discussing Unicode issues. If he's in Python 3.x, and if the default encoder is ASCII, which it seems to be most places, then he'll quickly get a conversion error for some character. And if it's some other 8 bit form, he might not get an error, but find that a space is inserted between two of the bytes of a UTF-8 code. DaveA From gagsl-py2 at yahoo.com.ar Tue Dec 8 15:12:30 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 08 Dec 2009 17:12:30 -0300 Subject: Does Python mess with the (unicode) code page? References: Message-ID: En Thu, 03 Dec 2009 15:38:28 -0300, Roy Smith escribi?: > We've got a windows executable which used to get run out of a shell > script > (Cygwin bash) and is now being run with subprocess.Popen(). The windows > app is misbehaving. To make a long story short, the guy who wrote the > code > in question says, > >> it's all based on the return values of the WinAPI calls GetACP and >> GetOEMCP >> [...] so maybe Python is doing something like setting the active code >> page >> and OEM code page prior to the point when they "exec" stuff? > > Does Python do these things? I'm using Python 2.5.1. Not that I know of (also, I don't know of any way to programmatically alter GetACP and GetOEMCP, they're global system settings). A console application should use the console functions GetConsoleCP and GetConsoleOutputCP; Python itself calls them to derive sys.stdin.encoding and sys.stdout.encoding respectively, but only queries the value, never sets it. GetConsoleCP isn't necesarily the same as GetOEMCP. -- Gabriel Genellina From carsten.haese at gmail.com Tue Dec 8 15:21:27 2009 From: carsten.haese at gmail.com (Carsten Haese) Date: Tue, 08 Dec 2009 15:21:27 -0500 Subject: My Darned Image Again In-Reply-To: <4dc0cfea0912081141g68e510e1lb0b3c63cd1ef7d6a@mail.gmail.com> References: <4dc0cfea0912081107n72fe3a9arbd8f1b0d97c9522f@mail.gmail.com> <4B1EA8E8.4050706@mrabarnett.plus.com> <4dc0cfea0912081141g68e510e1lb0b3c63cd1ef7d6a@mail.gmail.com> Message-ID: Victor Subervi wrote: > I don't know what happened, but when I > pulled that out, it threw a familiar error that alerted me to quote the > last variable (SKU="%s") and the blob went straight in. Thanks! The fact that you had to quote the SKU value indicates to me that it's an alphanumeric value (or worse), which means you should really heed the advice I've given in my other response on this thread: Use parameter binding instead of string interpolation to provide the SKU value. That way, regardless of what craziness the SKU value contains, the syntactic integrity of your database query is not in danger. -- Carsten Haese http://informixdb.sourceforge.net From irmen at -nospam-xs4all.nl Tue Dec 8 15:25:54 2009 From: irmen at -nospam-xs4all.nl (Irmen de Jong) Date: Tue, 08 Dec 2009 21:25:54 +0100 Subject: Exception classes don't follow pickle protocol, problems unpickling In-Reply-To: References: <4b1b96e2$0$22938$e4fe514c@news.xs4all.nl> Message-ID: <4b1eb60f$0$22920$e4fe514c@news.xs4all.nl> On 7-12-2009 10:12, Peter Otten wrote: >> So there are 2 problems: the pickle protocol isn't used when exception >> objects (or instances of classes derived from Exception) are pickled, and >> during unpickling, it then >> crashes because it calls __init__ with the wrong amount of parameters. >> (why is it bothering with __init__ anyway? Aren't exceptions new style >> classes?) > > The __reduce__() method is called when you pickle an object. It returns an > argument tuple and a factory. For exceptions that factory is the class which > is why __init__() is called when the object is unpickled. I didn't realize exceptions are treated as "objects pickle know nothing about" (or 'extension types'). They weren't in Python 2.4 at least :) So I was expecting them to follow the pickle protocol for normal Python types, and didn't look past __getnewargs__ and __getinitargs__... >> This started happening in Python 2.5, Python 2.4 works without error. >> >> What is causing this? > > I think Exceptions need special treatment because they have state that is > not stored in the instance __dict__. > >> How can I best solve this error? > > You could override __reduce__() to call __getstate__(). I don't see the need > for __getnewargs__() because exceptions aren't immutable. > > Peter Thanks, that was enlightening. I never had to deal with __reduce__ before :) --irmen From randybelt at gmail.com Tue Dec 8 15:51:07 2009 From: randybelt at gmail.com (Randy Belt) Date: Tue, 8 Dec 2009 15:51:07 -0500 Subject: Trying to set up dictionary to map to functions Message-ID: <5035af300912081251i5cfeaac6s4262999561683595@mail.gmail.com> Hi, I have a small test program written trying to set up a dictionary that points keys to functions. It is working. However, in the process of creating it I noticed a weird problem. The problem is that this IS WORKING and I think it shouldn't be. ~ Here is the input config file code ~ its called config.file and is referenced from the script. [MAPS] relmap = 1 posmap = 1 asnmap = 1 ~ Here is the code that is working but I feel that it shouldn't be ~ import ConfigParser config = ConfigParser.ConfigParser() config.read("config.file") sections = config.sections() print config.options('MAPS') def posmap(): print "posmap function" def relmap(): print "relmap function" def asnmap(): print "asnmap function" for value in config.options('MAPS'): value map_library = { 'posmap': posmap() ,'relmap': relmap() ,'asnmap': asnmap() } ~ Output ~ ['posmap', 'relmap', 'asnmap'] posmap function relmap function asnmap function ~ The reason I'm confused is because when I change the code (Take away the map_library dictionary) import ConfigParser config = ConfigParser.ConfigParser() config.read("config.file") sections = config.sections() print config.options('MAPS') def posmap(): print "posmap function" def relmap(): print "relmap function" def asnmap(): print "asnmap function" for value in config.options('MAPS'): value ~ The output is the following ~ ['posmap', 'relmap', 'asnmap'] Is this defaulting to the dictionary and making it work? In the first set of code I don't reference the map at all but it still seems to know where to look? I am considerably new to Python -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Tue Dec 8 16:02:39 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 08 Dec 2009 18:02:39 -0300 Subject: Fwd: Request for solution References: <7b87ecb70912070809x5d9b9853xdc62ed86759bfe78@mail.gmail.com> <4B1D4903.8010500@acm.org> <7b87ecb70912071659v43739710ma291c142cd6994c2@mail.gmail.com> Message-ID: En Mon, 07 Dec 2009 21:59:42 -0300, 74yrs old escribi?: >> For Kannada project .txt(not .doc) is used, my requirement is to have >> one space between two characters in Notepad file. In MSword there is >> provision to make space between two characters under "Font" and can be >> saved as _.doc_ But when tried to save as_ .txt_ all formatting will >> disappear. I could not understand how to do in notepad. Even tried copy >> and paste from doc to notepad but failed. >> >> In this context, I request you kindly for small Python program - to make >> or insert space between two characters in the _text_ file. (I have >> installed Fedora-11 and also ubuntu9.04) >> >> example: *F o r K a n n a d a p r o j e c t . t x t(n o t .d o c) i >> s u s e d, m y r e q u i r e m e n t i s t o h a v e o n e s p >> a c e b e t w e e n t w o c h a r a c t e r s i n t h e t e x t.* Suppose you have the desided text in a string: py> txt = """For Kannada project .txt(not .doc) is used, ... my requirement is to have ... one space between two characters in Notepad file.""" You can insert one space between each caracter by using: py> " ".join(txt) 'F o r K a n n a d a p r o j e c t . t x t ( n o t . d o c ) i s u s e d , \n m y r e q u i r e m e n t i s t o h a v e \n o n e s p a c e b e t w e e n t w o c h a r a c t e r s i n N o t e p a d f i l e .' and then write the resulting text into a file as usual. -- Gabriel Genellina From __peter__ at web.de Tue Dec 8 16:54:24 2009 From: __peter__ at web.de (Peter Otten) Date: Tue, 08 Dec 2009 22:54:24 +0100 Subject: Trying to set up dictionary to map to functions References: <5035af300912081251i5cfeaac6s4262999561683595@mail.gmail.com> Message-ID: Randy Belt wrote: > I have a small test program written trying to set up a dictionary that > points keys to functions. It is working. However, in the process of > creating it I noticed a weird problem. The problem is that this IS > WORKING and I think it shouldn't be. > > ~ Here is the input config file code ~ its called config.file and is > referenced from the script. > > [MAPS] > relmap = 1 > posmap = 1 > asnmap = 1 > > ~ Here is the code that is working but I feel that it shouldn't be ~ > > import ConfigParser > config = ConfigParser.ConfigParser() > config.read("config.file") > sections = config.sections() > print config.options('MAPS') > def posmap(): > print "posmap function" > def relmap(): > print "relmap function" > def asnmap(): > print "asnmap function" > for value in config.options('MAPS'): > value > map_library = { > 'posmap': posmap() > ,'relmap': relmap() > ,'asnmap': asnmap() > } I can only guess what you are trying to do here. A dictionary like d = {"key": func()} is equivaluent to value = func() d = {"key": value} i. e. you put the function's result into the dict, not the function itself. You can verify that for your program -- if you remove one of the three entries from the config file it will still invoke all three functions. If you want the config file to control which functions should be invoke change your code as follows: map_library = {"posmap": posmap, "relmap": relmap, "asnmap": asnmap} for value in config.options("MAPS"): map_library[value]() Peter From pavlovevidence at gmail.com Tue Dec 8 16:58:49 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Tue, 8 Dec 2009 13:58:49 -0800 (PST) Subject: Graph library for Python References: <4B18F685.8050102@egenix.com> <4B1CFA36.9060805@egenix.com> <4B1D35BC.5000002@egenix.com> <4B1D5CB3.8030805@egenix.com> <00a70ac5$0$15659$c3e8da3@news.astraweb.com> Message-ID: <9d122b56-e5ba-4e4e-95fc-5bcd807c91b7@e4g2000prn.googlegroups.com> On Dec 8, 4:27?am, Robin Becker wrote: > Is there reason to suppose that any one representation of graphs or digraphs is > so good we need to add it to python? One of them bothered to write a PEP proposing its inclusion? > Even for fairly common algorithms eg Dijkstra's shortest path there doesn't seem > to be complete agreement on how to implement them; for the details of how > nodes/edges/paths should be stored and efficiently manipulated there is huge > variety. > > Wait seems like a good policy. Geremy's team seems to balance open-mindedness with not being a pushover quite well; given this, and that they took initiative, I am satisfied that they will do a good job designing it for the general case. Also, "Now is better than never." (And before anyone gives the obvious retort, please consider if you really think it's happening "right now".) Carl Banks From gagsl-py2 at yahoo.com.ar Tue Dec 8 17:02:52 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 08 Dec 2009 19:02:52 -0300 Subject: hola References: <4f981bd80912061429g77b0bd66r617950b5d35e1caa@mail.gmail.com> <50697b2c0912061448w78bdecbci4cf38b9123bf403b@mail.gmail.com> Message-ID: En Sun, 06 Dec 2009 19:48:28 -0300, Chris Rebert escribi?: > 2009/12/6 franki fuentes cueto : >> hola soy un peque?o programador y quiesiera pedirles ayuda para >> programar en >> python, no se si me podrian mandar ejemplos para poder empezar, y como >> terminarlo para que se ejecute, me entiendes , aver sime ayudan gracias > > Esta lista de discusi?n es en Ingl?s. > > Hay una lista de discusi?n en Espa?ol aqui: > http://listas.aditel.org/listinfo/python-es Y tambi?n: http://news.gmane.org/gmane.org.user-groups.python.argentina/ -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Tue Dec 8 17:02:52 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 08 Dec 2009 19:02:52 -0300 Subject: hola References: <4f981bd80912061429g77b0bd66r617950b5d35e1caa@mail.gmail.com> <50697b2c0912061448w78bdecbci4cf38b9123bf403b@mail.gmail.com> Message-ID: En Sun, 06 Dec 2009 19:48:28 -0300, Chris Rebert escribi?: > 2009/12/6 franki fuentes cueto : >> hola soy un peque?o programador y quiesiera pedirles ayuda para >> programar en >> python, no se si me podrian mandar ejemplos para poder empezar, y como >> terminarlo para que se ejecute, me entiendes , aver sime ayudan gracias > > Esta lista de discusi?n es en Ingl?s. > > Hay una lista de discusi?n en Espa?ol aqui: > http://listas.aditel.org/listinfo/python-es Y tambi?n: http://news.gmane.org/gmane.org.user-groups.python.argentina/ -- Gabriel Genellina From davea at ieee.org Tue Dec 8 17:17:20 2009 From: davea at ieee.org (Dave Angel) Date: Tue, 08 Dec 2009 17:17:20 -0500 Subject: Trying to set up dictionary to map to functions In-Reply-To: <5035af300912081251i5cfeaac6s4262999561683595@mail.gmail.com> References: <5035af300912081251i5cfeaac6s4262999561683595@mail.gmail.com> Message-ID: <4B1ED070.2030408@ieee.org> Randy Belt wrote: > Hi, > > I have a small test program written trying to set up a dictionary that > points keys to functions. It is working. However, in the process of > creating it I noticed a weird problem. The problem is that this IS WORKING > and I think it shouldn't be. > > ~ Here is the input config file code ~ its called config.file and is > referenced from the script. > > [MAPS] > relmap = 1 > posmap = 1 > asnmap = 1 > > ~ Here is the code that is working but I feel that it shouldn't be ~ > > import ConfigParser > config = ConfigParser.ConfigParser() > config.read("config.file") > sections = config.sections() > print config.options('MAPS') > def posmap(): > print "posmap function" > def relmap(): > print "relmap function" > def asnmap(): > print "asnmap function" > for value in config.options('MAPS'): > value > map_library = { > 'posmap': posmap() > ,'relmap': relmap() > ,'asnmap': asnmap() > } > > ~ Output ~ > > ['posmap', 'relmap', 'asnmap'] > posmap function > relmap function > asnmap function > > ~ The reason I'm confused is because when I change the code (Take away the > map_library dictionary) > > import ConfigParser > config = ConfigParser.ConfigParser() > config.read("config.file") > sections = config.sections() > print config.options('MAPS') > def posmap(): > print "posmap function" > def relmap(): > print "relmap function" > def asnmap(): > print "asnmap function" > for value in config.options('MAPS'): > value > > ~ The output is the following ~ > > ['posmap', 'relmap', 'asnmap'] > > Is this defaulting to the dictionary and making it work? In the first set > of code I don't reference the map at all but it still seems to know where to > look? I am considerably new to Python > > I don't blame you for being confused. You're doing two things wrong which has the side effect of making it seem to be working. The reason it isn't obvious is that you happen to use the same ordering in your config.file as you use initializing map_library. Your initialization code for map_library is incorrect. You're actually calling each of those three functions during that line, and they each do their printing. However, this has nothing to do with the entries in config.options. If you want to be really surprised, try printing map_libary. It should have values of None for each of the three keys. I suggest you move the three defs and the map_library initialization near the beginning of your script (just after the imports). Precede it with an import sys, and follow it with a sys.exit(0), and run just that portion. You'll see that it prints out the three lines already. What you actually want is not to execute each function, but to create each function object. So change the line as follows: map_library = { 'posmap': posmap ,'relmap': relmap ,'asnmap': asnmap } Note that I don't use parentheses, so the functions are not executing yet. Now (when you remove the sys.exit()), let's look at your for-loop. For each item in the list, you do exactly nothing. That's probably where you want to be calling the elements of map_library. And since we moved its initialization earlier, we can actually do that, as I'm sure you were about to do. DaveA From gagsl-py2 at yahoo.com.ar Tue Dec 8 17:22:44 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 08 Dec 2009 19:22:44 -0300 Subject: How to create a docstring for a module? References: <26662729.post@talk.nabble.com> <20091206105550.16570a30@geekmail.INVALID> <00a50dbe$0$15659$c3e8da3@news.astraweb.com> <26668758.post@talk.nabble.com> <50697b2c0912061306i29d5faf9q9c25357c85652e44@mail.gmail.com> Message-ID: En Sun, 06 Dec 2009 23:51:30 -0300, alex23 escribi?: > "Phillip M. Feldman" wrote: >> It does seem as though IPython could be a bit more clever about this. > > I disagree. I _like_ that IPython is only reporting on the current > state of the interpreter and not trying to second guess what I meant. > >> If the user asks for documentation on xyz via "?xyz" and xyz is not >> defined, then I'd like to see IPython check for a module named "xyz" and >> if it exists, extract and display the docstring. > > How would you recommend IPython distinguish between which "xyz" you > meant: the one in site-packages, the one in some package on the python > path, or the one in the folder you're running IPython from? The "xyz" that would be imported by executing "import xyz", I'd say. The standard interpreter does that: Python 2.6.4 (r264:75708, Oct 26 2009, 08:23:19) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more in formation. py> help("poplib") Help on module poplib: NAME poplib - A POP3 client class. ... -- Gabriel Genellina From rhodri at wildebst.demon.co.uk Tue Dec 8 20:42:53 2009 From: rhodri at wildebst.demon.co.uk (Rhodri James) Date: Wed, 09 Dec 2009 01:42:53 -0000 Subject: Graph library for Python In-Reply-To: References: <4B18F685.8050102@egenix.com> <4B1CFA36.9060805@egenix.com> <4B1D35BC.5000002@egenix.com> <4B1D5CB3.8030805@egenix.com> <4B1D8FB1.5010703@egenix.com> Message-ID: On Tue, 08 Dec 2009 04:28:05 -0000, geremy condra wrote: > On Mon, Dec 7, 2009 at 6:28 PM, M.-A. Lemburg wrote: >> I wasn't thinking of anything clever :-) ... >> >> g = Graph( >> [Node("a"), Node("b"), Node("c")], >> [Edge(Node("a"), Node("b"), "ab"), >> Edge(Node("a"), Node("c"), "ac"), >> Edge(Node("b"), Node("c"), "bc"), >> ]) >> >> The main motivation here is to get lists, sets and dicts >> play nice together. > > Generally, we've tried to discourage people from instantiating > nodes and edges directly, in favor of having them controlled > through the graph. Maybe something along the lines of: > > g = Graph(nodes=['a', 'b', 'c'], edges=[('a', 'b'), ('a', 'c'), ('b', > 'c')]) > > ? That works fine for simple cases like this, but starts getting unpleasant if you want to initialise with attributes. Under those circumstances using Node and Edge explicitly is much cleaner. The only extra I'd suggest is allowing is_directed as a keyword argument, so you can set the default for all edges if you want to. g = Graph( nodes=[Node("a", colour="red"), Node("b", colour="white"), Node("c", colour="blue")], edges=[Edge("a", "b", "ab", weight=2), Edge("a", "c", "ac", is_directed=True), Edge("b", "c", "bc", style="dotted")], is_directed=True) I could see a use for this tracking a database structure using a constant graph, hence all set up in one go for preference. -- Rhodri James *-* Wildebeest Herder to the Masses From lie.1296 at gmail.com Tue Dec 8 20:52:46 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Wed, 09 Dec 2009 12:52:46 +1100 Subject: Generators. In-Reply-To: References: <4b1c8cc3$1@dnews.tpgi.com.au> <4b1e0617@dnews.tpgi.com.au> Message-ID: <4b1f0374$1@dnews.tpgi.com.au> On 12/9/2009 3:52 AM, Jorge Cardona wrote: > 2009/12/8 Lie Ryan: >> First, I apologize for rearranging your message out of order. >> >> Theoretically yes, but the semantic of generators in python is they work on >> an Iterable (i.e. objects that have __iter__), instead of a Sequence (i.e.. >> objects that have __getitem__). That means semantically, generators would >> call obj.__iter__() and call the iter.__next__() and do its operation for >> each items returned by the iterator's iterable's __next__(). >> >> The lazy semantic would be hard to fit the current generator model without >> changing the semantics of generator to require a Sequence that supports >> indexing. >> > > Why? > > The goal is add a formal way to separate the transformation of a > generator in those that act on the indexing set and those that act on > the result set. Well, that's just a pretty convoluted way to reverse the order of the operation (hey, why not reverse it altogether?). Nevertheless, it still requires a semantic change in that all generators must be able to produce the underlying stream, which is not always the case. Take this small example: def foo(x): i = 0 while True: yield i i += 1 What would you propose the .indexing_set to be? Surely not the same as .result_set? How would you propose to skip over and islice such generator? without executing the in-betweens? >> from functools import partial >> def f(x): >> print("eval: %d"%x) >> return x >> >> X = range(10) >> g = (partial(f, x) for x in X) >> >> print(list(x() for x in islice(g,0,None,2))) >> # # or without partial: >> # g = ((lambda: f(x)) for x in X) >> # print(list(f() for f in islice(g,0,None,2))) >> > > I keep here the problem in that i shouldn't be able to define the > original generator because the function receive the already defined > generator. > >> In a default-strict language, you have to explicitly say if you want lazy >> execution. >> >>> What i want to do is a function that receive any kind of generator and >>> execute it in several cores (after a fork) and return the data, so, i >>> can't slice the set X before create the generator. >> >> beware that a generator's contract is to return a valid iterator *once* >> only. You can use itertools.tee() to create more generators, but tee built a >> list of the results internally. > > Oh, yes, i used tee first, but i note then that I wasn't using the > same iterator in the same process, so, when the fork is made I can > use the initial generator in different processes without this problem, > so tee is not necessary in this case. You would have to change tee as well: >>> import itertools >>> def foo(x): ... print('eval: %s' % x) ... return x + 1 ... >>> l = [1, 2, 3, 4, 5, 6, 7] >>> it = iter(l) >>> it = (foo(x) for x in it) >>> a, b = itertools.tee(it) >>> # now on to you >>> it_a = itertools.islice(a, 0, None, 2) >>> it_b = itertools.islice(b, 1, None, 2) >>> next(it_b) eval: 1 eval: 2 3 >>> next(it_b) eval: 3 eval: 4 5 >>> next(it_b) eval: 5 eval: 6 7 From henryzhang62 at yahoo.com Tue Dec 8 20:53:56 2009 From: henryzhang62 at yahoo.com (hong zhang) Date: Tue, 8 Dec 2009 17:53:56 -0800 (PST) Subject: switch Message-ID: <335204.99872.qm@web57905.mail.re3.yahoo.com> List, Python does not have switch statement. Any other option does similar work? Thanks for help. --henry From clp2 at rebertia.com Tue Dec 8 20:57:38 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 8 Dec 2009 17:57:38 -0800 Subject: switch In-Reply-To: <335204.99872.qm@web57905.mail.re3.yahoo.com> References: <335204.99872.qm@web57905.mail.re3.yahoo.com> Message-ID: <50697b2c0912081757yaeaa95fs82a6292e81a0d3fd@mail.gmail.com> On Tue, Dec 8, 2009 at 5:53 PM, hong zhang wrote: > Python does not have switch statement. Any other option does similar work? Yes, a dictionary with functions as values: http://simonwillison.net/2004/May/7/switch/ Cheers, Chris -- http://blog.rebertia.com From benjamin.kaplan at case.edu Tue Dec 8 21:00:59 2009 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Tue, 8 Dec 2009 21:00:59 -0500 Subject: switch In-Reply-To: <335204.99872.qm@web57905.mail.re3.yahoo.com> References: <335204.99872.qm@web57905.mail.re3.yahoo.com> Message-ID: On Tue, Dec 8, 2009 at 8:53 PM, hong zhang wrote: > List, > > Python does not have switch statement. Any other option does similar work? > Thanks for help. > Use a dict instead, where the keys are the different cases and the values are usually callable objects (such as functions) options = {"a" : do_a, "b",do_b, "c", do_c} option = "a" try : options[option]() except KeyError : do_default() > --henry > > > > -- > http://mail.python.org/mailman/listinfo/python-list > From rzzzwilson at gmail.com Tue Dec 8 21:07:04 2009 From: rzzzwilson at gmail.com (rzzzwilson) Date: Tue, 8 Dec 2009 18:07:04 -0800 (PST) Subject: switch References: <335204.99872.qm@web57905.mail.re3.yahoo.com> Message-ID: On Dec 9, 1:00?pm, Benjamin Kaplan wrote: > On Tue, Dec 8, 2009 at 8:53 PM, hong zhang wrote: > > List, > > > Python does not have switch statement. Any other option does similar work? > > Thanks for help. > > Use a dict instead, where the keys are the different cases and the > values are usually callable objects (such as functions) > options = {"a" : do_a, "b",do_b, "c", do_c} > > option = "a" > > try : > ? ? options[option]() > except KeyError : > ? ? do_default() > > > --henry > > > -- > >http://mail.python.org/mailman/listinfo/python-list > > Even better (well, shorter!): options = {"a" : do_a, "b",do_b, "c", do_c} options.get(option, do_default)() Ross From zephjc at gmail.com Tue Dec 8 22:24:20 2009 From: zephjc at gmail.com (zeph) Date: Tue, 8 Dec 2009 19:24:20 -0800 (PST) Subject: switch References: <335204.99872.qm@web57905.mail.re3.yahoo.com> Message-ID: <9580bd0a-9651-4188-a788-efef1f71bfa6@u25g2000prh.googlegroups.com> > > Even better (well, shorter!): > options = {"a" : do_a, "b",do_b, "c", do_c} > options.get(option, do_default)() > You can also make it something callable like so, which is a little more compact if you need to reuse it a lot: >>> def do_a(x): print "a:", x ... >>> def do_b(x): print "b:", x ... >>> def do_c(x): print "c:", x ... >>> do_something = {"a":do_a, "b":do_b, "c": do_c}.get >>> do_something('a')(4) a: 4 >>> do_something('c')(5) c: 5 >>> do_something >>> do_something('d') >>> do_something('d')(5) Traceback (most recent call last): File "", line 1, in TypeError: 'NoneType' object is not callable From aioe.org at technicalbloke.com Tue Dec 8 22:26:22 2009 From: aioe.org at technicalbloke.com (r0g) Date: Wed, 09 Dec 2009 03:26:22 +0000 Subject: Request for py program to insert space between two characters and saved as text? References: <7b87ecb70912071856k10ad366du2b07ce92b94e50e3@mail.gmail.com> Message-ID: Dave Angel wrote: > > > r0g wrote: >> Dennis Lee Bieber wrote: >> >>> On Tue, 8 Dec 2009 08:26:58 +0530, 74yrs old >>> declaimed the following in gmane.comp.python.general: >>> >>> >>>> For Kannada project .txt(not .doc) is used, my requirement is to >>>> have one >>>> >> >> >>>> In this context, I request you kindly for small python program - to >>>> make or >>>> >>> Excuse me -- you want one of US to supply you with a program that >>> will be used for YOUR entry to some job site? (At least, that's what I >>> seem to be finding for "Kannada project") >>> >>> >> >> >> Well it is only a 2 line program and he did ask nicely after all, if you >> begrudge him it then feel free to not answer, righteous indignation >> rarely helps anyone. >> >> Dear OP... >> >> Put the following 2 lines into a file and save it as spacer.py >> >> import sys >> print ' '.join([e for e in open(sys.argv[1], 'r').read()]) >> >> >> Then open a terminal window and 'cd' to the same folder you just saved >> the spacer.py file in. Type... >> >> python spacer.py inputfile.txt > outputfile.txt >> >> This will run inputfile.txt through the space adding program we have >> just saved and then 'pipe' the output of that into a new file >> outputfile.txt >> >> Hope this helps, >> >> >> Roger Heathcote. >> >> > That seems a bit dangerous to give to a beginner at Python, without > discussing Unicode issues. If he's in Python 3.x, and if the default > encoder is ASCII, which it seems to be most places, then he'll quickly > get a conversion error for some character. And if it's some other 8 bit > form, he might not get an error, but find that a space is inserted > between two of the bytes of a UTF-8 code. > > DaveA > He said he's running the latest python and fedora, AFAIK the default for these systems is still the 2 series, not 3. Roger. From debatem1 at gmail.com Tue Dec 8 22:47:03 2009 From: debatem1 at gmail.com (geremy condra) Date: Tue, 8 Dec 2009 22:47:03 -0500 Subject: Graph library for Python In-Reply-To: References: <4B1CFA36.9060805@egenix.com> <4B1D35BC.5000002@egenix.com> <4B1D5CB3.8030805@egenix.com> <4B1D8FB1.5010703@egenix.com> Message-ID: On Tue, Dec 8, 2009 at 8:42 PM, Rhodri James wrote: > On Tue, 08 Dec 2009 04:28:05 -0000, geremy condra > wrote: > >> On Mon, Dec 7, 2009 at 6:28 PM, M.-A. Lemburg wrote: > >>> I wasn't thinking of anything clever :-) ... >>> >>> g = Graph( >>> ? ? [Node("a"), Node("b"), Node("c")], >>> ? ? [Edge(Node("a"), Node("b"), "ab"), >>> ? ? ?Edge(Node("a"), Node("c"), "ac"), >>> ? ? ?Edge(Node("b"), Node("c"), "bc"), >>> ? ? ]) >>> >>> The main motivation here is to get lists, sets and dicts >>> play nice together. >> >> Generally, we've tried to discourage people from instantiating >> nodes and edges directly, in favor of having them controlled >> through the graph. Maybe something along the lines of: >> >> g = Graph(nodes=['a', 'b', 'c'], edges=[('a', 'b'), ('a', 'c'), ('b', >> 'c')]) >> >> ? > > That works fine for simple cases like this, but starts getting unpleasant if > you want to initialise with attributes. ?Under those circumstances using > Node and Edge explicitly is much cleaner. ?The only extra I'd suggest is > allowing is_directed as a keyword argument, so you can set the default for > all edges if you want to. > > g = Graph( > ? ?nodes=[Node("a", colour="red"), > ? ? ? ? ? Node("b", colour="white"), > ? ? ? ? ? Node("c", colour="blue")], > ? ?edges=[Edge("a", "b", "ab", weight=2), > ? ? ? ? ? Edge("a", "c", "ac", is_directed=True), > ? ? ? ? ? Edge("b", "c", "bc", style="dotted")], > ? ?is_directed=True) > > I could see a use for this tracking a database structure using a constant > graph, hence all set up in one go for preference. While I agree with the rationale, I think we need to find another way. Aesthetics aside, directly instantiating edges by giving only node names requires that the edge be aware of what graph its in to provide expected behavior, which creates a bit of a chicken-or-the-egg dilemma. How about this: the constructor can take any type of iterable, and assumes that it follows my earlier format unless it specifies a .items() method, in which case it takes the values as follows: g = Graph( nodes={'a':{'colour':'red'}, 'b':{'colour':'white'}, 'c':{'colour':'blue'}}, edges={('a', 'b'):{'name':'ab', 'weight':2}, ('a', 'c'):{'name':'ac'}, ('b', 'c'):{'name':'bc', 'style':'dotted'}} ) Geremy Condra From kee at kagi.com Wed Dec 9 00:02:44 2009 From: kee at kagi.com (Kee Nethery) Date: Tue, 8 Dec 2009 21:02:44 -0800 Subject: switch In-Reply-To: <335204.99872.qm@web57905.mail.re3.yahoo.com> References: <335204.99872.qm@web57905.mail.re3.yahoo.com> Message-ID: I string together a bunch of elif statements to simulate a switch if foo == True: blah elif bar == True: blah blah elif bar == False: blarg elif .... From afriere at yahoo.co.uk Wed Dec 9 00:36:23 2009 From: afriere at yahoo.co.uk (Asun Friere) Date: Tue, 8 Dec 2009 21:36:23 -0800 (PST) Subject: switch References: <335204.99872.qm@web57905.mail.re3.yahoo.com> Message-ID: On Dec 9, 4:02?pm, Kee Nethery wrote: > I string together a bunch of elif statements to simulate a switch > > if foo == True: > ? ? ? ? blah > elif bar == True: > ? ? ? ? blah blah > elif bar == False: > ? ? ? ? blarg > elif .... This code is probably symptomatic of poor design. (Not to mention that your condition tests). For which reason python has no 'case' statement and why no decent OO language should. It is a principle of OO design that "an object should know what to do itself." Rather running an object though a series of tests, it is better to send the object a message, relying on polymorphism or duck- typing, and deal with any exceptions thrown. Generally if you find yourself wanting to use a 'case' statement or writing a series of if/elif which involves more than say, three, elifs, condsider whether you cannot use a double dispatch mechanism instead. From gagsl-py2 at yahoo.com.ar Wed Dec 9 00:53:20 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 09 Dec 2009 02:53:20 -0300 Subject: Brent's variation of a factorization algorithm References: <4B1EA031.9010907@mrabarnett.plus.com> Message-ID: En Tue, 08 Dec 2009 15:51:29 -0300, MRAB escribi?: > Gabriel Genellina wrote: >> En Fri, 27 Nov 2009 12:36:29 -0300, n00m escribi?: >> >>> def gcd(x, y): >>> if y == 0: >>> return x >>> return gcd(y, x % y) >>> >>> def brent(n): ... >> A better place to publish this code would be the Python Cookbook: >> http://code.activestate.com >> > An iterative alternative is: > > def gcd(x, y): > while y != 0: > x, y = y, x % y > return x (note that the interesting part was the snipped code, the brent() function...) -- Gabriel Genellina From steven at REMOVE.THIS.cybersource.com.au Wed Dec 9 01:12:15 2009 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 09 Dec 2009 06:12:15 GMT Subject: switch References: <335204.99872.qm@web57905.mail.re3.yahoo.com> Message-ID: On Tue, 08 Dec 2009 21:02:44 -0800, Kee Nethery wrote: > I string together a bunch of elif statements to simulate a switch > > if foo == True: > blah > elif bar == True: > blah blah > elif bar == False: > blarg > elif .... Are you sure you want to test for equality with True and False? Generally one should write that as: if foo: blah elif bar: blah blah elif not bar: blarg ... -- Steven From davea at ieee.org Wed Dec 9 01:37:15 2009 From: davea at ieee.org (Dave Angel) Date: Wed, 09 Dec 2009 01:37:15 -0500 Subject: Request for py program to insert space between two characters and saved as text? In-Reply-To: References: <7b87ecb70912071856k10ad366du2b07ce92b94e50e3@mail.gmail.com> Message-ID: <4B1F459B.9090706@ieee.org> r0g wrote: > Dave Angel wrote: > >> r0g wrote: >> >>> Dennis Lee Bieber wrote: >>> >>> >>>> On Tue, 8 Dec 2009 08:26:58 +0530, 74yrs old >>>> declaimed the following in gmane.comp.python.general: >>>> >>>> >>>> >>>>> For Kannada project .txt(not .doc) is used, my requirement is to >>>>> have one >>>>> >>>>> >>> >>> >>> >>>>> In this context, I request you kindly for small python program - to >>>>> make or >>>>> >>>>> >>>> Excuse me -- you want one of US to supply you with a program that >>>> will be used for YOUR entry to some job site? (At least, that's what I >>>> seem to be finding for "Kannada project") >>>> >>>> >>>> >>> Well it is only a 2 line program and he did ask nicely after all, if you >>> begrudge him it then feel free to not answer, righteous indignation >>> rarely helps anyone. >>> >>> Dear OP... >>> >>> Put the following 2 lines into a file and save it as spacer.py >>> >>> import sys >>> print ' '.join([e for e in open(sys.argv[1], 'r').read()]) >>> >>> >>> Then open a terminal window and 'cd' to the same folder you just saved >>> the spacer.py file in. Type... >>> >>> python spacer.py inputfile.txt > outputfile.txt >>> >>> This will run inputfile.txt through the space adding program we have >>> just saved and then 'pipe' the output of that into a new file >>> outputfile.txt >>> >>> Hope this helps, >>> >>> >>> Roger Heathcote. >>> >>> >>> >> That seems a bit dangerous to give to a beginner at Python, without >> discussing Unicode issues. If he's in Python 3.x, and if the default >> encoder is ASCII, which it seems to be most places, then he'll quickly >> get a conversion error for some character. And if it's some other 8 bit >> form, he might not get an error, but find that a space is inserted >> between two of the bytes of a UTF-8 code. >> >> DaveA >> >> > > > > He said he's running the latest python and fedora, AFAIK the default for > these systems is still the 2 series, not 3. > > > Roger. > > That's even worse. As far as I can tell, the code will never do what he wants in Python 2.x. The Kannada text file is full of Unicode characters in some encoding, and if you ignore the encoding, you'll just get garbage. From steven at REMOVE.THIS.cybersource.com.au Wed Dec 9 01:39:48 2009 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 09 Dec 2009 06:39:48 GMT Subject: switch References: <335204.99872.qm@web57905.mail.re3.yahoo.com> Message-ID: On Tue, 08 Dec 2009 21:36:23 -0800, Asun Friere wrote: > On Dec 9, 4:02?pm, Kee Nethery wrote: >> I string together a bunch of elif statements to simulate a switch >> >> if foo == True: >> ? ? ? ? blah >> elif bar == True: >> ? ? ? ? blah blah >> elif bar == False: >> ? ? ? ? blarg >> elif .... > > > This code is probably symptomatic of poor design. (Not to mention that > your condition tests). For which reason python has no 'case' statement > and why no decent OO language should. That's a provocative statement. > It is a principle of OO design that "an object should know what to do > itself." Rather running an object though a series of tests, it is > better to send the object a message, relying on polymorphism or duck- > typing, and deal with any exceptions thrown. Perhaps that's true, but you'll note that the example given above doesn't run a single object through a series of tests, but runs a series of tests on DIFFERENT objects, to find the first which matches. But putting that aside, I find myself wondering how you would deal with the following switch-like series of tests. def print_grades(score): if not 0 <= score <= 100: raise ValueError("score must be between 0 and 100") if score < 50: print "You have failed." consider_suspension() elif score == 50: print "You have just passed by the skin of your teeth." elif score < 60: print "You have scored a D. You need to try harder." elif score < 70: print "You have scored a C." elif score < 80: print "You have scored a B. Well done." elif score < 100: print "Congratulations, you have scored an A." else: assert score == 100 print "You have scored a PERFECT 100% SCORE!!!" if not evidence_of_cheating(): call_newspapers() Obviously that could, with a non-trivial amount of work, be turned into a dictionary dispatch, but is the benefit worth the extra effort? > Generally if you find yourself wanting to use a 'case' statement or > writing a series of if/elif which involves more than say, three, elifs, > condsider whether you cannot use a double > dispatch mechanism instead. I don't see how a series of tests on a single object is comparable to the double-dispatch example given. -- Steven From afriere at yahoo.co.uk Wed Dec 9 01:43:54 2009 From: afriere at yahoo.co.uk (Asun Friere) Date: Tue, 8 Dec 2009 22:43:54 -0800 (PST) Subject: switch References: <335204.99872.qm@web57905.mail.re3.yahoo.com> Message-ID: On Dec 9, 5:12?pm, Steven D'Aprano wrote: > On Tue, 08 Dec 2009 21:02:44 -0800, Kee Nethery wrote: > > I string together a bunch of elif statements to simulate a switch > > > if foo == True: > > ? ?blah > > elif bar == True: > > ? ?blah blah > > elif bar == False: > > ? ?blarg > > elif .... > > Are you sure you want to test for equality with True and False? Generally > one should write that as: > > if foo: > ? ? blah > elif bar: > ? ? blah blah > elif not bar: > ? ? blarg > ... > > -- > Steven I was going to point that out, but thought it a little OT. One might also mention that testing for "if foo is None :" is a special case. I'm also having a bit of a problem imagining what the subsequent conditions must be which make testing "elif not bar" subsequent to testing "elif bar" necessary, but that's just me. Back OT, one would hope not to encounter python code with a long chain of elifs like that. Probably the design should be improved, or where this would be overkill, use the dictionary trick. From gagsl-py2 at yahoo.com.ar Wed Dec 9 02:09:24 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 09 Dec 2009 04:09:24 -0300 Subject: python bijection References: <5a99def7-e182-4782-9054-f1035affa34d@x5g2000prf.googlegroups.com> <7n39ojF3jj6iuU1@mid.individual.net> <12c55890-118d-4655-b6c0-c908c9734a17@a32g2000yqm.googlegroups.com> Message-ID: En Sat, 28 Nov 2009 06:30:44 -0300, Joshua Bronson escribi?: > On Nov 27, 9:36 pm, "Gabriel Genellina" > wrote: >> En Fri, 27 Nov 2009 15:12:36 -0300, Francis Carr >> escribi?: >> >> > After much tinkering, I think I have a simpler solution. Just make >> > the inverse mapping accessible via an attribute, -AND- bind the >> > inverse of -THAT- mapping back to the original. The result is a >> > python dict with NO NEW METHODS except this inverse-mapping >> > attribute. I have posted it on code.activestate.com as > > href="http://code.activestate.com/recipes/576968/">Recipe 576968: >> > Flipdict -- python dict that also maintains a one-to-one inverse >> > mapping > >> Just a couple of comments: >> >> Instead of: >> self._flip = dict.__new__(self.__class__) >> I'd write: >> self._flip = self.__class__() >> unless I'm missing something (but see the next point). > > How would this not cause infinite recursion? That goes under "unless I'm missing something" ;) You're right, it would cause infinite recursion. Not a good idea... >> Also, although Python's GC is able to handle them, I prefer to avoid >> circular references like those between x and x._flip. Making >> self._flip a weak reference (and dereferencing it in the property) >> should be enough. > > If both self._flip and self._flip._flip are weak references, no strong > references to the inverse mapping survive leaving the constructor > scope. Unless I'm missing something, only one of these can be a weak > reference, and then you'd have to do something like this in the > property to prevent "TypeError: FlipDict is not callable": > > @property > def flip(self): > try: > # we're an inverse, self._flip is a weak reference > return self._flip() > except TypeError: > # we're a forward mapping, self._flip is a strong > reference > return self._flip Yes - although I'd explicitely test for a weakref object: def flip(self): _flip = self._flip if isinstance(_filp, weakref.ref): return _flip() return _flip and probably all those internal references to self._flip should become self.flip too; I've not tested the code but I think it *should* work... -- Gabriel Genellina From aioe.org at technicalbloke.com Wed Dec 9 02:11:56 2009 From: aioe.org at technicalbloke.com (r0g) Date: Wed, 09 Dec 2009 07:11:56 +0000 Subject: Request for py program to insert space between two characters and saved as text? References: <7b87ecb70912071856k10ad366du2b07ce92b94e50e3@mail.gmail.com> Message-ID: Dave Angel wrote: > r0g wrote: >> Dave Angel wrote: >> >>> r0g wrote: >>> >>>> Dennis Lee Bieber wrote: >>>> >>>> >>>>> On Tue, 8 Dec 2009 08:26:58 +0530, 74yrs old >>>>> declaimed the following in gmane.comp.python.general: >>>>> >>>>> >>>>>> For Kannada project .txt(not .doc) is used, my requirement is to >>>>>> have one >>>>>> >>>> >>>> >>>> >>>>>> In this context, I request you kindly for small python program - to >>>>>> make or >>>>>> >>>>> Excuse me -- you want one of US to supply you with a program that >>>>> will be used for YOUR entry to some job site? (At least, that's what I >>>>> seem to be finding for "Kannada project") >>>>> >>>>> >>>> Well it is only a 2 line program and he did ask nicely after all, if >>>> you >>>> begrudge him it then feel free to not answer, righteous indignation >>>> rarely helps anyone. >>>> >>>> Dear OP... >>>> >>>> Put the following 2 lines into a file and save it as spacer.py >>>> >>>> import sys >>>> print ' '.join([e for e in open(sys.argv[1], 'r').read()]) >>>> >>>> >>>> Then open a terminal window and 'cd' to the same folder you just saved >>>> the spacer.py file in. Type... >>>> >>>> python spacer.py inputfile.txt > outputfile.txt >>>> >>>> This will run inputfile.txt through the space adding program we have >>>> just saved and then 'pipe' the output of that into a new file >>>> outputfile.txt >>>> >>>> Hope this helps, >>>> >>>> >>>> Roger Heathcote. >>>> >>>> >>> That seems a bit dangerous to give to a beginner at Python, without >>> discussing Unicode issues. If he's in Python 3.x, and if the default >>> encoder is ASCII, which it seems to be most places, then he'll quickly >>> get a conversion error for some character. And if it's some other 8 bit >>> form, he might not get an error, but find that a space is inserted >>> between two of the bytes of a UTF-8 code. >>> >>> DaveA >>> >>> >> >> >> >> He said he's running the latest python and fedora, AFAIK the default for >> these systems is still the 2 series, not 3. >> >> >> Roger. >> >> > That's even worse. As far as I can tell, the code will never do what he > wants in Python 2.x. The Kannada text file is full of Unicode > characters in some encoding, and if you ignore the encoding, you'll just > get garbage. > > Ah, fair enough. In my defence though I never saw the original post or this kannada.txt file as my newsserver is not so much with the reliability. I guess it's naive to assume an english .txt file is going to be in ASCII these days eh? I've yet to try python 3 yet either, this whole Unicode thing looks like it could be a total nightmare! :( Roger. From pavlovevidence at gmail.com Wed Dec 9 03:08:39 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 9 Dec 2009 00:08:39 -0800 (PST) Subject: switch References: <335204.99872.qm@web57905.mail.re3.yahoo.com> Message-ID: <68e6e315-f3c7-4e52-a56f-802e99d75e6a@y32g2000prd.googlegroups.com> On Dec 8, 9:36?pm, Asun Friere wrote: > This code is probably symptomatic of poor design. (Not to mention that > your condition tests). ?For which reason python has no 'case' > statement and why no decent OO language should. > > It is a principle of OO design that "an object should know what to do > itself." ?Rather running an object though a series of tests, it is > better to send the object a message, relying on polymorphism or duck- > typing, and deal with any exceptions thrown. What if the object is a string you just read from a file? How do you dispatch using polymorphism in that case? Carl Banks From bruno.42.desthuilliers at websiteburo.invalid Wed Dec 9 03:54:22 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 09 Dec 2009 09:54:22 +0100 Subject: switch In-Reply-To: References: <335204.99872.qm@web57905.mail.re3.yahoo.com> Message-ID: <4b1f65b9$0$30372$426a74cc@news.free.fr> Steven D'Aprano a ?crit : > On Tue, 08 Dec 2009 21:36:23 -0800, Asun Friere wrote: (snip) >> It is a principle of OO design that "an object should know what to do >> itself." Rather running an object though a series of tests, it is >> better to send the object a message, relying on polymorphism or duck- >> typing, and deal with any exceptions thrown. > But putting that aside, I find myself wondering how you would deal with > the following switch-like series of tests. > > > def print_grades(score): > if not 0 <= score <= 100: > raise ValueError("score must be between 0 and 100") > if score < 50: > print "You have failed." > consider_suspension() > elif score == 50: > print "You have just passed by the skin of your teeth." > elif score < 60: > print "You have scored a D. You need to try harder." > elif score < 70: > print "You have scored a C." > elif score < 80: > print "You have scored a B. Well done." > elif score < 100: > print "Congratulations, you have scored an A." > else: > assert score == 100 > print "You have scored a PERFECT 100% SCORE!!!" > if not evidence_of_cheating(): > call_newspapers() Well, obviously such business rules must by no mean be hardcoded. You really need a "rule engine", configurable by your domain experts thru a DSL that we'll design specially for you. The rule engine will generate an AbstractScoreFactory that will instanciate appropriate IScore implementation objects that knows what to do. You also need to decouple the output mechanism - what if you need to output to a web page, an IPhone app, a RSS stream, an audio stream or clay tablets ? To allow for maximum decoupling, the output mechanism should be configurable thru a strict, well defined and universally understood language - I mean XML, of course. > > Obviously that could, with a non-trivial amount of work, be turned into a > dictionary dispatch, Dictionnary dispatch ? C'mon, you must be joking ? An enterprise application is not some Q&D cowboy script, you know ? You do have to apply state of the art designs and patterns to do it properly From jebagnanadas at gmail.com Wed Dec 9 05:05:21 2009 From: jebagnanadas at gmail.com (Jebagnana Das) Date: Wed, 9 Dec 2009 15:35:21 +0530 Subject: problem in freezing python script... Message-ID: <5ff1e7d40912090205p265f8e32u19c75245de36baa2@mail.gmail.com> Hello all, I'm using cxfreeze to freeze the python script in my ubuntu 9.04 machine. Now when i tried to execute the binary in mandriva 2008 the error message is.. File "/usr/local/lib/python3.1/site-packages/cx_Freeze/initscripts/Console3.py", line 27, in File "test.py", line 7, in File "ExtensionLoader_PyQt4_QtGui.py", line 12, in ImportError: /home/oputils/dist/PyQt4.QtGui.so: *undefined symbol: _ZTI19QStyledItemDelegate* when i searched the python mailing list i found this issue has been already raised http://www.mail-archive.com/python at py.cz/msg04278.html and is in french language(i think) which i don't know.. Can any of you restate this in english?? Your help would be much appreciated.. Regards, Jebagnanadas A. -------------- next part -------------- An HTML attachment was scrubbed... URL: From gabriel.rossetti at arimaz.com Wed Dec 9 05:17:08 2009 From: gabriel.rossetti at arimaz.com (Gabriel Rossetti) Date: Wed, 09 Dec 2009 11:17:08 +0100 Subject: UnboundLocalError: local variable '_[1]' referenced before assignment Message-ID: <4B1F7924.2080407@arimaz.com> Hello everyone, I get this error on python 2.6.1 on mac os x 10.6 : UnboundLocalError: local variable '_[1]' referenced before assignment here's the code that raises this: params = [ self.__formatData(paramProcFunc, query, p) for p in params ] what I don't get is that it worked on mac os x 10.5 (python 2.5.x) but it no longer works. I tried the following and it works : r = [] for p in params: r.append(self.__formatData(paramProcFunc, query, p)) params = r Does anyone understand what is going on here? Thank you, Gabriel From chardster at gmail.com Wed Dec 9 07:40:11 2009 From: chardster at gmail.com (Richard Thomas) Date: Wed, 9 Dec 2009 04:40:11 -0800 (PST) Subject: UnboundLocalError: local variable '_[1]' referenced before assignment References: Message-ID: <05bdf0c1-9fce-4de6-a639-4ec388976eca@s31g2000yqs.googlegroups.com> On Dec 9, 10:17?am, Gabriel Rossetti wrote: > Hello everyone, > > I get this error on python 2.6.1 on mac os x 10.6 : > > UnboundLocalError: local variable '_[1]' referenced before assignment > > here's the code that raises this: > > params = [ self.__formatData(paramProcFunc, query, p) for p in params ] > > what I don't get is that it worked on mac os x 10.5 (python 2.5.x) but > it no longer works. I tried the following and it works : > > r = [] > for p in params: > ? ? r.append(self.__formatData(paramProcFunc, query, p)) > params = r > > Does anyone understand what is going on here? > > Thank you, > Gabriel That isn't an error that should occur, not least because _[1] isn't a valid name. Can you post a full traceback? Richard. From frank at chagford.com Wed Dec 9 07:56:06 2009 From: frank at chagford.com (Frank Millman) Date: Wed, 9 Dec 2009 14:56:06 +0200 Subject: Question about 'remote objects' Message-ID: Hi all I am writing a multi-user business/accounting application. It is getting rather complex and I am looking at how to, not exactly simplify it, but find a way to manage the complexity. I have realised that it is logically made up of a number of services - database service with connection to database workflow engine for business processes services manager to handle automated services, such as web services client manager to service logins from client workstations possibly others I have made a start by splitting some of these off into separate modules and running them in their own threads. I am concerned about scalability if they are all running on the same machine, so I am looking into how to enable these services to run on separate servers if required. My first thought was to look into Pyro. It seems quite nice. One concern I had was that it creates a separate thread for each object made available by the server. My database server creates separate objects for each instance of a row read in from the database, and with multiple users running multiple applications, with each one opening multiple tables, this could run into hundreds, so I was not sure if that would work. Then I read that the multiprocessing module allows processes to be spread across multiple servers. The documentation is not as clear as Pyro's, but it looks as if it could do what I want. I assume it would use processes rather than threads to make multiple objects available, but I don't know if there is a practical limit. Then I thought that, instead of the database server exposing each object remotely, I could create one 'proxy' object on the server through which all clients would communicate, and it in turn would communicate with each instance locally. That felt more managable, but then I thought - why bother with remote objects at all? Why not just run a SocketServer on the database server, and design a mini-protocol to allow clients to make requests and receive results. This is a technology I am already comfortable with, as this is how I handle client workstation logins. If I did go this route, I could apply the same principle to all the services. I don't have the experience to make an informed decision at this point, so I thought I would see if there is any consensus on the best way to go from here. Is there any particular benefit in using remote objects as opposed to writing a SocketServer? Any advice will be much appreciated. Thanks Frank Millman From giles.thomas at resolversystems.com Wed Dec 9 08:01:09 2009 From: giles.thomas at resolversystems.com (Giles Thomas) Date: Wed, 9 Dec 2009 05:01:09 -0800 (PST) Subject: ANN: London Financial Python Users Group Message-ID: Hi all, If you're based in or visiting London, and have an interest in using Python for financial software, you might want to come to the next meeting of the London Financial Python Users Group! The time: Monday 14 December 2009 at 7pm The place: MWB Regent Street, Liberty House 222 Regent Street, London W1B 5TR We've got a couple of lightning talks lined up, but if you're interested in giving one yourself then drop Didrik Pinte a line at dpinte at enthought.com. There's a (very minimal) Wiki page about the Users Group here: Cheers, Giles -- Giles Thomas giles.thomas at resolversystems.com +44 (0) 20 7253 6372 17a Clerkenwell Road, London EC1M 5RD, UK VAT No.: GB 893 5643 79 Registered in England and Wales as company number 5467329. Registered address: 843 Finchley Road, London NW11 8NA, UK From sccolbert at gmail.com Wed Dec 9 08:18:10 2009 From: sccolbert at gmail.com (Chris Colbert) Date: Wed, 9 Dec 2009 14:18:10 +0100 Subject: relative imports with the __import__ function In-Reply-To: References: Message-ID: <7f014ea60912090518o6596f494h4c15c3091ac2cf82@mail.gmail.com> On Tue, Dec 8, 2009 at 5:48 PM, Peter Otten <__peter__ at web.de> wrote: > Chris Colbert wrote: > >> I have package tree that looks like this: >> >> main.py >> package >> ----__init__.py >> ----configuration.ini >> ----server >> --------__init__.py >> --------xmlrpc_server.py >> --------controller.py >> --------reco >> ------------ >> ----segmentation >> --------__init__.py >> --------red_objects.py >> ---- >> >> >> main.py launches an instance of xmlrpc_server.py which, in turn, >> imports controller.py. >> controller.py reads configuration.ini to determine which >> module/function to import from the segmentation directory and >> subsequently use. >> >> that config file specifies the module as 'red_objects' and the >> function as 'segment_red'. >> >> I am trying to dynamically import that module and func using the >> __import__ statement but keep getting empty module errors. > > >> I'm assuming i'm missing something fundamental on the import resolution... > > After some experimentation it turns out you have to provide some context for > __import__() to determine the absolute location of the requested module. The > required bit of information is the current module's __name__ attribute which > you can provide via the globals parameter: > > def import_segmentation(name): > ? ?return getattr(__import__("segmentation." + name, level=2, > globals=globals()), name) > > Peter > -- > http://mail.python.org/mailman/listinfo/python-list > Many thanks Peter! Almost like a charm! It seems the relative import level is dependent on the location of the main entry module. I thought the whole idea of relative imports was to make the import independent of the entry point? here is the import function i'm using def import_segmentation(self): # get the segmentation function defined in configuration.ini parent_dir = os.path.split(os.path.dirname(__file__))[0] prsr = ConfigParser.ConfigParser() prsr.read(os.path.join(parent_dir, 'configuration.ini')) seg_mod = prsr.get('segmentation', 'module') seg_func = prsr.get('segmentation', 'function') print __name__ smod = __import__('segmentation.%s' % seg_mod, globals=globals(), fromlist=[seg_func], level=2) sfunc = getattr(smod, seg_func) return sfunc for that import level of 2 to work the tree must look like this: main.py package ----__init__.py ----configuration.ini ----server --------__init__.py --------xmlrpc_server.py --------controller.py --------reco ------------ ----segmentation --------__init__.py --------red_objects.py ---- but if I rearrange the package structure like this (just moving the location of main.py): package ----main.py ----__init__.py ----configuration.ini ----server --------__init__.py --------xmlrpc_server.py --------controller.py --------reco ------------ ----segmentation --------__init__.py --------red_objects.py ---- I have to change the import to level=1 or I get this error: ValueError: Attempted relative import beyond toplevel package I don't understand why the location of my main.py should have ANY bearing on relative import resolution. But again, i'm probably just being dense and need someone to explain it to me in newb speak ;) Cheers, Chris From fabio at aptana.com Wed Dec 9 08:26:00 2009 From: fabio at aptana.com (Fabio Zadrozny) Date: Wed, 9 Dec 2009 11:26:00 -0200 Subject: Pydev 1.5.2 Released Message-ID: Hi All, Pydev 1.5.2 has been released Details on Pydev: http://pydev.org Details on its development: http://pydev.blogspot.com Release Highlights: ------------------------------- * Profile to have much lower memory requirements (especially on code-analysis rebuilds) * Profile for parsing to be faster * Compare Editor o Syntax highlighting integrated o Editions use the pydev editor behavior o Code completion works * Fixed issue where pydev could deadlock * No longer reporting import redefinitions and unused variables for the initial parts of imports such as import os.path * Fixed issue where pydev was removing __classpath__ from the pythonpath in jython * Using M1, M2 and M3 for keys instead of hardcoding Ctrl, Shift and Alt (which should make keybindings right on Mac OS) * Fixed some menus and popups * Properly categorizing Pydev views * Handling binary numbers in the python 2.6 and 3.0 grammar * from __future__ import print_function works on python 2.6 * Added drag support from the pydev package explorer * Properly translating slashes on client/server debug * Other minor fixes What is PyDev? --------------------------- PyDev is a plugin that enables users to use Eclipse for Python, Jython and IronPython 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 Aptana http://aptana.com/python Pydev - Python Development Environment for Eclipse http://pydev.org http://pydev.blogspot.com From davea at ieee.org Wed Dec 9 08:48:41 2009 From: davea at ieee.org (Dave Angel) Date: Wed, 09 Dec 2009 08:48:41 -0500 Subject: Request for py program to insert space between two characters and saved as text? In-Reply-To: References: <7b87ecb70912071856k10ad366du2b07ce92b94e50e3@mail.gmail.com> Message-ID: <4B1FAAB9.8050801@ieee.org> r0g wrote: > Dave Angel wrote: > >> r0g wrote: >> >>> Dave Angel wrote: >>> >>> >>>> r0g wrote: >>>> >>>> >>>>> Dennis Lee Bieber wrote: >>>>> >>>>> >>>>> >>>>>> On Tue, 8 Dec 2009 08:26:58 +0530, 74yrs old >>>>>> declaimed the following in gmane.comp.python.general: >>>>>> >>>>>> >>>>>> >>>>>>> For Kannada project .txt(not .doc) is used, my requirement is to >>>>>>> have one >>>>>>> >>>>>>> >>>>> >>>>> >>> >>> >> That's even worse. As far as I can tell, the code will never do what he >> wants in Python 2.x. The Kannada text file is full of Unicode >> characters in some encoding, and if you ignore the encoding, you'll just >> get garbage. >> >> >> > > Ah, fair enough. In my defence though I never saw the original post or > this kannada.txt file as my newsserver is not so much with the > reliability. I guess it's naive to assume an english .txt file is going > to be in ASCII these days eh? > > I've yet to try python 3 yet either, this whole Unicode thing looks like > it could be a total nightmare! :( > > Roger. > > But it isn't an english .txt file, it's a Kannada .txt file. Presumably you didn't realize that Kannada is a (non-English) language, spoken in parts of India, with several hundred characters. ASCII wasn't even an option. Anyway, no harm done, someone else referred the OP to a Python user-group local to that region. DaveA From kerny404 at gmail.com Wed Dec 9 08:48:46 2009 From: kerny404 at gmail.com (Andrea Crotti) Date: Wed, 9 Dec 2009 05:48:46 -0800 (PST) Subject: In lista infinita? References: <20091208185015.3d0011e0@geekmail.INVALID> Message-ID: <24f103b3-1707-47cb-ac15-f00d2782c49e@m25g2000yqc.googlegroups.com> On 8 Dic, 18:50, Andreas Waldenburger wrote: > Maybe. But I'm sure it.comp.lang.python might help you better. And from > the looks of it, you seem to have started a similar thread there > (called "Generatori infiniti"). > > Generally, you'll fare better with English (even broken English will be > fine.) in this group. It's just nicer for everyone if they can > understand all messages and not feel left out. > > Anyway, good luck with your question. I didn't understand a whole lot > of it, but I guess you want to test for membership in an infinite > list/generator. Yes, possible in principle, but obviously eats memory > for larger generators. Also, consumes the generators, which is also a > factor. > I'm sorry of course it was a mistake, I wanted to post on it.comp. but I had this other group open... Anyway it was not really a question, that code was just something to check if an element is a member of a generator. Is always possible to write a in x() but if it's not in it doesn't terminate, passing the right function (in that case it was just increasing sequence) will do the trick.. From davea at ieee.org Wed Dec 9 08:58:23 2009 From: davea at ieee.org (Dave Angel) Date: Wed, 09 Dec 2009 08:58:23 -0500 Subject: UnboundLocalError: local variable '_[1]' referenced before assignment In-Reply-To: <4B1F7924.2080407@arimaz.com> References: <4B1F7924.2080407@arimaz.com> Message-ID: <4B1FACFF.9040802@ieee.org> Gabriel Rossetti wrote: >
Hello > everyone, > > I get this error on python 2.6.1 on mac os x 10.6 : > > UnboundLocalError: local variable '_[1]' referenced before assignment > > here's the code that raises this: > > params = [ self.__formatData(paramProcFunc, query, p) for p in params ] > > what I don't get is that it worked on mac os x 10.5 (python 2.5.x) but > it no longer works. I tried the following and it works : > > r = [] > for p in params: > r.append(self.__formatData(paramProcFunc, query, p)) > params = r > > Does anyone understand what is going on here? > > Thank you, > Gabriel > >
> Clearly you're not supplying enough context. The UnboundLocalError is only raised inside a function (or method), and you only show one line of that function. And in the second example, it's even worse, since you imply it's top-level code by carefully unindenting everything. My *guess* is that you have a global variable params, which you're looping on. And then you assign a local variable by the same name. If you have an assignment anywhere in the function, that name is considered a local, and if you reference it before you assign it, it'll generate this error. Three possible fixes, depending on why you're doing this. 1) pass the params in to the function as an argument 2) use a different name for the local thing you're building 3) use a global statement to force the compiler to use the global one and not create a local. (probably a bad idea) DaveA From bruno.42.desthuilliers at websiteburo.invalid Wed Dec 9 09:14:05 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 09 Dec 2009 15:14:05 +0100 Subject: UnboundLocalError: local variable '_[1]' referenced before assignment In-Reply-To: <05bdf0c1-9fce-4de6-a639-4ec388976eca@s31g2000yqs.googlegroups.com> References: <05bdf0c1-9fce-4de6-a639-4ec388976eca@s31g2000yqs.googlegroups.com> Message-ID: <4b1fb0a6$0$30281$426a74cc@news.free.fr> Richard Thomas a ?crit : > On Dec 9, 10:17 am, Gabriel Rossetti > wrote: >> >> UnboundLocalError: local variable '_[1]' referenced before assignment >> > > That isn't an error that should occur, not least because _[1] isn't a > valid name It's an internal identifier used in list comps. Implementation detail, really, you're not even supposed to know about it... From gabriel.rossetti at arimaz.com Wed Dec 9 09:19:31 2009 From: gabriel.rossetti at arimaz.com (Gabriel Rossetti) Date: Wed, 09 Dec 2009 15:19:31 +0100 Subject: no SPA in poplib? Message-ID: <4B1FB1F3.4020402@arimaz.com> Hello, I couldn't find SPA in poplib, does anyone know of an alternative implementation? Thanks, Gabriel -- Arimaz SA Ing?nieur en Informatique Av. du 24 Janvier 11 Ateliers de la Ville de Renens, Atelier 5 1020 Renens, Switzerland www.arimaz.com www.mydeskfriend.com Mob: +41-(0)79-539-0069 Tel: +41-(0)21-566-7343 From gabriel.rossetti at arimaz.com Wed Dec 9 09:32:52 2009 From: gabriel.rossetti at arimaz.com (Gabriel Rossetti) Date: Wed, 09 Dec 2009 15:32:52 +0100 Subject: UnboundLocalError: local variable '_[1]' referenced before assignment In-Reply-To: <4B1FACFF.9040802@ieee.org> References: <4B1F7924.2080407@arimaz.com> <4B1FACFF.9040802@ieee.org> Message-ID: <4B1FB514.9010804@arimaz.com> Dave Angel wrote: > Gabriel Rossetti wrote: >>
Hello >> everyone, >> >> I get this error on python 2.6.1 on mac os x 10.6 : >> >> UnboundLocalError: local variable '_[1]' referenced before assignment >> >> here's the code that raises this: >> >> params = [ self.__formatData(paramProcFunc, query, p) for p in params ] >> >> what I don't get is that it worked on mac os x 10.5 (python 2.5.x) >> but it no longer works. I tried the following and it works : >> >> r = [] >> for p in params: >> r.append(self.__formatData(paramProcFunc, query, p)) >> params = r >> >> Does anyone understand what is going on here? >> >> Thank you, >> Gabriel >> >>
>> > Clearly you're not supplying enough context. The UnboundLocalError is > only raised inside a function (or method), and you only show one line > of that function. > > And in the second example, it's even worse, since you imply it's > top-level code by carefully unindenting everything. > > My *guess* is that you have a global variable params, which you're > looping on. And then you assign a local variable by the same name. > If you have an assignment anywhere in the function, that name is > considered a local, and if you reference it before you assign it, > it'll generate this error. > > Three possible fixes, depending on why you're doing this. > > 1) pass the params in to the function as an argument > 2) use a different name for the local thing you're building > 3) use a global statement to force the compiler to use the global one > and not create a local. (probably a bad idea) > > DaveA > Hello Dave, ok, you' re right about not showing enough: params = [ self.__formatData(paramProcFunc, query, p) for p in params ] where : paramProcFunc = "percent2Volume" def __formatData(self, func, query, data): return getattr(self._unitDataAbs, func)(self._unitCmdAbs, query, data) def percent2Volume(self, absCmds, query, percent): return query, int(round(percent / 100.0 * absCmds["volCeil"])) but I still don't see where the problem is and why it works with the explicit loop and not the list comp. Thanks, Gabriel From yjoshi at starentnetworks.com Wed Dec 9 09:40:37 2009 From: yjoshi at starentnetworks.com (Joshi, Yateen) Date: Wed, 9 Dec 2009 20:10:37 +0530 Subject: Issues with multiprocessing Message-ID: <3BD53621E5C8E54594130AF5459379EE135B9135@exchindia4.starentnetworks.com> Hi, I have an application that uses multiprocessing pools (multiprocessing.Pool(processes=.....)). There are multiple such pools and each pool has configurable number of processes. Once the process is spawned, it keeps on executing and does the needed processing. If there is nothing to process (like ftp'ing files from some source, if the files are not there, the process would sleep for some time, and then again check for files, that way, it is a infinite loop with some sleep), the process 'sleeps' for some time and continues. I am using a T5220, Solaris box with Solaris 10. Problem -there are multiple pools and multiple processes, i am seeing that not all the processes get spawned. They get spawned when the sleep time is increased (say from 0.1 sec to 1 sec). If I further increase the number of processes, again some process do not get spawned. For that, I further need to increase the sleep time (say to 2 sec), then the processes get spawned. Typically, in a multiprocessing I would expect that if a process sleeps for even a small time, other processes should get their chance to execute, but this does not seem to be happening here. Can you please throw some light on it? Thanks and Regards, Yateen V. Joshi This email and any attachments may contain legally privileged and/or confidential information of Starent Networks, Corp. and is intended only for the individual or entity named in the message. The information transmitted may not be used to create or change any contractual obligations of Starent Networks, Corp. Any review, retransmission, dissemination or other use of, or taking of any action in reliance upon this e-mail and its attachments by persons or entities other than the intended recipient is prohibited. If you are not the intended recipient, please notify the sender immediately -- by replying to this message or by sending an email to postmaster at starentnetworks.com -- and destroy all copies of this message and any attachments without reading or disclosing their contents. Thank you. -------------- next part -------------- An HTML attachment was scrubbed... URL: From hniksic at xemacs.org Wed Dec 9 09:48:27 2009 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Wed, 09 Dec 2009 15:48:27 +0100 Subject: UnboundLocalError: local variable '_[1]' referenced before assignment References: <05bdf0c1-9fce-4de6-a639-4ec388976eca@s31g2000yqs.googlegroups.com> Message-ID: <877hswfbk4.fsf@busola.homelinux.net> Richard Thomas writes: > That isn't an error that should occur, not least because _[1] isn't a > valid name. Can you post a full traceback? The name _[n] is used internally when compiling list comprehensions. The name is chosen precisely because it is not an (otherwise) valid identifier. For example, try: import dis dis.dis(lambda: [ a for a in l ]) The user should never see _[n]; if he does, it's probably due to a bug in Python. From khamenya at gmail.com Wed Dec 9 09:58:11 2009 From: khamenya at gmail.com (Valery) Date: Wed, 9 Dec 2009 06:58:11 -0800 (PST) Subject: a huge shared read-only data in parallel accesses -- How? multithreading? multiprocessing? Message-ID: Hi all, Q: how to organize parallel accesses to a huge common read-only Python data structure? Details: I have a huge data structure that takes >50% of RAM. My goal is to have many computational threads (or processes) that can have an efficient read-access to the huge and complex data structure. "Efficient" in particular means "without serialization" and "without unneeded lockings on read-only data" To what I see, there are following strategies: 1. multi-processing => a. child-processes get their own *copies* of huge data structure -- bad and not possible at all in my case; => b. child-processes often communicate with the parent process via some IPC -- bad (serialization); => c. child-processes access the huge structure via some shared memory approach -- feasible without serialization?! (copy-on-write is not working here well in CPython/Linux!!); 2. multi-threading => d. CPython is told to have problems here because of GIL -- any comments? => e. GIL-less implementations have their own issues -- any hot recommendations? I am a big fan of parallel map() approach -- either multiprocessing.Pool.map or even better pprocess.pmap. However this doesn't work straight-forward anymore, when "huge data" means >50% RAM ;-) Comments and ideas are highly welcome!! Here is the workbench example of my case: ###################### import time from multiprocessing import Pool def f(_): time.sleep(5) # just to emulate the time used by my computation res = sum(parent_x) # my sofisticated formula goes here return res if __name__ == '__main__': parent_x = [1./i for i in xrange(1,10000000)]# my huge read- only data :o) p = Pool(7) res= list(p.map(f, xrange(10))) # switch to ps and see how fast your free memory is getting wasted... print res ###################### Kind regards Valery From james at agentultra.com Wed Dec 9 09:59:13 2009 From: james at agentultra.com (J Kenneth King) Date: Wed, 09 Dec 2009 09:59:13 -0500 Subject: Question about 'remote objects' References: Message-ID: <85zl5s19dq.fsf@agentultra.com> "Frank Millman" writes: > Hi all > > I am writing a multi-user business/accounting application. It is getting > rather complex and I am looking at how to, not exactly simplify it, but find > a way to manage the complexity. > > I have realised that it is logically made up of a number of services - > database service with connection to database > workflow engine for business processes > services manager to handle automated services, such as web services > client manager to service logins from client workstations > possibly others > > I have made a start by splitting some of these off into separate modules and > running them in their own threads. > > I am concerned about scalability if they are all running on the same > machine, so I am looking into how to enable these services to run on > separate servers if required. Have you finished the application already? At my job we're still serving just over 1M+ web requests (a month), processing 15k+ uploads, and searching through over 5M+ database records a day. We're still running on 3 boxes. You can get a lot out of your machines before you have to think about the complex task of scaling/distributing. > My first thought was to look into Pyro. It seems quite nice. One concern I > had was that it creates a separate thread for each object made available by > the server. My database server creates separate objects for each instance of > a row read in from the database, and with multiple users running multiple > applications, with each one opening multiple tables, this could run into > hundreds, so I was not sure if that would work. It probably will work. Pyro is a very nice framework and one that I've built a few applications on. It has a lot of flexible design patterns available. Just look in the examples included with the distribution. > > Then I read that the multiprocessing module allows processes to be spread > across multiple servers. The documentation is not as clear as Pyro's, but it > looks as if it could do what I want. I assume it would use processes rather > than threads to make multiple objects available, but I don't know if there > is a practical limit. There is a theoretical limit to all of the resources on a machine. Threads don't live outside of that limit. They just have a speedier start-up time and are able to communicate with one another in a single process. It doesn't sound like that will buy you a whole lot in your application. You can spawn as many processes as you need. > > Then I thought that, instead of the database server exposing each object > remotely, I could create one 'proxy' object on the server through which all > clients would communicate, and it in turn would communicate with each > instance locally. > > That felt more managable, but then I thought - why bother with remote > objects at all? Why not just run a SocketServer on the database server, and > design a mini-protocol to allow clients to make requests and receive > results. This is a technology I am already comfortable with, as this is how > I handle client workstation logins. If I did go this route, I could apply > the same principle to all the services. Because unless you wrote your own database or are using some arcane relic, it should already have its own configurable socket interface? > > I don't have the experience to make an informed decision at this point, so I > thought I would see if there is any consensus on the best way to go from > here. Finish building the application. Do the benchmarks. Profile. Optimize. Find the clear boundaries of each component. Build an API along those boundaries. Add a network layer in front of the boundaries. Pyro is a good choice, twisted is also good. Roll your own if you think you can do better or it would fit your projects' needs. > Is there any particular benefit in using remote objects as opposed to > writing a SocketServer? Abstraction. Pyro is just an abstraction over an RPC mechanism. Nothing special about it. Twisted has libraries to do the same thing. Writing your own socket-level code can be messy if you don't do it right. > > Any advice will be much appreciated. > > Thanks > > Frank Millman Best of luck. From joaopcf at gmail.com Wed Dec 9 09:59:48 2009 From: joaopcf at gmail.com (=?ISO-8859-1?Q?Jo=E3o?=) Date: Wed, 9 Dec 2009 06:59:48 -0800 (PST) Subject: plain text parsing to html (newbie problem) Message-ID: <6664c88b-ec93-4b6c-a536-8a6b5959cd5e@a21g2000yqc.googlegroups.com> I apologize for my newbiness but I'm banging my head making this work : ( What change must I made for the tag enforcement being reflected to the 'mail' file? Am I using the WritableObject class correctly? (I'm getting a blank 'mail' file after running the .py script) How can I see the output run in debug mode like in perl? #!/usr/bin/env python import sys, os import subprocess import re import datetime # simple class with write method to redirect print output to a file class WritableObject: def __init__(self): self.content = [] def write(self, string): self.content.append(string) x=datetime.date.today() yyyy, dd = x.year, x.day mail = WritableObject() print >>mail, "To: %s" % (mail1) print >>mail, "Subject: %s day %s " % (yyyy, dd) print >>mail, "Content-Type: text/html; charset=\"us-ascii\"" subprocess.call("php $HOME/report.php > temp.txt", shell=True) body = subprocess.call("cat $HOME/.txt", shell=True) print >>mail, "" print >>mail, "" print >>mail, "" #copies common header in the Problem html to the OK one subprocess.call("cp $HOME/mail $HOME/OK.html", shell=True) input_file = open('mail', 'r+') lines = input_file.readlines() input_file.close() output_file = open("mail", "w+") for line in lines: if line.startswith('

'): line = '

' + line.rstrip('\n') + '

' + '\n' output_file.write(line) if not body: print >>mail, '''

[No problems detected ]. All monitored metrics

OK

''' else: print >>mail, '''
Table Table2 Table3
%s ''' % (body) subprocess.call("sendmail me at my.mail < mail", shell=True) output_file.close() From martin.hellwig at dcuktec.org Wed Dec 9 10:28:06 2009 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Wed, 09 Dec 2009 15:28:06 +0000 Subject: tkinter photoimage, couldn't recognize image data (PPM) Message-ID: Hi all, I've tried to display an image with the source being a string but it fails (see below). Is there a way to display PPM without writing it first to a file? Thanks, Martin ----- snippet ----- ''' Ubuntu 9.04 64bit, python 3.1 ''' import tkinter DATA="""P3 3 2 255 255 0 0 0 255 0 0 0 255 255 255 0 255 255 255 0 0 0""" def display(): tk = tkinter.Tk() canvas = tkinter.Canvas(tk, width=3, height=2) canvas._image_reference = tkinter.PhotoImage(format='ppm', data=DATA) canvas.create_image((0,0), image=canvas._image_reference) canvas.pack() tk.after(1500, tk.quit) tk.mainloop() if __name__ == '__main__': display() ----- ----- traceback ----- Traceback (most recent call last): File "/home/martin/DCUK Technologies/workspace/mhellwig/src/test/tkintering.py ", line 24, in display() File "/home/martin/DCUK Technologies/workspace/mhellwig/src/test/tkintering.py ", line 17, in display canvas._image_reference = tkinter.PhotoImage(format='ppm', data=DATA) File "/usr/local/lib/python3.1/tkinter/__init__.py", line 3269, in __init__ Image.__init__(self, 'photo', name, cnf, master, **kw) File "/usr/local/lib/python3.1/tkinter/__init__.py", line 3225, in __init__ self.tk.call(('image', 'create', imgtype, name,) + options) _tkinter.TclError: couldn't recognize image data ----- -- MPH http://blog.dcuktec.com 'If consumed, best digested with added seasoning to own preference.' From klaussfreire at gmail.com Wed Dec 9 10:28:54 2009 From: klaussfreire at gmail.com (Klauss) Date: Wed, 9 Dec 2009 07:28:54 -0800 (PST) Subject: a huge shared read-only data in parallel accesses -- How? multithreading? multiprocessing? References: Message-ID: On Dec 9, 11:58?am, Valery wrote: > Hi all, > > Q: how to organize parallel accesses to a huge common read-only Python > data structure? > > Details: > > I have a huge data structure that takes >50% of RAM. > My goal is to have many computational threads (or processes) that can > have an efficient read-access to the huge and complex data structure. > > > > 1. multi-processing > ?=> a. child-processes get their own *copies* of huge data structure > -- bad and not possible at all in my case; How's the layout of your data, in terms # of objects vs. bytes used? Just to have an idea of the overhead involved in refcount externalization (you know, what I mentioned here: http://groups.google.com/group/unladen-swallow/browse_thread/thread/9d2af1ac3628dc24 ) From alfps at start.no Wed Dec 9 10:38:41 2009 From: alfps at start.no (Alf P. Steinbach) Date: Wed, 09 Dec 2009 16:38:41 +0100 Subject: More stuff added to ch 2 of my programming intro Message-ID: Format: PDF The new stuff, section 2.7, is about programs as simulations and handling data, focusing on modeling things. It includes some Python GUI programming. The plan is to discuss containers like lists and dictionaries in perhaps two more subsections of 2.7, but I'm not quite sure about how to approach that or exactly how much to cover, since the intent of ch 2 is to introduce mostly general concepts and enable the reader to try out (more or less) interesting things. Cheers, - Alf PS: comments welcome! From wanderer at dialup4less.com Wed Dec 9 10:42:10 2009 From: wanderer at dialup4less.com (Wanderer) Date: Wed, 9 Dec 2009 07:42:10 -0800 (PST) Subject: How do I Block Events in wxPython Message-ID: <6854a0bb-9edc-4392-9761-d2f3cf98f89e@k4g2000yqb.googlegroups.com> I have a wxPython program which does some calculations and displays the results. During these calculations if I click the mouse inside the dialog the program locks up. If I leave the dialog alone the process completes fine. I have tried running the function from a separate dialog with Show Modal and I have tried using SetEvtHandlerEnabled all to no avail. The program is long and occupies several files so I won't show the whole thing but here is the calculation part. How do I block events? def DoEfficiency(self): from time import sleep self.timer.Stop() TotalPower = 0 Counter = 0 for ang in range(1,89): self.tc_angle.SetValue(ang) height = int(self.eclwidth * 10) for hgt in range(0,height): self.tc_height.SetValue(float(hgt)/10.0) self.UpdateValues() self.Redraw() self.DrawRays() sPower = self.tc_power.GetValue() Power = sPower.split('%') TotalPower +=float(Power[0]) Counter +=1 sleep(0.1) efficiency = TotalPower/Counter self.tc_eff.SetLabel(str(round(efficiency,1))) self.timer.Start(10) # end DoEfficiency def OnEfficiency(self, event): self.tc_aangle.SetEvtHandlerEnabled(False) self.tc_angle.SetEvtHandlerEnabled(False) self.tc_calc_len.SetEvtHandlerEnabled(False) self.tc_cpclength.SetEvtHandlerEnabled(False) self.tc_cpcwidth.SetEvtHandlerEnabled(False) self.tc_det.SetEvtHandlerEnabled(False) self.tc_ecl.SetEvtHandlerEnabled(False) self.tc_eff.SetEvtHandlerEnabled(False) self.tc_gap1.SetEvtHandlerEnabled(False) self.tc_gap2.SetEvtHandlerEnabled(False) self.tc_height.SetEvtHandlerEnabled(False) self.tc_parab.SetEvtHandlerEnabled(False) self.tc_power.SetEvtHandlerEnabled(False) self.tc_refresh.SetEvtHandlerEnabled(False) self.tc_tlength.SetEvtHandlerEnabled(False) self.tc_twidth.SetEvtHandlerEnabled(False) self.tc_use_tir.SetEvtHandlerEnabled(False) self.SetEvtHandlerEnabled(False) dlf = CalcEfficiency(self,"CalcEfficiency",wx.DefaultPosition, (90,60)) self.tc_aangle.SetEvtHandlerEnabled(True) self.tc_angle.SetEvtHandlerEnabled(True) self.tc_calc_len.SetEvtHandlerEnabled(True) self.tc_cpclength.SetEvtHandlerEnabled(True) self.tc_cpcwidth.SetEvtHandlerEnabled(True) self.tc_det.SetEvtHandlerEnabled(True) self.tc_ecl.SetEvtHandlerEnabled(True) self.tc_eff.SetEvtHandlerEnabled(True) self.tc_gap1.SetEvtHandlerEnabled(True) self.tc_gap2.SetEvtHandlerEnabled(True) self.tc_height.SetEvtHandlerEnabled(True) self.tc_parab.SetEvtHandlerEnabled(True) self.tc_power.SetEvtHandlerEnabled(True) self.tc_refresh.SetEvtHandlerEnabled(True) self.tc_tlength.SetEvtHandlerEnabled(True) self.tc_twidth.SetEvtHandlerEnabled(True) self.tc_use_tir.SetEvtHandlerEnabled(True) self.SetEvtHandlerEnabled(True) # end MyInterface class CalcEfficiency(wx.Dialog): """ """ def __init__(self, parent, title, pos, size): self.parent = parent wx.Dialog.__init__(self,parent, -1, title, pos, size) self.runButton = wx.ToggleButton(self, ID_TOGGLE, "Start", wx.DefaultPosition, (70,30)) self.Bind(wx.EVT_TOGGLEBUTTON, self.OnToggle, id = ID_TOGGLE) self.ShowModal() self.Destroy() # end init def OnToggle(self, event): if self.runButton.GetValue(): self.runButton.SetLabel("WAIT") self.SetEvtHandlerEnabled(False) self.parent.DoEfficiency() self.SetEvtHandlerEnabled(True) else: self.Close() # end OnQuit # end CalcEfficiency if __name__ == '__main__': app = MyApp(False) app.MainLoop() # end main From khamenya at gmail.com Wed Dec 9 10:43:47 2009 From: khamenya at gmail.com (Valery) Date: Wed, 9 Dec 2009 07:43:47 -0800 (PST) Subject: a huge shared read-only data in parallel accesses -- How? multithreading? multiprocessing? References: Message-ID: Hi Klauss, > How's the layout of your data, in terms # of objects vs. bytes used? dict (or list) of 10K-100K objects. The objects are lists or dicts. The whole structure eats up to 2+ Gb RAM > Just to have an idea of the overhead involved in refcount > externalization (you know, what I mentioned here:http://groups.google.com/group/unladen-swallow/browse_thread/thread/9... > ) yes, I've understood the idea explained by you there. regards, Valery From python at mrabarnett.plus.com Wed Dec 9 11:11:53 2009 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 09 Dec 2009 16:11:53 +0000 Subject: plain text parsing to html (newbie problem) In-Reply-To: <6664c88b-ec93-4b6c-a536-8a6b5959cd5e@a21g2000yqc.googlegroups.com> References: <6664c88b-ec93-4b6c-a536-8a6b5959cd5e@a21g2000yqc.googlegroups.com> Message-ID: <4B1FCC49.3010304@mrabarnett.plus.com> Jo?o wrote: > I apologize for my newbiness but I'm banging my head making this work : > ( > What change must I made for the tag enforcement being reflected to the > 'mail' file? Am I using the WritableObject class correctly? > (I'm getting a blank 'mail' file after running the .py script) > How can I see the output run in debug mode like in perl? > [snip] You're storing the text in the 'mail' object (an instance of WritableObject), but at no point do you use what you have stored. I can also see that you're writing to a file call "mail" via output_file, but you're not closing the file before passing it to "sendmail". From deets at nospam.web.de Wed Dec 9 11:18:35 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 09 Dec 2009 17:18:35 +0100 Subject: Question about 'remote objects' References: Message-ID: <7oa0urF3pfblkU1@mid.uni-berlin.de> > I am writing a multi-user business/accounting application. It is getting > rather complex and I am looking at how to, not exactly simplify it, but > find a way to manage the complexity. > > I have realised that it is logically made up of a number of services - > database service with connection to database > workflow engine for business processes > services manager to handle automated services, such as web services > client manager to service logins from client workstations > possibly others > > I have made a start by splitting some of these off into separate modules > and running them in their own threads. I wouldn't do that. Creating threads (or processes) with potentially interacting components ramps up complexity a great deal, with little if any benefit at your current stage, and only a vague possibility that scaling issues appear and can be remedied by that. Instead, use threading or multi-processing to create various instances of your application that synchronize only over the DB, using locks where it is needed. Introducing RPC of whatever kind to your design will make you lose a lot of the power and flexibility code-wise, because all of a sudden you can only pass data, not behavior around. And as J Kenneth already said, deal with performance issues when the crop up. At work, we had a design with a whole bunch of separated XMLRPC-connected services, all of them restricting their access to only certain sub-schemas of the DB. This was done so that we could run them on separate servers if we wanted, with several databases. The creators of that system had the same fears as you. Guess what? Most of the time the system spend in serializing and de-serializing XML for making RPC-calls. We had no referential integrity between schemas, and no single transactions around HTTP-requests, which didn't exactly make crap out of our data, but the occasional hickup was in there. And through the limited RCP-interface, a great deal of code consisted of passing around dicts, lists and strings - with no rich OO-interface of whatever kind. Once we got rid of these premature optimizations, the system improved in performance, and the code-base was open to a *lot* of cleaning up that is still under way, but already massively improved the design. Diez From aioe.org at technicalbloke.com Wed Dec 9 11:32:23 2009 From: aioe.org at technicalbloke.com (r0g) Date: Wed, 09 Dec 2009 16:32:23 +0000 Subject: Request for py program to insert space between two characters and saved as text? References: <7b87ecb70912071856k10ad366du2b07ce92b94e50e3@mail.gmail.com> Message-ID: Dave Angel wrote: > > > r0g wrote: >> Dave Angel wrote: >> >>> r0g wrote: >>> >>>> Dave Angel wrote: >>>> >>>> >>>>> r0g wrote: >>>>> >>>>>> Dennis Lee Bieber wrote: >>>>>> >>>>>> >>>>>>> On Tue, 8 Dec 2009 08:26:58 +0530, 74yrs old >>>>>>> >>>>>>> declaimed the following in gmane.comp.python.general: >>>>>>> >>>>>>> >>>>>>>> For Kannada project .txt(not .doc) is used, my requirement is to >>>>>>>> have one >>>>>>>> >>>>>> >>>>>> >>>> >>> That's even worse. As far as I can tell, the code will never do what he >>> wants in Python 2.x. The Kannada text file is full of Unicode >>> characters in some encoding, and if you ignore the encoding, you'll just >>> get garbage. >>> >>> >>> >> >> Ah, fair enough. In my defence though I never saw the original post or >> this kannada.txt file as my newsserver is not so much with the >> reliability. I guess it's naive to assume an english .txt file is going >> to be in ASCII these days eh? >> >> I've yet to try python 3 yet either, this whole Unicode thing looks like >> it could be a total nightmare! :( >> >> Roger. >> >> > But it isn't an english .txt file, it's a Kannada .txt file. > Presumably you didn't realize that Kannada is a (non-English) language, > spoken in parts of India, with several hundred characters. ASCII wasn't > even an option. Anyway, no harm done, someone else referred the OP to a > Python user-group local to that region. > > DaveA > Well this looked like English to me... example: *F o r K a n n a d a p r o j e c t . t x t(n o t .d o c) i s u s e d, m y r e q u i r e m e n t i s t o h a v e o n e s p a c e b e t w e e n t w o c h a r a c t e r s i n t h e t e x t.* ...but yes you're right, I had never heard of Kannada let alone knew it was another language! Roger. From zephjc at gmail.com Wed Dec 9 11:42:19 2009 From: zephjc at gmail.com (zeph) Date: Wed, 9 Dec 2009 08:42:19 -0800 (PST) Subject: How do I Block Events in wxPython References: <6854a0bb-9edc-4392-9761-d2f3cf98f89e@k4g2000yqb.googlegroups.com> Message-ID: <6a65a495-3e2a-4478-98a5-1f850ba85e6e@w19g2000pre.googlegroups.com> The wxPython wiki actually has a page on dealing with long running tasks called from event handlers called (surprise surprise): http://wiki.wxpython.org/LongRunningTasks Hint: the second to last example on that page has the clearest example - using a worker thread object to do your DoEfficiency() function. I also don't think you want to disable so many event handlers, do you? Nothing will respond to inputs as long as that process is running (assuming you aren't running it in another thread.) From philip at semanchuk.com Wed Dec 9 11:43:03 2009 From: philip at semanchuk.com (Philip Semanchuk) Date: Wed, 9 Dec 2009 11:43:03 -0500 Subject: How do I Block Events in wxPython In-Reply-To: <6854a0bb-9edc-4392-9761-d2f3cf98f89e@k4g2000yqb.googlegroups.com> References: <6854a0bb-9edc-4392-9761-d2f3cf98f89e@k4g2000yqb.googlegroups.com> Message-ID: <78889DAB-984A-4FEE-AD8D-0C7A44CF19CF@semanchuk.com> On Dec 9, 2009, at 10:42 AM, Wanderer wrote: > I have a wxPython program which does some calculations and displays > the results. During these calculations if I click the mouse inside the > dialog the program locks up. If I leave the dialog alone the process > completes fine. I have tried running the function from a separate > dialog with Show Modal and I have tried using SetEvtHandlerEnabled all > to no avail. The program is long and occupies several files so I won't > show the whole thing but here is the calculation part. How do I block > events? Hi Wanderer, I don't have a solution for you but I have three suggestions. First, your program shouldn't be locking up just because you clicked on it. IMO that's the real problem, and discarding events is just a band-aid to cover it up. Nevertheless, sometimes a band-aid is an appropriate solution and you're the best judge of that. Second, the wxPython mailing list would be a better place for this question. Third, if you can't seem to resolve the problem, try paring it down to a minimal example that reproduces the problem. It's difficult to offer suggestions when we can't see the whole code or try the sample code ourselves. Good luck Philip From aioe.org at technicalbloke.com Wed Dec 9 11:48:26 2009 From: aioe.org at technicalbloke.com (r0g) Date: Wed, 09 Dec 2009 16:48:26 +0000 Subject: How do I Block Events in wxPython References: <6854a0bb-9edc-4392-9761-d2f3cf98f89e@k4g2000yqb.googlegroups.com> Message-ID: Wanderer wrote: > I have a wxPython program which does some calculations and displays > the results. During these calculations if I click the mouse inside the > dialog the program locks up. If I leave the dialog alone the process > completes fine. If anything in your GUI app takes a non trivial length of time to execute you need to run it in either a thread or a separate process. http://linuxgazette.net/107/pai.html Roger From tjreedy at udel.edu Wed Dec 9 11:55:00 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 09 Dec 2009 11:55:00 -0500 Subject: UnboundLocalError: local variable '_[1]' referenced before assignment In-Reply-To: <4B1FB514.9010804@arimaz.com> References: <4B1F7924.2080407@arimaz.com> <4B1FACFF.9040802@ieee.org> <4B1FB514.9010804@arimaz.com> Message-ID: Gabriel Rossetti wrote: >> Gabriel Rossetti wrote: >>> I get this error on python 2.6.1 on mac os x 10.6 : >>> >>> UnboundLocalError: local variable '_[1]' referenced before assignment >>> >>> here's the code that raises this: >>> >>> params = [ self.__formatData(paramProcFunc, query, p) for p in params ] >>> >>> what I don't get is that it worked on mac os x 10.5 (python 2.5.x) >>> but it no longer works. In 3.0, list comps were changed to not 'leak' the iteration variables. To do this, they are compiled to a function run in a separate namespace. It appears the new code was backported to 2.6 with an extra fix to continue leaking the iteration variable for back compatibility. I presume there is or was intended to be a switch to to get 3.x behavior for code being ported. As others have said, the error is from that internal function, and should never appear. Hence, you may have found a corner-case bug that otherwise passed the current tests. Suggestions. 1) Run with 3.1 and see if you get the same error. In not, problem is in difference between 3.1 and 2.6 listcomp code. Report to tracker. 2) Simplify the code and see if you still get the error. I would try removing the '__' from the method name, or using a data attribute instead of a method, or a method with no parameters. Unless someone here otherwise pins the error on you, report on the tracker. Terry Jan Reedy > I tried the following and it works : >>> >>> r = [] >>> for p in params: >>> r.append(self.__formatData(paramProcFunc, query, p)) >>> params = r In 2.5, list comps were rewritten like this. >>> >>> Does anyone understand what is going on here? > params = [ self.__formatData(paramProcFunc, query, p) for p in params ] > > > where : > > paramProcFunc = "percent2Volume" > > def __formatData(self, func, query, data): > return getattr(self._unitDataAbs, func)(self._unitCmdAbs, query, > data) > > def percent2Volume(self, absCmds, query, percent): > return query, int(round(percent / 100.0 * absCmds["volCeil"])) > > > but I still don't see where the problem is and why it works with the > explicit loop and not the list comp. > > Thanks, > Gabriel From jpeck at fedex.com Wed Dec 9 12:00:47 2009 From: jpeck at fedex.com (Jeff Peck) Date: Wed, 09 Dec 2009 11:00:47 -0600 Subject: How do I Block Events in wxPython In-Reply-To: <78889DAB-984A-4FEE-AD8D-0C7A44CF19CF@semanchuk.com> References: <6854a0bb-9edc-4392-9761-d2f3cf98f89e@k4g2000yqb.googlegroups.com> <78889DAB-984A-4FEE-AD8D-0C7A44CF19CF@semanchuk.com> Message-ID: <4B1FD7BF.6010009@fedex.com> Philip Semanchuk wrote: > > On Dec 9, 2009, at 10:42 AM, Wanderer wrote: > >> I have a wxPython program which does some calculations and displays >> the results. During these calculations if I click the mouse inside the >> dialog the program locks up. If I leave the dialog alone the process >> completes fine. I have tried running the function from a separate >> dialog with Show Modal and I have tried using SetEvtHandlerEnabled all >> to no avail. The program is long and occupies several files so I won't >> show the whole thing but here is the calculation part. How do I block >> events? > > > Hi Wanderer, > I don't have a solution for you but I have three suggestions. > > First, your program shouldn't be locking up just because you clicked > on it. IMO that's the real problem, and discarding events is just a > band-aid to cover it up. Nevertheless, sometimes a band-aid is an > appropriate solution and you're the best judge of that. > > Second, the wxPython mailing list would be a better place for this > question. > > Third, if you can't seem to resolve the problem, try paring it down to > a minimal example that reproduces the problem. It's difficult to offer > suggestions when we can't see the whole code or try the sample code > ourselves. > > > Good luck > Philip Wanderer, I agree with Philip. You probably want your calculation code in a separate thread. I'd advise against this, but if you're just looking for a bandaid you could try creating an event handler to catch the mouse clicks and simply call event.Skip(). If you do this, you might have to introduce a flag that gets set to True only during your calculation, and then your event hander could look something like this: def OnMouseClick(self, event): # Only skip mouse click event if calculating if self.busy: event.Skip() Jeff From tjreedy at udel.edu Wed Dec 9 12:04:21 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 09 Dec 2009 12:04:21 -0500 Subject: plain text parsing to html (newbie problem) In-Reply-To: <6664c88b-ec93-4b6c-a536-8a6b5959cd5e@a21g2000yqc.googlegroups.com> References: <6664c88b-ec93-4b6c-a536-8a6b5959cd5e@a21g2000yqc.googlegroups.com> Message-ID: Jo?o wrote: > I apologize for my newbiness but I'm banging my head making this work : > ( > What change must I made for the tag enforcement being reflected to the > 'mail' file? Am I using the WritableObject class correctly? > (I'm getting a blank 'mail' file after running the .py script) > How can I see the output run in debug mode like in perl? > > #!/usr/bin/env python > > import sys, os > import subprocess > import re > import datetime > > # simple class with write method to redirect print output to a file > class WritableObject: > def __init__(self): > self.content = [] > def write(self, string): > self.content.append(string) Python comes with a stringio class that does this *AND* has a method to retrieve the result. StringIO in 2.x, io module in 3.x From wanderer at dialup4less.com Wed Dec 9 12:06:04 2009 From: wanderer at dialup4less.com (Wanderer) Date: Wed, 9 Dec 2009 09:06:04 -0800 (PST) Subject: How do I Block Events in wxPython References: <6854a0bb-9edc-4392-9761-d2f3cf98f89e@k4g2000yqb.googlegroups.com> Message-ID: <17ed589d-f8e2-4fac-b489-5f62060ecd17@j19g2000yqk.googlegroups.com> On Dec 9, 11:48?am, r0g wrote: > Wanderer wrote: > > I have a wxPython program which does some calculations and displays > > the results. During these calculations if I click the mouse inside the > > dialog the program locks up. If I leave the dialog alone the process > > completes fine. > > If anything in your GUI app takes a non trivial length of time to > execute you need to run it in either a thread or a separate process. > > http://linuxgazette.net/107/pai.html > > Roger Thanks Everyone. I'll have to look over these wikis about threading. I decided to go another route and user a timer to perform the loops. That way the events can be processed normally. def DoEfficiency(self, event): ang = self.tc_angle.GetValue() hgt = self.tc_height.GetValue() hgt += 0.1 if hgt > self.eclwidth: hgt = 0 ang +=1 self.tc_angle.SetValue(ang) self.height = hgt self.tc_height.SetValue(hgt) self.tc_height.SetValue(hgt) self.UpdateValues() self.Redraw() self.DrawRays() sPower = self.tc_power.GetValue() Power = sPower.split('%') self.TotalPower +=float(Power[0]) self.Counter +=1 efficiency = self.TotalPower/self.Counter self.tc_eff.SetLabel(str(round(efficiency,1))) if ang > 89: self.efftimer.Stop() self.timer.Start(10) # end DoEfficiency def OnEfficiency(self, event): self.TotalPower = 0 self.Counter = 0 self.tc_angle.SetValue(1) self.tc_height.SetValue(0) self.timer.Stop() self.efftimer.Start(100) # end MyInterface Found another strange bug (Strange to me, anyway). int(0.8 * 10.0) = 7. Had to change the code to int(0.8 * 10.0 + 0.0001). From aaron.watters at gmail.com Wed Dec 9 12:14:02 2009 From: aaron.watters at gmail.com (Aaron Watters) Date: Wed, 9 Dec 2009 09:14:02 -0800 (PST) Subject: ANN: WHIFF.0.7 += GAE + jQueryUI + internationalization + testdrive = (last beta?) Message-ID: ANNOUNCING WHIFF [WSGI HTTP Integrated Filesystem Frames] release 0.7 WHIFF INDEX PAGE: http://whiff.sourceforge.net The new release adds many new features, including - Google app engine support with tutorial: http://whiffdoc.appspot.com/docs/W1100_2300.GAEDeploy - jQueryUI interactive widget support with tutorial: http://whiffdoc.appspot.com/docs/W1100_1450.jQueryUI - Internationalization tutorial: http://whiffdoc.appspot.com/docs/W1100_1700.international - "no install" test drive: http://whiffdoc.appspot.com/docs/W1100_0500.TestDrive Also the WHIFF documentation is now hosted on Google App Engine at the http://whiffdoc.appspot.com/ domain. What is WHIFF? WHIFF is a collection of support services for WSGI/Python web applications which allows applications to be composed by "dropping" dynamic pages into container directories. This mode of development will be familiar to developers who have created PHP applications, vanilla CGI scripts, Apache/modpy Publisher applications, JSP pages, or static web content. The WHIFF implementation significantly generalizes the "drop in" paradigm to support WSGI middleware components and application fragments as well as stand-alone pages. WHIFF provides other services in addition to supporting "drop in" components, such as managed application resources. WHIFF requires Python 2.5 or better to run out-of-the-box. Unless significant problems appear in the next month or so I think this release will be the last beta release and the next release will add a couple more features to become WHIFF 1.0. For more fun please have a look at my community list/tree maker at http://listtree.appspot.com which is inspired by Guido van Rossum's excellent faqwiz. ListTree is implemented on Google App Engine using WHIFF. I hope you like. -- Aaron Watters === Talk low. Talk slow. And don't say a lot. -- John Wayne's advice to Clint Eastwood From nobody at nowhere.com Wed Dec 9 12:24:42 2009 From: nobody at nowhere.com (Nobody) Date: Wed, 09 Dec 2009 17:24:42 +0000 Subject: subprocess kill References: <5f755846-e79d-444b-b608-86f5823540e8@j19g2000yqk.googlegroups.com> <68cd2042-cd2a-43a8-97ae-2893f181168c@c3g2000yqd.googlegroups.com> <011ae123-d777-438c-83b6-f6600c1dfde1@m25g2000yqc.googlegroups.com> <786e4fb7-1f03-45d5-9be0-55926387283f@s20g2000yqd.googlegroups.com> Message-ID: On Mon, 07 Dec 2009 11:04:06 +0100, Jean-Michel Pichavant wrote: > When using shell=True, your process is started in a shell, meaning the > PID of your subprocess is not self.luca.pid, self.luca.pid is the PID of > the shell. This isn't true for a simple command on Unix (meaning a program name plus arguments, and redirections, rather than e.g. a pipeline or a command using subshells, flow-control constructs, etc). For a simple command, "/bin/sh -c 'prog arg arg ...'" will exec() the program *without* fork()ing, so the program will "take over" the shell's process and PID. You can verify this by running e.g.: import subprocess p = subprocess.Popen('sleep 10', shell=True) print p.pid subprocess.call('ps') p.wait() From wimmersimon at googlemail.com Wed Dec 9 12:36:34 2009 From: wimmersimon at googlemail.com (SiWi) Date: Wed, 9 Dec 2009 09:36:34 -0800 (PST) Subject: Sum of the factorial of the digits of a number - wierd behaviour Message-ID: <5b7b2fca-67f2-4d13-9965-293368cb9ba3@d10g2000yqh.googlegroups.com> Dear python community, I've got a wierd problem and I hope you can help me out at it. I wrote the following code to find the Sum of the factorial of the digits of a number (this is for Project Euler 74): def fac(n): x=1 for i in range(2,n+1): x*=i return x t=tuple(fac(n) for n in range(1,10)) def decimals(x): i=1 d=[] while x>0: d.append(x%10) x=x/10 return d def sumfac(x): return sum(t[n-1] for n in decimals(x)) The problem is that i get the following results, for which I can't see any reason: sumfac(145)->145 (1!+4!+5!=1 + 24 +120 = 145) - ok sumfac(1454)-> 169 - ok sumfac(45362) -> 872 - ok sumfac(363600) -> 727212 - wrong, should be1454 Greetings, SiWi. From patrickstinson.lists at gmail.com Wed Dec 9 12:38:29 2009 From: patrickstinson.lists at gmail.com (Patrick Stinson) Date: Wed, 9 Dec 2009 10:38:29 -0700 Subject: xmlrpc idea for getting around the GIL In-Reply-To: References: <6214d7a20911221338l30296032y32d2d1215de57b6d@mail.gmail.com> <83303a84-a8ca-486a-8173-ef0892779f39@x16g2000vbk.googlegroups.com> <4b0b07a1$0$22159$9b622d9e@news.freenet.de> Message-ID: <6214d7a20912090938m5efb2892na66cabbf0e7e34d6@mail.gmail.com> On Wed, Dec 2, 2009 at 7:42 AM, sturlamolden wrote: > On 2 Des, 02:47, Patrick Stinson > wrote: > >> We don't need extension modules, and all we need to do is run some >> fairly basic scripts that make callbacks and use some sip-wrapped >> types. > > Sure, you use SIP but not extension modules... > > >> - Python is not suitable for real-time work. >> >> Not true. We have been running python callback code using >> PyObject_CallObject from within our audio thread for some time without >> a problem, and it's *extremely* fast. > > It seems you are confusing "real-time" with "real-fast". The fact that > something runs fast does not make it "real-time". > > Python is not suitable for real-time applications, nor are the OSes > commonly used to run Python. > Semantics aside, my point is that it runs well enough in our environment. If the audio is smooth, it is considered "working". > > >> We >> need just a liiiitle push to get our code to work at low latencies, >> and the only thing that is standing in our way is that all threads >> 9usually around 20 have to block on the Gil, and this causes small >> gaps in the sound at low latencies (around 5ms, or 64 sample period). >> >> ...almost perfect. > > Python is not programmed with real-time applications in mind: You have > no guarrantees on maximum time-lag when a thread is blocked on the > GIL. We don't need theoretical guarantees, because we've tried it and it works. That's the bottom line > > "Priority requests" (i.e. pre-emptive multitasking) was removed from > Antoine's "newgil" branch, but that is the kind of mechanism you would > need. Even with priority requests, Python would not be suitable for > real-time apps, as extension modules (e.g. C++ wrapped with SIP) can > hold the GIL forever. see above. > > You will also need an OS with a real-time scheduler and a real-time C > library, such as QNX or VxWorks. > > I find thea idea of a true real-time Python very interesting, but it > would take a completely reworked interpreter. > > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > From wimmersimon at googlemail.com Wed Dec 9 12:39:51 2009 From: wimmersimon at googlemail.com (SiWi) Date: Wed, 9 Dec 2009 09:39:51 -0800 (PST) Subject: Sum of the factorial of the digits of a number - wierd behaviour References: <5b7b2fca-67f2-4d13-9965-293368cb9ba3@d10g2000yqh.googlegroups.com> Message-ID: <2128a693-638a-4228-bb5d-b4aa0afb3abb@a21g2000yqc.googlegroups.com> On Dec 9, 6:36?pm, SiWi wrote: > Dear python community, > I've got a wierd problem and I hope you can help me out at it. > I wrote the following code to find the Sum of the factorial of the > digits of a number (this is for Project Euler 74): > > def fac(n): > ? ? x=1 > ? ? for i in range(2,n+1): > ? ? ? ? x*=i > ? ? return x > > t=tuple(fac(n) for n in range(1,10)) > > def decimals(x): > ? ? i=1 > ? ? d=[] > ? ? while x>0: > ? ? ? ? d.append(x%10) > ? ? ? ? x=x/10 > ? ? return d > > def sumfac(x): > ? ? return sum(t[n-1] for n in decimals(x)) > > The problem is that i get the following results, for which I can't see > any reason: > sumfac(145)->145 (1!+4!+5!=1 + 24 +120 = 145) - ok > sumfac(1454)-> 169 - ok > sumfac(45362) -> 872 - ok > sumfac(363600) -> 727212 - wrong, should be1454 > > Greetings, > SiWi. Oops, found it myself. You can ignote the message above. From apt.shansen at gmail.com Wed Dec 9 12:40:09 2009 From: apt.shansen at gmail.com (Stephen Hansen) Date: Wed, 9 Dec 2009 09:40:09 -0800 Subject: How do I Block Events in wxPython In-Reply-To: <17ed589d-f8e2-4fac-b489-5f62060ecd17@j19g2000yqk.googlegroups.com> References: <6854a0bb-9edc-4392-9761-d2f3cf98f89e@k4g2000yqb.googlegroups.com> <17ed589d-f8e2-4fac-b489-5f62060ecd17@j19g2000yqk.googlegroups.com> Message-ID: <7a9c25c20912090940h7f25c75eva5e0b357b68494d8@mail.gmail.com> On Wed, Dec 9, 2009 at 9:06 AM, Wanderer wrote: > Found another strange bug (Strange to me, anyway). int(0.8 * 10.0) = > 7. Had to change the code to int(0.8 * 10.0 + 0.0001). > > http://effbot.org/pyfaq/why-are-floating-point-calculations-so-inaccurate.htm Floating point math is not precise; if you need precision, use the decimal module. Alternately, you can just be sure to round() your floats to whatever precision you need to consider significant after calculations. --S -------------- next part -------------- An HTML attachment was scrubbed... URL: From massimodipierro71 at gmail.com Wed Dec 9 12:47:20 2009 From: massimodipierro71 at gmail.com (mdipierro) Date: Wed, 9 Dec 2009 09:47:20 -0800 (PST) Subject: How decoupled are the Python frameworks? References: <6316c8e5-34a0-43e3-92ad-966d95e84108@j24g2000yqa.googlegroups.com> Message-ID: Interesting post. I would like to make some comments about design decisions that went into web2py: - For each app Model/View/Controllers/Language Files/Static Files/ Modules/Cron Tasks are stored in separated folders - You can code only the models (no controllers and no view) and you get a fully functional admin interface - You can develop only controllers (with or without models but no views) and you get a fully working application with workflow - There is a convention for dispatching. You can override it with routes. - There is no metadata in the framework. URLs are mapped into an app (within the web2py instance), into a controller file, and into a function (action) in that controller file. - You can have multiple apps within a web2py instance (they can be installed, uninstalled, packaged, compiled without restarting web2py) - You can have multiple model files, multiple controllers and multiple views. You can override the mapping between controllers and default views. - You can group files (models/controllers/views/static files) functionally into plugins. Plugins can be packaged separately from the app and applied to multiple apps. - Plugins expose components (i.e. reusable objects that can be embedded in a page and talk to their own controllers via ajax). - Plugin components are coded as any other web2py models/controller/ view but the form submission is automatically trapped (transparently to the user) and executed via ajax so that, if the component contains a form only the component is reloaded upon submissions of the form. - web2py supports FORM, SQLFORM, SQLFORM.factory and CRUD for automtical generation of forms (from a model or other structure). All web2py forms execute postbacks and modify themselves to report error messages. A form is comprised of widgets that contain validators. There is a default layout but it can be customized in the view by allocating widgets or individual html tags. - You can put doctests in actions and we provide a web interface for testing the app online. - It completely abstracts the database backend (we support 10 different database backends including Google App Engine) thus make the code very portable. - It authomatically writes sql for queries, for create table and alter table. -Web2py provides a Role Based Access Control mechanism with plugguble login components so that you can authenticate using multiple mechanism including Gmail and Twitter for example. Specifically about you concerns:- better scalability - easy to test => web2py is very easy to test because of the web based interface to doctests - easy to maintain => In web2py "Do not repeat yourself" trumps "explicit if better than implicit". This means code is very compact. - easy to re-use code for different applications => using plugins - easy to migrate/port => because of DAL Massimo On Dec 7, 4:38?pm, shocks wrote: > Hi > > I'm getting back into Python after a long break. ?I've been developing > large enterprise apps solely with Adobe Flex (ActionScript) for the > past couple years. ?During that time I've used a number of 'MVC' > frameworks to glue the bits together - among them Cairngorm, a > modified implementation of Cairngorm using the Presentation Model > pattern, PureMVC, Mate (an IOC container but with an MVC > implementation) and Parsley (IOC but you have to roll-you-own MVC). > During that time I've been in large teams (30 Flex + 30 Java) to small > teams (2 Flex + 1 Java). ?The motivation of these frameworks is the > decouple your concerns, allowing your apps to be more scalable, easier > to test, and ?supposedly easier to maintain. ?Some do the decoupling > better job than others, but there is also the question of "how > decoupled is your code from the framework"? ?It's all well and good > having something clever working behind the scenes wiring and routing > everything together, but I wonder where this leaves the code base if > the framework, which was selected at the beginning of the project, is > replaced with something else months or years later (i.e. the framework > just doesn't scale as expected, the community involvement dies and > it's no longer maintained properly, etc). ?I've seen it happen and > I've been experienced the pain of detangling massive amounts of code > which is full of framework specific imports, methods and boilerplate > code. ?And then there's updating the unit tests! > > My question is how good are the current crop of Python frameworks? > I've used Django twice in production and didn't like that much. ?The > implementation is Django specific for starters. ?I've picked up Pylons > and I'm trying that out. ?I'm not sure how well it fares? ?I do feel a > bit uneasy about the code generation that some of the Python > frameworks do. ?Pylons creates something like 20 files for a > 'helloworld'. ?It does do some great things out of the box, but I > wonder where that leaves your own code. ?After spending 3-6 months on > your Pylons webapp, how easy is it to move to something else? ?Maybe > one of the Python IOC once they mature. ?What are some good techniques > people are using to future (framework) proof their apps? > > I'm interested to hear people experiences with the various frameworks > and how decoupled their code is from them. ?The best of the current > Flex frameworks for me is Parsley. ?The only noticeable Parlsey code > is an '[Inject]' meta tag here and there and a couple import > statements. ?All the complicated object creation and messaging is done > higher up the chain. > > Cheers, > Ben From tjreedy at udel.edu Wed Dec 9 12:51:55 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 09 Dec 2009 12:51:55 -0500 Subject: tkinter photoimage, couldn't recognize image data (PPM) In-Reply-To: References: Message-ID: Martin P. Hellwig wrote: > Hi all, > > I've tried to display an image with the source being a string but it > fails (see below). Is there a way to display PPM without writing it > first to a file? > > Thanks, > > Martin > > ----- snippet ----- > ''' > Ubuntu 9.04 64bit, python 3.1 > ''' > import tkinter > > DATA="""P3 > 3 2 > 255 > 255 0 0 0 255 0 0 0 255 > 255 255 0 255 255 255 0 0 0""" Should the string really have the newlines? Or should this be DATA="""P3\ 3 2\ 255\ 255 0 0 0 255 0 0 0 255\ 255 255 0 255 255 255 0 0 0""" > def display(): > tk = tkinter.Tk() > canvas = tkinter.Canvas(tk, width=3, height=2) > canvas._image_reference = tkinter.PhotoImage(format='ppm', data=DATA) > canvas.create_image((0,0), image=canvas._image_reference) > canvas.pack() > tk.after(1500, tk.quit) > tk.mainloop() > > if __name__ == '__main__': > display() > ----- > > ----- traceback ----- > Traceback (most recent call last): > File "/home/martin/DCUK > Technologies/workspace/mhellwig/src/test/tkintering.py > ", line 24, in > display() > File "/home/martin/DCUK > Technologies/workspace/mhellwig/src/test/tkintering.py > ", line 17, in display > canvas._image_reference = tkinter.PhotoImage(format='ppm', data=DATA) > File "/usr/local/lib/python3.1/tkinter/__init__.py", line 3269, in > __init__ > Image.__init__(self, 'photo', name, cnf, master, **kw) > File "/usr/local/lib/python3.1/tkinter/__init__.py", line 3225, in > __init__ > self.tk.call(('image', 'create', imgtype, name,) + options) > _tkinter.TclError: couldn't recognize image data > ----- > From nobody at nowhere.com Wed Dec 9 12:53:21 2009 From: nobody at nowhere.com (Nobody) Date: Wed, 09 Dec 2009 17:53:21 +0000 Subject: When will Python 3 be fully deployed References: Message-ID: On Sun, 06 Dec 2009 22:10:15 +0000, Edward A. Falk wrote: >>I recently read that many libraries, including Numpy have not been >>ported to Python 3. >> >>When do you think that Python 3 will be fully deployed? > > It will never be fully deployed. There will always be people out there who > haven't felt it necessary to upgrade their systems. Moreover, there will always be people out there who have felt it necessary not to upgrade their systems. IMNSHO, Python 2 will still be alive when Python 4 is released. If python.org doesn't want to maintain it, ActiveState will. In particular: for Unix scripting, Python 3's Unicode obsession just gets in the way. Ultimately, argv, environ, filenames, etc really are just byte strings. Converting to Unicode just means that the first thing that the script does is to convert back to bytes. I'm sure that the Unicode approach works great on Windows, where wchar_t is so pervasive that Microsoft may as well have just redefined "char" (even to the point of preferring UTF-16-LE for text files over UTF-8, ASCII-compatibility be damned). But on Unix, it's a square-peg-round-hole situation. From freesoft12 at gmail.com Wed Dec 9 12:57:36 2009 From: freesoft12 at gmail.com (nick) Date: Wed, 9 Dec 2009 09:57:36 -0800 (PST) Subject: Implementation suggestions for creating a Hierarchical circuit database Message-ID: <5476262c-67f7-49c6-aa09-05c7fcb1e362@v30g2000yqm.googlegroups.com> Hi, I am writing a personal software that will read circuit design/ netlist. I will be using the MCNC benchmarks that contain different types of designs in SPICE netlist format. I need some pointers/papers/suggestions on creating a "hierarchical" netlist database. The netlist database can, at times, be fully flattened, partially flattened or fully hierarchical. I should be able to answer queries like: are there any capacitors connected to node: x1.x2.n1? My program is currently only for analyzing designs for connectivity, types of elements (resistors/capacitors) and figuring out some simple electrical properties. I am just starting, so please bear with me if I haven't thought about corner cases. Regards Nick From mccredie at gmail.com Wed Dec 9 13:02:21 2009 From: mccredie at gmail.com (Matt McCredie) Date: Wed, 9 Dec 2009 18:02:21 +0000 (UTC) Subject: switch References: <335204.99872.qm@web57905.mail.re3.yahoo.com> Message-ID: hong zhang yahoo.com> writes: > > List, > > Python does not have switch statement. Any other option does similar work? > Thanks for help. > > --henry > > I see a couple of people have mentioned using a dictionary. If the value that you are switching on is a string, or could be made into one, you can use a variant of the command dispatch pattern. class MyCommandDispatcher(object): def do_a(self): # do stuff def do_b(self): # do stuff def do_5(self): # do stuff def default(self): # do stuff def switch(self, option): getattr(self, 'do_' + str(option), self.default)() d = MyCommandDispatcher() d.switch('a') d.switch(5) This isn't _much_ more coding than using the dictionary method, and is pretty readable. This is also a common pattern in python. Matt From rami.chowdhury at gmail.com Wed Dec 9 13:28:40 2009 From: rami.chowdhury at gmail.com (Rami Chowdhury) Date: Wed, 9 Dec 2009 10:28:40 -0800 Subject: When will Python 3 be fully deployed In-Reply-To: References: Message-ID: <2f79f590912091028k612035dj4d13c98123383590@mail.gmail.com> On Wed, Dec 9, 2009 at 09:53, Nobody wrote: > > I'm sure that the Unicode approach works great on Windows, where wchar_t > is so pervasive that Microsoft may as well have just redefined "char" > (even to the point of preferring UTF-16-LE for text files over UTF-8, > ASCII-compatibility be damned). > > But on Unix, it's a square-peg-round-hole situation. I dunno, I find it rather useful not to have to faff about with encoding to/from when working with non-ASCII files (with non-ASCII filenames) on Linux. -------- Rami Chowdhury "Never assume malice when stupidity will suffice." -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) > > -- > http://mail.python.org/mailman/listinfo/python-list > From martin.hellwig at dcuktec.org Wed Dec 9 13:35:40 2009 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Wed, 09 Dec 2009 18:35:40 +0000 Subject: tkinter photoimage, couldn't recognize image data (PPM) In-Reply-To: References: Message-ID: Terry Reedy wrote: >> DATA="""P3 >> 3 2 >> 255 >> 255 0 0 0 255 0 0 0 255 >> 255 255 0 255 255 255 0 0 0""" > > Should the string really have the newlines? Or should this be > DATA="""P3\ > 3 2\ > 255\ > 255 0 0 0 255 0 0 0 255\ > 255 255 0 255 255 255 0 0 0""" > I've tried it, still same error, I did had a look at http://netpbm.sourceforge.net/doc/ppm.html and the wikipedia page. >> self.tk.call(('image', 'create', imgtype, name,) + options) >> _tkinter.TclError: couldn't recognize image data >> ----- >> > -- MPH http://blog.dcuktec.com 'If consumed, best digested with added seasoning to own preference.' From tjreedy at udel.edu Wed Dec 9 13:48:38 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 09 Dec 2009 13:48:38 -0500 Subject: ANN: WHIFF.0.7 += GAE + jQueryUI + internationalization + testdrive = (last beta?) In-Reply-To: References: Message-ID: Aaron Watters wrote: > Also the WHIFF documentation is now hosted on Google App > Engine at the http://whiffdoc.appspot.com/ domain. When I went there and clicked on the "scatter chart is generated by a straightforward invocation of the standard WHIFF OpenFlashChart middleware: ", Firefox *immediately* opened the 'Official' page of a well-known ugly cult www.sci-----logy.org in a new tab. Something is very, very wrong. I really hope this was not intentional on your part. When I load the doc page again and click the chart box again, the chart is reloaded from the local cache instead of your site and no tab is opened. tjr From nobody at nowhere.com Wed Dec 9 13:50:29 2009 From: nobody at nowhere.com (Nobody) Date: Wed, 09 Dec 2009 18:50:29 +0000 Subject: switch References: <335204.99872.qm@web57905.mail.re3.yahoo.com> Message-ID: On Tue, 08 Dec 2009 21:02:44 -0800, Kee Nethery wrote: > I string together a bunch of elif statements to simulate a switch > > if foo == True: > blah > elif bar == True: > blah blah > elif bar == False: > blarg > elif .... This isn't what would normally be considered a switch (i.e. what C considers a switch). A switch tests the value of an expression against a set of constants. If you were writing the above in C, you would need to use a chain of if/else statements; you couldn't use a switch. Compiled languages' switch statements typically require constant labels as this enables various optimisations. The above construct is equivalent to Lisp's "cond", or guards in some functional languages. While switch-like constructs can be implemented with a dictionary, cond-like constructs would have to be implemented with a list, as there's no guarantee that the tests are mutually exclusive, so the order is significant. E.g. rules = [((lambda (foo, bar): return foo), (lambda: blah)), ((lambda (foo, bar): return bar), (lambda: blah blah)), ((lambda (foo, bar): return not bar), (lambda: blarg)), ...] for test, action in rules: if test(foo, bar): action() break From n00m at narod.ru Wed Dec 9 13:53:11 2009 From: n00m at narod.ru (n00m) Date: Wed, 9 Dec 2009 10:53:11 -0800 (PST) Subject: Brent's variation of a factorization algorithm References: <4B1EA031.9010907@mrabarnett.plus.com> Message-ID: <1a9900e4-c9d6-49bd-aefe-8780433ef030@g7g2000yqa.googlegroups.com> Being an absolute dummy in Theory of Number for me ***c'est fantastique*** that brent() works =) PS 1. Values of magic parameters c = 11 and m = 137 almost don't matter. Usually they choose c = 2 (what about to run brent() in parallel with different values of "c" waiting for "n" is cracked?) 2. Before calling brent() "n" should be tested for its primality. If it is a prime brent(n) may freeze for good. 3. > A better place to publish this code would be the Python Cookbook: It requires a tedious registration etc. Gabriel, don't you mind to publish the code there by yourself? In the long run, it is an invention by Richard Brent (b.1946) =) I just rewrote it to Python from a pseudo-code once available in Wiki but which for some vague reason was later on removed from there. From tdorsey at zindagigames.com Wed Dec 9 13:57:43 2009 From: tdorsey at zindagigames.com (Trevor Dorsey) Date: Wed, 9 Dec 2009 10:57:43 -0800 Subject: attributes, properties, and accessors -- philosophy In-Reply-To: <4b0d5f78$0$23304$426a74cc@news.free.fr> References: <4b0b92de$0$14677$426a74cc@news.free.fr> <4b0cfefa$0$24750$426a34cc@news.free.fr> <4b0d5f78$0$23304$426a74cc@news.free.fr> Message-ID: <359be4620912091057jf503f44o433ed7af6e9e52d5@mail.gmail.com> Back to the subject of good tools. Use an IDE that's intended for python. We started using WingIDE because it had an inline debugger and came with all the nice things like autocomplete etc that things like eclipse or visual studio have. On Wed, Nov 25, 2009 at 8:46 AM, Bruno Desthuilliers wrote: > Ethan Furman a ?crit : > > >> Very helpful, thank you. Hopefully my brain will be up to the descriptor >> protocol this time... the last couple times were, um, less than successful. >> :) >> > > Well, it's quite simple in fact. Most of the "magic" happens in > object.__getattribute__ and object.__setattr__. You'll find a rough > description of what happens here: > > > http://groups.google.com/group/comp.lang.python/browse_frm/thread/a136f7626b2a8b7d/70a672cf7448c68e > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -Trevor D -------------- next part -------------- An HTML attachment was scrubbed... URL: From grpadmin at gmail.com Wed Dec 9 14:09:31 2009 From: grpadmin at gmail.com (Ask me about System Design) Date: Wed, 9 Dec 2009 11:09:31 -0800 (PST) Subject: Implementation suggestions for creating a Hierarchical circuit database References: <5476262c-67f7-49c6-aa09-05c7fcb1e362@v30g2000yqm.googlegroups.com> Message-ID: On Dec 9, 9:57?am, nick wrote: > Hi, > > I am writing a personal software that will read circuit design/ > netlist. I will be using the MCNC benchmarks that contain different > types of designs in SPICE netlist format. > > I need some pointers/papers/suggestions on creating a "hierarchical" > netlist database. The netlist database can, at times, be fully > flattened, partially flattened or fully hierarchical. I should be able > to answer queries like: are there any capacitors connected to node: > x1.x2.n1? > > My program is currently only for analyzing designs for connectivity, > types of elements (resistors/capacitors) and figuring out some simple > electrical properties. > > I am just starting, so please bear with me if I haven't thought about > corner cases. > > Regards > Nick If you start by considering just the flattened case, you will find that the underlying database is not much more than a labeled graph. Make sure the code (or specs anyway) to handle that case is rock solid before trying non-flattened versions. You don't want to be fixing those problems when you move to the non-flat situations. I used to work at a CAE (computer-aided enigineering) vendor where commercial software was developed to do this, plus simulation and layout (and other considerations). One issue was name resolution and linking signals across different levels. Another issue was using shared (nested) designs, where one page was used to specify a component and other pages used several instances of that component, but I don't know if the flattened version contained copies of the subcircuit or different references to (virtual) copies of the subcircuit. I advise implementing limited hierarchical features and debugging them thoroughly before you move on. E.g., make sure mutli-page designs work, then try multi-level, then nested, etc. If you limit your specs in the beginning, you will be able to build and test prototype versions quickly. Your eventual end-design will hinge on answers to questions like: Am I only doing lookup and simple local queries, or will I have to provide a flattened version of the design? If you only have to do local queries, then you can "build" a virtual copy of what you need in a subcircuit and then throw it away; if you need a flattened version, then several actual copies of the subcircuit need to be built and printed out. So even before you build a good spec, you should have a good set of questions whose answers will help determine the specification and direct the design. Mentor Graphics is still around; they may have someone who can give you pointers to aid in your project. Also many issues are addressed by CAD software; hopefully you will ask on those forums. Try hardware and CAD forums as well as comp.* forums Gerhard "Ask Me About System Design" Paseman, 2009.12.09 From kst-u at mib.org Wed Dec 9 14:13:44 2009 From: kst-u at mib.org (Keith Thompson) Date: Wed, 09 Dec 2009 11:13:44 -0800 Subject: Implementation suggestions for creating a Hierarchical circuit database References: <5476262c-67f7-49c6-aa09-05c7fcb1e362@v30g2000yqm.googlegroups.com> Message-ID: nick writes: > I am writing a personal software that will read circuit design/ > netlist. I will be using the MCNC benchmarks that contain different > types of designs in SPICE netlist format. [snip] You cross-posted this question to comp.theory, comp.lang.c++, comp.lang.c, comp.lang.python, and sci.math. Since you don't mention anything about any implementation language, I don't see how your question is relevant to any of the comp.lang.* groups. If you have questions about a particular language, feel free to post to comp.lang.whatever. (I won't bother to redirect followups, since that affects only followups to *this* article, but please consider trimming the newsgroups line.) -- Keith Thompson (The_Other_Keith) kst-u at mib.org Nokia "We must do something. This is something. Therefore, we must do this." -- Antony Jay and Jonathan Lynn, "Yes Minister" From nobody at nowhere.com Wed Dec 9 14:25:40 2009 From: nobody at nowhere.com (Nobody) Date: Wed, 09 Dec 2009 19:25:40 +0000 Subject: When will Python 3 be fully deployed References: Message-ID: On Wed, 09 Dec 2009 10:28:40 -0800, Rami Chowdhury wrote: >> But on Unix, it's a square-peg-round-hole situation. > > I dunno, I find it rather useful not to have to faff about with > encoding to/from when working with non-ASCII files (with non-ASCII > filenames) on Linux. For the kind of task I'm referring to, there is no encoding or decoding. You get byte strings from argv, environ, files, etc, and pass them to library functions. What those bytes "mean" as text (if anything) never enters the equation. For cases where you *need* text (e.g. GUIs), Python 3 makes the simplest cases easier. The more complex cases (e.g. where each data source may have its own encoding, or even multiple encodings) aren't much different between Python 2 and Python 3. From henryzhang62 at yahoo.com Wed Dec 9 14:32:18 2009 From: henryzhang62 at yahoo.com (hong zhang) Date: Wed, 9 Dec 2009 11:32:18 -0800 (PST) Subject: IndentationError In-Reply-To: Message-ID: <506405.21155.qm@web57906.mail.re3.yahoo.com> List, I got error says IndentationError in end of line. I could not figure out why. See following: $ ./cont-mcs File "./cont-mcs", line 264 mcs1 = ht_val+cck_val+green_val+fat_val+sgi_val ^ IndentationError: unindent does not match any outer indentation level Thanks for help. --henry From aaron.watters at gmail.com Wed Dec 9 14:33:57 2009 From: aaron.watters at gmail.com (Aaron Watters) Date: Wed, 9 Dec 2009 11:33:57 -0800 (PST) Subject: ANN: WHIFF.0.7 += GAE + jQueryUI + internationalization + testdrive = (last beta?) References: Message-ID: <954766b0-3b3e-47d6-943e-364d34a619af@v30g2000yqm.googlegroups.com> On Dec 9, 1:48?pm, Terry Reedy wrote: > Aaron Watters wrote: > > Also the WHIFF documentation is now hosted on Google App > > Engine at thehttp://whiffdoc.appspot.com/domain. > > When I went there and clicked on the "scatter chart is generated by a > straightforward invocation of the standard WHIFF OpenFlashChart > middleware: ", Firefox *immediately* opened the 'Official' page of a > well-known ugly cultwww.sci-----logy.orgin a new tab. Something is > very, very wrong. I really hope this was not intentional on your part. > > When I load the doc page again and click the chart box again, the chart > is reloaded from the local cache instead of your site and no tab is opened. > > tjr That was a joke in the tree view. You clicked on the "science link" in the tree hierarchy. I will fix it due to your complaint. Nothing is very very wrong :), it was just a misguided joke (the bio link also goes off to someone fisherman's biography...) Sorry about that. Thanks for the feedback. -- Aaron Watters === want a friend? get a dog. -- Truman From python at bdurham.com Wed Dec 9 14:34:41 2009 From: python at bdurham.com (python at bdurham.com) Date: Wed, 09 Dec 2009 14:34:41 -0500 Subject: Recommendation for small, fast, Python based web server Message-ID: <1260387281.5558.1349282363@webmail.messagingengine.com> I'm looking for a small, simple, fast, Python based web server for a simple, client side application we're building. We don't want to distrubute and support a "real" web server like Apache or Tomcat or depend on the presence of local web server such as IIS. The application in question will service AJAX requests from a browser. We're not looking for a web framework like Django, Plone, etc. I've looked at the web servers that come bundled with the Python standard library[1] and they are too slow. I suspect this is because they don't maintain a session between the client and server, thus every GET/POST request repeats the session setup and break down process. Or they might be based on a polling model? Here are the other Python based web server implementations I'm aware of: - cherrypy - web.py - twisted Any recommendations appreciated (Python 2.6 preferred but open to Python 3.1 options). Thanks! Malcolm [1] http://docs.python.org/library/basehttpserver.html (base) http://docs.python.org/library/simplehttpserver.html http://docs.python.org/library/cgihttpserver.html -------------- next part -------------- An HTML attachment was scrubbed... URL: From rami.chowdhury at gmail.com Wed Dec 9 14:43:19 2009 From: rami.chowdhury at gmail.com (Rami Chowdhury) Date: Wed, 9 Dec 2009 11:43:19 -0800 Subject: When will Python 3 be fully deployed In-Reply-To: References: Message-ID: <2f79f590912091143x4e5fa4e9x224a12183cca1130@mail.gmail.com> On Wed, Dec 9, 2009 at 11:25, Nobody wrote: > On Wed, 09 Dec 2009 10:28:40 -0800, Rami Chowdhury wrote: > >>> But on Unix, it's a square-peg-round-hole situation. >> >> I dunno, I find it rather useful not to have to faff about with >> encoding to/from when working with non-ASCII files (with non-ASCII >> filenames) on Linux. > > For the kind of task I'm referring to, there is no encoding or decoding. > You get byte strings from argv, environ, files, etc, and pass them to > library functions. What those bytes "mean" as text (if anything) never > enters the equation. Perhaps we're referring to slightly different tasks, then. I'm thinking of scripts to move log files around, or archive documents, where some manipulation of file and folder names is necessary -- that's where I personally have been bitten by encodings and the like (especially since I was moving around between filesystems, as well). But I take your point that the more complex cases are complex regardless of Python version. From irmen at -nospam-xs4all.nl Wed Dec 9 14:49:29 2009 From: irmen at -nospam-xs4all.nl (Irmen de Jong) Date: Wed, 09 Dec 2009 20:49:29 +0100 Subject: Question about 'remote objects' In-Reply-To: References: Message-ID: <4b1fff07$0$22936$e4fe514c@news.xs4all.nl> On 9-12-2009 13:56, Frank Millman wrote: > My first thought was to look into Pyro. It seems quite nice. One concern I > had was that it creates a separate thread for each object made available by > the server. It doesn't. Pyro creates a thread for every active proxy connection. You can register thousands of objects on the server, as long as your client programs only access a fraction of those at the same time you will have as many threads as there are proxies in your client programs. This behavior can be tuned a little as well: - you can tell Pyro to not use threading at all (that will hurt concurrency a lot though) - you can limit the number of proxies that can be connected to the daemon at a time. > Then I thought that, instead of the database server exposing each object > remotely, I could create one 'proxy' object on the server through which all > clients would communicate, and it in turn would communicate with each > instance locally. I think that this is the better design in general: access large amounts of remote objects not individually, but as a batch. Lots of small remote calls are slow. A few larger calls are more efficient. > Is there any particular benefit in using remote objects as opposed to > writing a SocketServer? It saves you reinventing the wheel and dealing with all its problems again, problems that have been solved already in existing remote object libraries such as Pyro. Think about it: do you want to spend time implementing a stable, well defined communication protocol, or do you want to spend time building your actual application logic? Regards, Irmen. From aaron.watters at gmail.com Wed Dec 9 14:57:38 2009 From: aaron.watters at gmail.com (Aaron Watters) Date: Wed, 9 Dec 2009 11:57:38 -0800 (PST) Subject: ANN: WHIFF.0.7 += GAE + jQueryUI + internationalization + testdrive = (last beta?) References: <954766b0-3b3e-47d6-943e-364d34a619af@v30g2000yqm.googlegroups.com> Message-ID: <34fef074-beaf-4bc0-9251-08dbfbd43d98@u7g2000yqm.googlegroups.com> > That was a joke in the tree view. ?You clicked on the "science link" > in the tree hierarchy. ?I will fix it due to your complaint. Fixed. Now clicking on the same link goes to "Scientific American". http://whiffdoc.appspot.com/ Is that humourless enough for you? :) You are now immortalized in the WHIFF repository http://aaron.oirt.rutgers.edu/cgi-bin/whiffRepo.cgi/rev/6d8c650102dd Please let me know if anything else offends your sensibilities. Thanks again, -- Aaron Watters === an apple every 8 hours will keep 3 doctors away. -- kliban From python.list at tim.thechases.com Wed Dec 9 14:57:48 2009 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 09 Dec 2009 13:57:48 -0600 Subject: switch In-Reply-To: <68e6e315-f3c7-4e52-a56f-802e99d75e6a@y32g2000prd.googlegroups.com> References: <335204.99872.qm@web57905.mail.re3.yahoo.com> <68e6e315-f3c7-4e52-a56f-802e99d75e6a@y32g2000prd.googlegroups.com> Message-ID: <4B20013C.9080907@tim.thechases.com> Carl Banks wrote: > What if the object is a string you just read from a file? > > How do you dispatch using polymorphism in that case? This is where I most miss a switch/case statement in Python...I do lots of text-file processing (cellular provider data), so I have lots of code (for each provider's individual format) that looks like phones = {} for row in csv.DictReader(file('data.txt', 'rb')): phonenumber = row['phonenumber'] if phonenumber not in phones: phones[phonenumber] = Phone(phonenumber) phone = phones[phonenumber] rectype = rectype if rectype == '01': phone.international += Decimal(row['internationalcost']) elif rectype == '02': phone.text_messaging += ( int(row['textmessages sent']) + int(row['pages received']) + int(row['textmessages sent']) + int(row['pages received']) elif rectype == ... ... else: raise WhatTheHeckIsThis() which would nicely change into something like switch row['recordtype']: case '01': phone.international += Decimal(row['internationalcost']) // optionally a "break" here depending on // C/C++/Java/PHP syntax vs. Pascal syntax which // doesn't have fall-through case '02': phone.text_messaging += ( int(row['textmessages sent']) + int(row['pages received']) + int(row['textmessages sent']) + int(row['pages received']) ... default: raise WhatTheHeckIsThis() This doesn't convert well (i.e. compactly) to a dictionary-dispatch idiom. :( -tkc From patrickstinson.lists at gmail.com Wed Dec 9 15:04:45 2009 From: patrickstinson.lists at gmail.com (Patrick Stinson) Date: Wed, 9 Dec 2009 13:04:45 -0700 Subject: using freeze.py with python3 Message-ID: <6214d7a20912091204h2d176b55m75afdd0dc18851f@mail.gmail.com> Has anyone tried using Python-3.1.1/Tools/freeze/freeze.py with the encodings package? It appears that encodings is required to intialize the interpreter, but PyImport_ImportFrozenModule is failing for the "encodings" module in marshal.c:r_object(), after trying to demarshal an object of type 0. The failing callstack looks like this: #0 0x00599114 in PyImport_ImportFrozenModule at import.c:2011 #1 0x00598b14 in load_module at import.c:1830 #2 0x0059aef2 in import_submodule at import.c:2631 #3 0x0059a2ed in load_next at import.c:2436 #4 0x00599629 in import_module_level at import.c:2153 #5 0x00599a80 in PyImport_ImportModuleLevel at import.c:2204 #6 0x00565b76 in builtin___import__ at bltinmodule.c:173 #7 0x004e6cfc in PyCFunction_Call at methodobject.c:84 #8 0x0048fbe5 in PyObject_Call at abstract.c:2160 #9 0x0048fd94 in call_function_tail at abstract.c:2192 #10 0x0048fe6e in PyObject_CallFunction at abstract.c:2216 #11 0x0059b7f6 in PyImport_Import at import.c:2811 #12 0x0059945e in PyImport_ImportModule at import.c:2064 #13 0x00599551 in PyImport_ImportModuleNoBlock at import.c:2115 #14 0x0058c99a in _PyCodecRegistry_Init at codecs.c:1042 #15 0x00589a50 in _PyCodec_Lookup at codecs.c:110 #16 0x005a7892 in get_codeset at pythonrun.c:145 #17 0x005a7ea1 in Py_InitializeEx at pythonrun.c:272 #18 0x005a7fbc in Py_Initialize at pythonrun.c:309 As you can see it is calling _PyCodecRegistry_Init from get_codeset(). Is there something I can disable here to avoid this problem altogether? I am using the following script with freeze.py to freeze the required modules: print('Hello world...') import dummy_threading import encodings import encodings.aliases import encodings.ascii import encodings.big5 import encodings.big5hkscs import encodings.charmap import encodings.cp037 import encodings.cp1006 import encodings.cp1026 import encodings.cp1140 import encodings.cp1250 import encodings.cp1251 import encodings.cp1252 import encodings.cp1253 import encodings.cp1254 import encodings.cp1255 import encodings.cp1256 import encodings.cp1257 import encodings.cp1258 import encodings.cp424 import encodings.cp437 import encodings.cp500 import encodings.cp737 import encodings.cp775 import encodings.cp850 import encodings.cp852 import encodings.cp855 import encodings.cp856 import encodings.cp857 import encodings.cp860 import encodings.cp861 import encodings.cp862 import encodings.cp863 import encodings.cp864 import encodings.cp865 import encodings.cp866 import encodings.cp869 import encodings.cp874 import encodings.cp875 import encodings.cp932 import encodings.cp949 import encodings.cp950 import encodings.euc_jis_2004 import encodings.euc_jisx0213 import encodings.euc_jp import encodings.euc_kr import encodings.gb18030 import encodings.gb2312 import encodings.gbk import encodings.hp_roman8 import encodings.hz import encodings.idna import encodings.iso2022_jp import encodings.iso2022_jp_1 import encodings.iso2022_jp_2 import encodings.iso2022_jp_2004 import encodings.iso2022_jp_3 import encodings.iso2022_jp_ext import encodings.iso2022_kr import encodings.iso8859_1 import encodings.iso8859_10 import encodings.iso8859_11 import encodings.iso8859_13 import encodings.iso8859_14 import encodings.iso8859_15 import encodings.iso8859_16 import encodings.iso8859_2 import encodings.iso8859_3 import encodings.iso8859_4 import encodings.iso8859_5 import encodings.iso8859_6 import encodings.iso8859_7 import encodings.iso8859_8 import encodings.iso8859_9 import encodings.johab import encodings.koi8_r import encodings.koi8_u import encodings.latin_1 import encodings.mac_arabic import encodings.mac_centeuro import encodings.mac_croatian import encodings.mac_cyrillic import encodings.mac_farsi import encodings.mac_greek import encodings.mac_iceland import encodings.mac_latin2 import encodings.mac_roman import encodings.mac_romanian import encodings.mac_turkish import encodings.mbcs import encodings.palmos import encodings.ptcp154 import encodings.punycode import encodings.raw_unicode_escape import encodings.shift_jis import encodings.shift_jis_2004 import encodings.shift_jisx0213 import encodings.tis_620 import encodings.undefined import encodings.unicode_escape import encodings.unicode_internal import encodings.utf_16 import encodings.utf_16_be import encodings.utf_16_le import encodings.utf_32 import encodings.utf_32_be import encodings.utf_32_le import encodings.utf_7 import encodings.utf_8 import encodings.utf_8_sig From python at mrabarnett.plus.com Wed Dec 9 15:13:30 2009 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 09 Dec 2009 20:13:30 +0000 Subject: switch In-Reply-To: <4B20013C.9080907@tim.thechases.com> References: <335204.99872.qm@web57905.mail.re3.yahoo.com> <68e6e315-f3c7-4e52-a56f-802e99d75e6a@y32g2000prd.googlegroups.com> <4B20013C.9080907@tim.thechases.com> Message-ID: <4B2004EA.5040007@mrabarnett.plus.com> Tim Chase wrote: > Carl Banks wrote: >> What if the object is a string you just read from a file? >> >> How do you dispatch using polymorphism in that case? > [snip] > > which would nicely change into something like > > switch row['recordtype']: > case '01': > phone.international += Decimal(row['internationalcost']) > // optionally a "break" here depending on > // C/C++/Java/PHP syntax vs. Pascal syntax which > // doesn't have fall-through > case '02': > phone.text_messaging += ( > int(row['textmessages sent']) + > int(row['pages received']) + > int(row['textmessages sent']) + > int(row['pages received']) > ... > default: > raise WhatTheHeckIsThis() > > This doesn't convert well (i.e. compactly) to a dictionary-dispatch > idiom. :( > Shouldn't 'case' be indented to the same level as 'switch'? And 'default' could be replaced by 'else' without ambiguity. From joncle at googlemail.com Wed Dec 9 15:21:34 2009 From: joncle at googlemail.com (Jon Clements) Date: Wed, 9 Dec 2009 12:21:34 -0800 (PST) Subject: Sum of the factorial of the digits of a number - wierd behaviour References: <5b7b2fca-67f2-4d13-9965-293368cb9ba3@d10g2000yqh.googlegroups.com> <2128a693-638a-4228-bb5d-b4aa0afb3abb@a21g2000yqc.googlegroups.com> Message-ID: Even though you've worked it out -- a couple of tips: On Dec 9, 5:39?pm, SiWi wrote: > On Dec 9, 6:36?pm, SiWi wrote: > > > > > Dear python community, > > I've got a wierd problem and I hope you can help me out at it. > > I wrote the following code to find the Sum of the factorial of the > > digits of a number (this is for Project Euler 74): > > > def fac(n): > > ? ? x=1 > > ? ? for i in range(2,n+1): > > ? ? ? ? x*=i > > ? ? return x > numpy/scipy etc... are quite useful for Euler :) They contain a function to do factorials (and loads more). This to one of the readable uses of 'reduce': def fac(n): reduce(operator.mul, xrange(2, n+1), n) > > t=tuple(fac(n) for n in range(1,10)) > > > def decimals(x): > > ? ? i=1 > > ? ? d=[] > > ? ? while x>0: > > ? ? ? ? d.append(x%10) > > ? ? ? ? x=x/10 > > ? ? return d The builtin str object can take integers and return it as a string. def decimals(x): return map(int, str(x)) decimals(145) == [1, 4, 5] > > > def sumfac(x): > > ? ? return sum(t[n-1] for n in decimals(x)) > And join the two: print sum(fac(n) for n in decimals(145)) > > The problem is that i get the following results, for which I can't see > > any reason: > > sumfac(145)->145 (1!+4!+5!=1 + 24 +120 = 145) - ok > > sumfac(1454)-> 169 - ok > > sumfac(45362) -> 872 - ok > > sumfac(363600) -> 727212 - wrong, should be1454 > > > Greetings, > > SiWi. > > Oops, found it myself. You can ignote the message above. You might also find it useful to write generators (esp. for primes and factorials). Cheers, Jon. From martin.schoon at gmail.com Wed Dec 9 15:33:56 2009 From: martin.schoon at gmail.com (Martin =?utf-8?B?U2Now7bDtm4=?=) Date: Wed, 09 Dec 2009 21:33:56 +0100 Subject: Perl to Python conversion Message-ID: <87zl5rnayz.fsf@crunchbang.Belkin> First off: I am new here and this is my first post after lurking for quite some time. Second off: I don't know much Python---yet. Problem: I have come across a small open source application that I find quite useful. It does have one major flaw though. Its output is in imperial units. Converting isn't a big deal for occasional use but if I start to use this stuff on a regular basis... So I down-loaded the source code and found this thing is written in Perl. Should I learn enough Perl to add the conversion? Probably but this may be a nice excuse to get my Python education going and if I do I might as well re-do the user interface. If I do re-write this thing in Python I might need to learn both Perl and Python... Hence, are there any Perl to Python converters? So far I have only found bridgekeeper which really is (was?) consultancy. Apart from that I only find people recommending a manual re-write. Any thoughts/recommendations? TIA, /Martin From emile at fenx.com Wed Dec 9 15:41:01 2009 From: emile at fenx.com (Emile van Sebille) Date: Wed, 09 Dec 2009 12:41:01 -0800 Subject: a huge shared read-only data in parallel accesses -- How? multithreading? multiprocessing? In-Reply-To: References: Message-ID: On 12/9/2009 6:58 AM Valery said... > Hi all, > > Q: how to organize parallel accesses to a huge common read-only Python > data structure? I have such a structure which I buried in a zope process which keeps it in memory and is accessed through http requests. This was done about 8 years ago, and I think today I'd check out pyro. Emile From debatem1 at gmail.com Wed Dec 9 15:42:06 2009 From: debatem1 at gmail.com (geremy condra) Date: Wed, 9 Dec 2009 15:42:06 -0500 Subject: Sum of the factorial of the digits of a number - wierd behaviour In-Reply-To: References: <5b7b2fca-67f2-4d13-9965-293368cb9ba3@d10g2000yqh.googlegroups.com> <2128a693-638a-4228-bb5d-b4aa0afb3abb@a21g2000yqc.googlegroups.com> Message-ID: > numpy/scipy etc... are quite useful for Euler :) I've come to love sympy, personally. > They contain a function to do factorials (and loads more). >>> from math import factorial >>> factorial(5) 120 Geremy Condra From akean at clear.net.nz Wed Dec 9 16:03:17 2009 From: akean at clear.net.nz (akean) Date: Wed, 9 Dec 2009 13:03:17 -0800 (PST) Subject: plain text parsing to html (newbie problem) References: <6664c88b-ec93-4b6c-a536-8a6b5959cd5e@a21g2000yqc.googlegroups.com> Message-ID: <35a19377-d2d4-4fb1-ad58-b999e0b9ff8f@u16g2000pru.googlegroups.com> On Dec 10, 3:59 am, Jo?o wrote: > I apologize for my newbiness but I'm banging my head making this work : > ( ... > How can I see the output run in debug mode like in perl? > One method: install ipython (another python shell, but with some useful extra features) and then run the program inside ipython in debug mode: --------- $ ipython In [1]: run -d filename.py Breakpoint 1 at /path/to/filename.py:3 NOTE: Enter 'c' at the ipdb> prompt to start your script. > (1)() ipdb> -------- (You type c to continue) -------- ipdb> c > /path/to/filename.py(3)() 2 1---> 3 import sys, os 4 import subprocess -------- and you can see you're now on line 3. Press h for help to see what commands you can type. Press n for next line if you want to step. Press s to step into a function when it's being called. Etc. -- Anita From zephjc at gmail.com Wed Dec 9 16:05:33 2009 From: zephjc at gmail.com (zeph) Date: Wed, 9 Dec 2009 13:05:33 -0800 (PST) Subject: Perl to Python conversion References: <87zl5rnayz.fsf@crunchbang.Belkin> Message-ID: <4c587427-ebab-4a4d-a3d9-5b2fbff64a81@e4g2000prn.googlegroups.com> Python and Perl often have different design idioms - learning to write *well* in a language involves understanding those idioms, and being able to translate between languages involves understanding the source language well enough to understand the intent of the program's code (even if its poorly written), and understanding the target language well enough to translate the intent into a design fitting the language. Perl and Python have enough syntactic similarities that you could, if you wanted, just translate the program verbatim. Overall, I would recommend adding your imperial->metric functionality to the Perl code for now, and on your free time work on translating to Python, so you don't feel rushed to get it finished. You will probably come to understand the Perl code better after having worked with it and been involved in a hands-on way with it. Likewise, you will become even more familiar with it and with Python as you learn how to translate the application. From aaron.watters at gmail.com Wed Dec 9 16:06:13 2009 From: aaron.watters at gmail.com (Aaron Watters) Date: Wed, 9 Dec 2009 13:06:13 -0800 (PST) Subject: a huge shared read-only data in parallel accesses -- How? multithreading? multiprocessing? References: Message-ID: <63801a6e-1e22-4e43-9149-6ea356e12b48@z10g2000prh.googlegroups.com> On Dec 9, 9:58?am, Valery wrote: > Hi all, > > Q: how to organize parallel accesses to a huge common read-only Python > data structure? Use a BTree on disk in a file. A good file system will keep most of the pages you need in RAM whenever the data is "warm". This works for Python or any other programming language. Generally you can always get to any piece of data in about 4 seeks at most anyway, so if your disk is fast your app will be fast too. The file can be accessed concurrently without problems by any number of processes or threads. -- Aaron Watters http://listtree.appspot.com http://whiffdoc.appspot.com === less is more From python.list at tim.thechases.com Wed Dec 9 16:09:29 2009 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 09 Dec 2009 15:09:29 -0600 Subject: switch In-Reply-To: <4B2004EA.5040007@mrabarnett.plus.com> References: <335204.99872.qm@web57905.mail.re3.yahoo.com> <68e6e315-f3c7-4e52-a56f-802e99d75e6a@y32g2000prd.googlegroups.com> <4B20013C.9080907@tim.thechases.com> <4B2004EA.5040007@mrabarnett.plus.com> Message-ID: <4B201209.7060406@tim.thechases.com> MRAB wrote: > Tim Chase wrote: >> switch row['recordtype']: >> case '01': >> phone.international += Decimal(row['internationalcost']) >> // optionally a "break" here depending on >> // C/C++/Java/PHP syntax vs. Pascal syntax which >> // doesn't have fall-through >> case '02': >> phone.text_messaging += ( >> int(row['textmessages sent']) + >> int(row['pages received']) + >> int(row['textmessages sent']) + >> int(row['pages received']) >> ... >> default: >> raise WhatTheHeckIsThis() >> >> This doesn't convert well (i.e. compactly) to a dictionary-dispatch >> idiom. :( >> > Shouldn't 'case' be indented to the same level as 'switch'? And > 'default' could be replaced by 'else' without ambiguity. But I want a GREEN bike-shed! :-) Yeah, "else" works nicely and makes sense. Indentation could go either way in my book, but I lean towards indented "case" because the "switch" can get easily lost if the "case"s aren't indented: switch foo: case 1: stuff() case 2: morestuff() switch bar: case 3: whatever() case 4: yet_more() else: whip_it() vs switch foo: case 1: stuff() case 2: morestuff() switch bar: case 3: whatever() case 4: yet_more() else: whip_it() Just my ponderings... -tkc From unlearned at gmail.com Wed Dec 9 16:10:34 2009 From: unlearned at gmail.com (Intchanter / Daniel Fackrell) Date: Wed, 9 Dec 2009 13:10:34 -0800 (PST) Subject: Perl to Python conversion References: <87zl5rnayz.fsf@crunchbang.Belkin> Message-ID: <1852e170-4acc-44d7-8aff-04f40a705188@d9g2000prh.googlegroups.com> On Dec 9, 1:33?pm, martin.sch... at gmail.com (Martin Sch??n) wrote: > First off: I am new here and this is my first post after > lurking for quite some time. > > Second off: I don't know much Python---yet. > > Problem: I have come across a small open source application > that I find quite useful. It does have one major flaw though. > Its output is in imperial units. Converting isn't a big deal > for occasional use but if I start to use this stuff on a > regular basis... > > So I down-loaded the source code and found this thing is written > in Perl. > > Should I learn enough Perl to add the conversion? Probably > but this may be a nice excuse to get my Python education > going and if I do I might as well re-do the user interface. > > If I do re-write this thing in Python I might need to learn both > Perl and Python... > > Hence, are there any Perl to Python converters? So far I > have only found bridgekeeper which really is (was?) consultancy. > Apart from that I only find people recommending a manual re-write. > > Any thoughts/recommendations? > > TIA, > > /Martin Martin, A full answer will depend a lot on several different factors, including the length of the Perl code, what style it was written in (there seem to be uncountably many possibilities), your experience with languages in general, and with that style in particular. In general, though, if your primary purpose is to learn Python and ending up with a useful tool is secondary, I'd recommend rewriting the tool from scratch, possibly keeping the Perl source handy. If the existing tool is command-line based, you might also be able to write a short script through which you can pipe the output of the original program to handle the conversion. Intchanter Daniel Fackrell From claird.visiprise at gmail.com Wed Dec 9 16:15:19 2009 From: claird.visiprise at gmail.com (Cameron Laird) Date: Wed, 9 Dec 2009 13:15:19 -0800 (PST) Subject: Python-URL! - weekly Python news and links (Dec 9) Message-ID: QOTW: "I'm not sure you ever understood what the problem was, or where, but I'm happy you feel like you've solved it." - Marco Mariani http://groups.google.com/group/comp.lang.python/browse_thread/thread/8ec7ad4fcc714538 Python 2.7a1, the first alpha release of the 2.7 series, is available now: http://groups.google.com/group/comp.lang.python/t/743e13e80290fbbf/ A bidirectional dictionary structure analyzed: http://groups.google.com/group/comp.lang.python/t/785d100681f7d101/ How to define and use a nested class: http://groups.google.com/group/comp.lang.python/t/6649dfa6eb9797c8/ PyCon 2010 registration opens: http://pycon.blogspot.com/2009/11/registration-for-pycon-2010-is-open.html Why not have a local variable scope smaller than a function? http://groups.google.com/group/comp.lang.python/t/57a8dec0d5d5deda/ How to test whether two floating point values are "close enough" to be almost equal: http://groups.google.com/group/comp.lang.python/t/54ec18c06c46caaf/ A special notation for accessing dynamic attribute names: http://groups.google.com/group/comp.lang.python/t/2f5674a1f451b12f/ Computed attributes, properties, and the descriptor protocol "magic": http://groups.google.com/group/comp.lang.python/t/c07268689549cf01/ Name resolution, global names, importing modules, and how all of them interact: http://groups.google.com/group/comp.lang.python/t/55afecc0d9e3e6c/ http://groups.google.com/group/comp.lang.python/t/de91efba9c5d68ae/ Are there any high-volume Python-powered websites? http://groups.google.com/group/comp.lang.python/t/7e388f22cccf7c4b/ How decoupled are the Python web frameworks? http://groups.google.com/group/comp.lang.python/t/f04940f9d4b136bc/ Moving from Python 2 to Python 3: A "cheat sheet" by Mark Summerfield http://groups.google.com/group/comp.lang.python/t/53716c4136be473b/ The sheets: http://www.informit.com/promotions/promotion.aspx?promo=137519 Thoughts about bytecode optimization and measuring overhead of the eval loop: http://groups.google.com/group/comp.lang.python/t/115b24c0ee9ee06a/ Python as the starting point for a career on IT: http://groups.google.com/group/comp.lang.python/t/907419d0cdd68570/ Idea: get around the GIL using XMLRPC http://groups.google.com/group/comp.lang.python/t/9f84e7aa634de4f5/ Bored and looking for something to do in Python: http://groups.google.com/group/comp.lang.python/t/bba7c231bb9940a4/ ======================================================================== 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 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 enthusiasts": http://pythonpapers.org/ The Python Magazine is a technical monthly devoted to Python: http://pythonmagazine.com Readers have recommended the "Planet" site: http://planet.python.org comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/group/comp.lang.python.announce/topics Python411 indexes "podcasts ... to help people learn Python ..." Updates appear more-than-weekly: http://www.awaretek.com/python/index.html The Python Package Index catalogues packages. http://www.python.org/pypi/ 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/donations/ The Summary of Python Tracker Issues is an automatically generated report summarizing new bugs, closed ones, and patch submissions. http://search.gmane.org/?author=status%40bugs.python.org&group=gmane.comp.python.devel&sort=date 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://code.activestate.com/recipes/langs/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, see: http://www.python.org/channews.rdf 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/ 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 Enjoy the *Python Magazine*. http://pymag.phparch.com/ *Py: the Journal of the Python Language* http://www.pyzine.com Dr.Dobb's Portal is another source of Python news and articles: http://www.ddj.com/TechSearch/searchResults.jhtml?queryText=python and Python articles regularly appear at IBM DeveloperWorks: http://www.ibm.com/developerworks/search/searchResults.jsp?searchSite=dW&searchScope=dW&encodedQ uery=python&rankprofile=8 Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://search.gmane.org/?query=python+URL+weekly+news+links&group=gmane.comp.python.general&sort=date http://groups.google.com/groups/search?q=Python-URL!+group%3Acomp.lang.python&start=0&scoring=d& http://lwn.net/Search/DoSearch?words=python-url&ctype3=yes&cat_25=yes 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 python.list at tim.thechases.com Wed Dec 9 16:27:18 2009 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 09 Dec 2009 15:27:18 -0600 Subject: Recommendation for small, fast, Python based web server In-Reply-To: <1260387281.5558.1349282363@webmail.messagingengine.com> References: <1260387281.5558.1349282363@webmail.messagingengine.com> Message-ID: <4B201636.7010104@tim.thechases.com> python at bdurham.com wrote: > I'm looking for a small, simple, fast, Python based web server > for a simple, client side application we're building. I've used WebStack[1] for this in the past. It allows for stand-alone serving as well as plugging nicely into various "real" servers (apache+mod_python, etc) with a small tweak in how it's configured. > I've looked at the web servers that come bundled with the Python > standard library[1] and they are too slow. I suspect this is > because they don't maintain a session between the client and > server, thus every GET/POST request repeats the session setup and > break down process. Or they might be based on a polling model? I'm not sure what caused the slowness you've experienced -- using Python in a CGI environment requires starting the Python interpreter each time. However if the interpreter starts just once, I've not had notable performance issues for low-volume sites (using the BaseHTTP builtin). For higher-volume sites, you might reach for Twisted which WebStack supports as well. I believe both WebStack and Twisted are redistribtable as needed. -tkc [1] http://www.boddie.org.uk/python/WebStack.html From python-url at phaseit.net Wed Dec 9 16:32:45 2009 From: python-url at phaseit.net (Gabriel Genellina) Date: Wed, 9 Dec 2009 21:32:45 +0000 (UTC) Subject: Python-URL! - weekly Python news and links (Dec 9) Message-ID: QOTW: "I'm not sure you ever understood what the problem was, or where, but I'm happy you feel like you've solved it." - Marco Mariani http://groups.google.com/group/comp.lang.python/browse_thread/thread/8ec7ad4fcc714538 Python 2.7a1, the first alpha release of the 2.7 series, is available now: http://groups.google.com/group/comp.lang.python/t/743e13e80290fbbf/ A bidirectional dictionary structure analyzed: http://groups.google.com/group/comp.lang.python/t/785d100681f7d101/ How to define and use a nested class: http://groups.google.com/group/comp.lang.python/t/6649dfa6eb9797c8/ PyCon 2010 registration opens: http://pycon.blogspot.com/2009/11/registration-for-pycon-2010-is-open.html Why not have a local variable scope smaller than a function? http://groups.google.com/group/comp.lang.python/t/57a8dec0d5d5deda/ How to test whether two floating point values are "close enough" to be almost equal: http://groups.google.com/group/comp.lang.python/t/54ec18c06c46caaf/ A special notation for accessing dynamic attribute names: http://groups.google.com/group/comp.lang.python/t/2f5674a1f451b12f/ Computed attributes, properties, and the descriptor protocol "magic": http://groups.google.com/group/comp.lang.python/t/c07268689549cf01/ Name resolution, global names, importing modules, and how all of them interact: http://groups.google.com/group/comp.lang.python/t/55afecc0d9e3e6c/ http://groups.google.com/group/comp.lang.python/t/de91efba9c5d68ae/ Are there any high-volume Python-powered websites? http://groups.google.com/group/comp.lang.python/t/7e388f22cccf7c4b/ How decoupled are the Python web frameworks? http://groups.google.com/group/comp.lang.python/t/f04940f9d4b136bc/ Moving from Python 2 to Python 3: A "cheat sheet" by Mark Summerfield http://groups.google.com/group/comp.lang.python/t/53716c4136be473b/ The sheets: http://www.informit.com/promotions/promotion.aspx?promo=137519 Thoughts about bytecode optimization and measuring overhead of the eval loop: http://groups.google.com/group/comp.lang.python/t/115b24c0ee9ee06a/ Python as the starting point for a career on IT: http://groups.google.com/group/comp.lang.python/t/907419d0cdd68570/ Idea: get around the GIL using XMLRPC http://groups.google.com/group/comp.lang.python/t/9f84e7aa634de4f5/ Bored and looking for something to do in Python: http://groups.google.com/group/comp.lang.python/t/bba7c231bb9940a4/ ======================================================================== 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 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 enthusiasts": http://pythonpapers.org/ The Python Magazine is a technical monthly devoted to Python: http://pythonmagazine.com Readers have recommended the "Planet" site: http://planet.python.org comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/group/comp.lang.python.announce/topics Python411 indexes "podcasts ... to help people learn Python ..." Updates appear more-than-weekly: http://www.awaretek.com/python/index.html The Python Package Index catalogues packages. http://www.python.org/pypi/ 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/donations/ The Summary of Python Tracker Issues is an automatically generated report summarizing new bugs, closed ones, and patch submissions. http://search.gmane.org/?author=status%40bugs.python.org&group=gmane.comp.python.devel&sort=date 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://code.activestate.com/recipes/langs/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, see: http://www.python.org/channews.rdf 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/ 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 Enjoy the *Python Magazine*. http://pymag.phparch.com/ *Py: the Journal of the Python Language* http://www.pyzine.com Dr.Dobb's Portal is another source of Python news and articles: http://www.ddj.com/TechSearch/searchResults.jhtml?queryText=python and Python articles regularly appear at IBM DeveloperWorks: http://www.ibm.com/developerworks/search/searchResults.jsp?searchSite=dW&searchScope=dW&encodedQuery=python&rankprofile=8 Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://search.gmane.org/?query=python+URL+weekly+news+links&group=gmane.comp.python.general&sort=date http://groups.google.com/groups/search?q=Python-URL!+group%3Acomp.lang.python&start=0&scoring=d& http://lwn.net/Search/DoSearch?words=python-url&ctype3=yes&cat_25=yes 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 davea at ieee.org Wed Dec 9 16:52:13 2009 From: davea at ieee.org (Dave Angel) Date: Wed, 09 Dec 2009 16:52:13 -0500 Subject: UnboundLocalError: local variable '_[1]' referenced before assignment In-Reply-To: <4B1FB514.9010804@arimaz.com> References: <4B1F7924.2080407@arimaz.com> <4B1FACFF.9040802@ieee.org> <4B1FB514.9010804@arimaz.com> Message-ID: <4B201C0D.7060305@ieee.org> Gabriel Rossetti wrote: > Dave Angel wrote: >> Gabriel Rossetti wrote: >>>
Hello >>> everyone, >>> >>> I get this error on python 2.6.1 on mac os x 10.6 : >>> >>> UnboundLocalError: local variable '_[1]' referenced before assignment >>> >>> here's the code that raises this: >>> >>> params = [ self.__formatData(paramProcFunc, query, p) for p in params ] >>> >>> what I don't get is that it worked on mac os x 10.5 (python 2.5.x) >>> but it no longer works. I tried the following and it works : >>> >>> r = [] >>> for p in params: >>> r.append(self.__formatData(paramProcFunc, query, p)) >>> params = r >>> >>> Does anyone understand what is going on here? >>> >>> Thank you, >>> Gabriel >>> >>>
>>> >> Clearly you're not supplying enough context. The UnboundLocalError >> is only raised inside a function (or method), and you only show one >> line of that function. >> >> And in the second example, it's even worse, since you imply it's >> top-level code by carefully unindenting everything. >> >> My *guess* is that you have a global variable params, which you're >> looping on. And then you assign a local variable by the same name. >> If you have an assignment anywhere in the function, that name is >> considered a local, and if you reference it before you assign it, >> it'll generate this error. >> >> Three possible fixes, depending on why you're doing this. >> >> 1) pass the params in to the function as an argument >> 2) use a different name for the local thing you're building >> 3) use a global statement to force the compiler to use the global one >> and not create a local. (probably a bad idea) >> >> DaveA >> > > Hello Dave, > > ok, you' re right about not showing enough: > > params = [ self.__formatData(paramProcFunc, query, p) for p in params ] > > > where : > > paramProcFunc = "percent2Volume" > > def __formatData(self, func, query, data): > return getattr(self._unitDataAbs, func)(self._unitCmdAbs, > query, data) > > def percent2Volume(self, absCmds, query, percent): > return query, int(round(percent / 100.0 * absCmds["volCeil"])) > > > but I still don't see where the problem is and why it works with the > explicit loop and not the list comp. > > Thanks, > Gabriel > I don't see either; you still don't supply nearly enough context. You don't show enough code for someone to actually try it, and since it's not crashing on that line, you're clearly not showing the whole stack trace. I made a few wild guesses about your code, and have something that compiles and runs. But I'm on Windows XP, with Python 2.6.4, so your mileage may vary. import sys print sys.version class Dummy(object): def __init__(self): self._unitDataAbs = self self._unitCmdAbs = {"volCeil":298} def crash(self): query = "this is a query" params = [100,20,37,42] paramProcFunc = "percent2Volume" params = [ self.__formatData(paramProcFunc, query, p) for p in params ] return params def __formatData(self, func, query, data): return getattr(self._unitDataAbs, func)(self._unitCmdAbs, query, data) def percent2Volume(self, absCmds, query, percent): return query, int(round(percent / 100.0 * absCmds["volCeil"])) obj = Dummy() p = obj.crash() print p When I run it, I get the following output: 2.6.4 (r264:75706, Nov 3 2009, 13:23:17) [MSC v.1500 32 bit (Intel)] [('this is a query', 298), ('this is a query', 60), ('this is a query', 110), ('this is a query', 125)] You could try pasting the same code into a file on your system, and if it crashes, then copy the full error stacktrace into a message. If it doesn't, you need to either post your whole code (enough for somebody to actually test), or simplify it till it doesn't crash. Then the next-to-last change is the one that masks the problem. From davea at ieee.org Wed Dec 9 17:01:39 2009 From: davea at ieee.org (Dave Angel) Date: Wed, 09 Dec 2009 17:01:39 -0500 Subject: Request for py program to insert space between two characters and saved as text? In-Reply-To: References: <7b87ecb70912071856k10ad366du2b07ce92b94e50e3@mail.gmail.com> Message-ID: <4B201E43.2000402@ieee.org> r0g wrote: > Dave Angel wrote: > >> r0g wrote: >> >>> Dave Angel wrote: >>> >>> >>>> r0g wrote: >>>> >>>> >>>>> Dave Angel wrote: >>>>> >>>>> >>>>> >>>>>> r0g wrote: >>>>>> >>>>>> >>>>>>> Dennis Lee Bieber wrote: >>>>>>> >>>>>>> >>>>>>> >>>>>>>> On Tue, 8 Dec 2009 08:26:58 +0530, 74yrs old >>>>>>>> >>>>>>>> declaimed the following in gmane.comp.python.general: >>>>>>>> >>>>>>>> >>>>>>>> >>>>>>>>> For Kannada project .txt(not .doc) is used, my requirement is to >>>>>>>>> have one >>>>>>>>> >>>>>>>>> >>>>>>> >>>>>>> >>>>>>> >>>>> >>>>> >>>> That's even worse. As far as I can tell, the code will never do what he >>>> wants in Python 2.x. The Kannada text file is full of Unicode >>>> characters in some encoding, and if you ignore the encoding, you'll just >>>> get garbage. >>>> >>>> >>>> >>>> >>> Ah, fair enough. In my defence though I never saw the original post or >>> this kannada.txt file as my newsserver is not so much with the >>> reliability. I guess it's naive to assume an english .txt file is going >>> to be in ASCII these days eh? >>> >>> I've yet to try python 3 yet either, this whole Unicode thing looks like >>> it could be a total nightmare! :( >>> >>> Roger. >>> >>> >>> >> But it isn't an english .txt file, it's a Kannada .txt file. >> Presumably you didn't realize that Kannada is a (non-English) language, >> spoken in parts of India, with several hundred characters. ASCII wasn't >> even an option. Anyway, no harm done, someone else referred the OP to a >> Python user-group local to that region. >> >> DaveA >> >> > > Well this looked like English to me... > > example: *F o r K a n n a d a p r o j e c t . t x t(n o t .d o c) i s > u s e d, m y r e q u i r e m e n t i s t o h a v e o n e s p a > c e b e t w e e n t w o c h a r a c t e r s i n t h e t e x t.* > > ...but yes you're right, I had never heard of Kannada let alone knew it > was another language! > > Roger. > > There were two examples. The one you quoted was in English, and immediately afterward was the second one, presumably in Kannada. DaveA From davea at ieee.org Wed Dec 9 17:10:51 2009 From: davea at ieee.org (Dave Angel) Date: Wed, 09 Dec 2009 17:10:51 -0500 Subject: How do I Block Events in wxPython In-Reply-To: <17ed589d-f8e2-4fac-b489-5f62060ecd17@j19g2000yqk.googlegroups.com> References: <6854a0bb-9edc-4392-9761-d2f3cf98f89e@k4g2000yqb.googlegroups.com> <17ed589d-f8e2-4fac-b489-5f62060ecd17@j19g2000yqk.googlegroups.com> Message-ID: <4B20206B.2030702@ieee.org> Wanderer wrote: > > > Found another strange bug (Strange to me, anyway). int(0.8 * 10.0) 7. Had to change the code to int(0.8 * 10.0 + 0.0001). > > > Floating point is intrinsically imprecise. The value 0.8 cannot be exactly represented in IEEE fp notation (binary). One answer is to round() the result before converting to int. DaveaA From n00m at narod.ru Wed Dec 9 17:34:58 2009 From: n00m at narod.ru (n00m) Date: Wed, 9 Dec 2009 14:34:58 -0800 (PST) Subject: Brent's variation of a factorization algorithm References: <4B1EA031.9010907@mrabarnett.plus.com> <1a9900e4-c9d6-49bd-aefe-8780433ef030@g7g2000yqa.googlegroups.com> Message-ID: <8e2a01cf-a8c8-4040-8b92-682cec2bad2e@j14g2000yqm.googlegroups.com> PPS The code was successfully tested e.g. here: http://www.spoj.pl/ranks/FACT1/ (see my 2nd and 4th places). They confused versions: the 2nd is in Python 2.5, not 2.6.2. PPPS Funnilly... almost only Python on the 1st page =) From peteRE at MpeteOzilla.Vco.ukE Wed Dec 9 17:46:15 2009 From: peteRE at MpeteOzilla.Vco.ukE (Peter Chant) Date: Wed, 09 Dec 2009 22:46:15 +0000 Subject: Perl to Python conversion References: <87zl5rnayz.fsf@crunchbang.Belkin> Message-ID: Martin Sch??n wrote: > Hence, are there any Perl to Python converters? So far I > have only found bridgekeeper which really is (was?) consultancy. > Apart from that I only find people recommending a manual re-write. > > Any thoughts/recommendations? Voice of almost no experience. I once ran a fortran programme through a fortran to c converter and when I saw the result I ran away screaming - it did not look very human friendly. -- http://www.petezilla.co.uk From thewellsoliver at gmail.com Wed Dec 9 17:51:32 2009 From: thewellsoliver at gmail.com (Wells) Date: Wed, 9 Dec 2009 14:51:32 -0800 (PST) Subject: Parsing json where object keys are not quoted? Message-ID: <295defd9-f8aa-4dc2-99fd-ce09a55f7376@u8g2000prd.googlegroups.com> Is there some way to finagle the json module to parse JSON (well, almost JSON) where the object keys are not in quotes? I know it's not 100% valid JSON, but I'm just curious. I don't have control over the data, so I can't make it fit the spec :) From rhodri at wildebst.demon.co.uk Wed Dec 9 18:04:18 2009 From: rhodri at wildebst.demon.co.uk (Rhodri James) Date: Wed, 09 Dec 2009 23:04:18 -0000 Subject: Graph library for Python In-Reply-To: References: <4B1CFA36.9060805@egenix.com> <4B1D35BC.5000002@egenix.com> <4B1D5CB3.8030805@egenix.com> <4B1D8FB1.5010703@egenix.com> Message-ID: On Wed, 09 Dec 2009 03:47:03 -0000, geremy condra wrote: > On Tue, Dec 8, 2009 at 8:42 PM, Rhodri James > wrote: >> >> g = Graph( >> nodes=[Node("a", colour="red"), >> Node("b", colour="white"), >> Node("c", colour="blue")], >> edges=[Edge("a", "b", "ab", weight=2), >> Edge("a", "c", "ac", is_directed=True), >> Edge("b", "c", "bc", style="dotted")], >> is_directed=True) >> >> I could see a use for this tracking a database structure using a >> constant >> graph, hence all set up in one go for preference. > > While I agree with the rationale, I think we need to find another way. > Aesthetics aside, directly instantiating edges by giving only node names > requires that the edge be aware of what graph its in to provide expected > behavior, which creates a bit of a chicken-or-the-egg dilemma. Oops. I missed that, sorry. > How about this: the constructor can take any type of iterable, and > assumes that it follows my earlier format unless it specifies a .items() > method, in which case it takes the values as follows: isinstance(x, collections.Mapping) is perhaps the right test? > g = Graph( > nodes={'a':{'colour':'red'}, > 'b':{'colour':'white'}, > 'c':{'colour':'blue'}}, > edges={('a', 'b'):{'name':'ab', 'weight':2}, > ('a', 'c'):{'name':'ac'}, > ('b', 'c'):{'name':'bc', 'style':'dotted'}} > ) That's OK for nodes, but for consistency with add_edges I would have expected the name to be the optional third element of the key tuples. It works either way, but I can't help feel it's beginning to look a bit ugly. -- Rhodri James *-* Wildebeest Herder to the Masses From irmen at -nospam-xs4all.nl Wed Dec 9 18:11:57 2009 From: irmen at -nospam-xs4all.nl (Irmen de Jong) Date: Thu, 10 Dec 2009 00:11:57 +0100 Subject: Brent's variation of a factorization algorithm In-Reply-To: References: Message-ID: <4b202e78$0$22943$e4fe514c@news.xs4all.nl> On 27-11-2009 16:36, n00m wrote: > Maybe someone'll make use of it: > > > def gcd(x, y): > if y == 0: > return x > return gcd(y, x % y) > > def brent(n): [...] [D:\Projects]python brentfactor.py 999999999 == 27 * 37037037 What gives? Isn't this thing supposed to factor numbers into the product of two primes? -irmen From gnewsg at gmail.com Wed Dec 9 18:13:17 2009 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Wed, 9 Dec 2009 15:13:17 -0800 (PST) Subject: Porting pyftpdlib to Python 3.x: question about tarball naming convention Message-ID: Hi, I've started the (hard) process of porting pyftpdlib [1] to Python 3. In order to do that I'm working on a separate SVN branch and I plan to maintain two different releases of my software, one for 2.x and another one for 3.x. My doubts are about the naming convention I have to use for the tarball and how it affects the integration with distutils and setuptools. So far I've always used the following naming convention: pyftpdlib-0.5.2.tar.gz pyftpdlib-0.5.1.tar.gz pyftpdlib-0.4.1.tar.gz ... This way I'm able to download and "easy install" pyftpdlib by just doing: > easy_install pyftpdlib ...which retrieves the last pyftpdlib version (0.5.2, at the moment) from PYPI and installs it. Now that I'm going to have two major releases (pyftpdlib-0.5.2 for Python 2.x and pyftpdlib-0.5.2 for Python 3.x) how am I supposed to deal with that? Do I have to use a different name like "pyftpdlib-0.5.2-py3k.tar.gz" or "pyftpdlib-py3k-0.5.2.tar.gz"? How this affects the interaction with easy install? And again: in case it is possible to keep the same tarball name for both versions what am I gonna do with PYPI? Is it possible to host two programs with the same name on PYPI and just differentiate the description (e.g. "pyftpdlib version for python 2.x" / "pyftpdlib version for python 3.x") Thanks in advance [1] http://code.google.com/p/pyftpdlib From unlearned at gmail.com Wed Dec 9 18:26:16 2009 From: unlearned at gmail.com (Intchanter / Daniel Fackrell) Date: Wed, 9 Dec 2009 15:26:16 -0800 (PST) Subject: Parsing json where object keys are not quoted? References: <295defd9-f8aa-4dc2-99fd-ce09a55f7376@u8g2000prd.googlegroups.com> Message-ID: <3f753326-f8f8-4758-90fc-edf4cae258f3@13g2000prl.googlegroups.com> On Dec 9, 3:51?pm, Wells wrote: > Is there some way to finagle the json module to parse JSON (well, > almost JSON) where the object keys are not in quotes? I know it's not > 100% valid JSON, but I'm just curious. > > I don't have control over the data, so I can't make it fit the spec :) Hopefully this won't be a recurring problem, because maintenance of any solution could very well be a nightmare if you have to keep it up. The JSON library that ships with Python doesn't appear to be built for malformed JSON like what you mention, and making it handle it will take a bit of work on your part, but here's a start (based on my 2.6.4 installation): In /path_to_python_standard_library/json/decoder.py (please back this up before making any changes), comment out the try/except block that tries to load scanstring from _json and duplicate the last line (c_scanstring = None), removing its indentation. You'll then need to modify py_scanstring() to meet your needs, but be sure you understand what it's doing first. You'll need to track whether you found the leading '"' for the key and look for the other one if you did, but just look for the ':' otherwise. Again, this isn't an advisable solution, and it won't work in all cases even if you have the best of luck, but it may just work in enough cases. It's pretty amazing that the incoming document doesn't match the spec, though. The only correct solution would be to fix the library that generated it. From fetchinson at googlemail.com Wed Dec 9 18:30:00 2009 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Thu, 10 Dec 2009 00:30:00 +0100 Subject: Recommendation for small, fast, Python based web server In-Reply-To: <1260387281.5558.1349282363@webmail.messagingengine.com> References: <1260387281.5558.1349282363@webmail.messagingengine.com> Message-ID: > I'm looking for a small, simple, fast, Python based web server > for a simple, client side application we're building. We don't > want to distrubute and support a "real" web server like Apache or > Tomcat or depend on the presence of local web server such as IIS. > The application in question will service AJAX requests from a > browser. > > We're not looking for a web framework like Django, Plone, etc. > > I've looked at the web servers that come bundled with the Python > standard library[1] and they are too slow. I suspect this is > because they don't maintain a session between the client and > server, thus every GET/POST request repeats the session setup and > break down process. Or they might be based on a polling model? > > Here are the other Python based web server implementations I'm > aware of: > - cherrypy > - web.py > - twisted > > Any recommendations appreciated (Python 2.6 preferred but open to > Python 3.1 options). I'm using cherrypy for this purpose, actually together with turbogears 1. Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From debatem1 at gmail.com Wed Dec 9 18:42:13 2009 From: debatem1 at gmail.com (geremy condra) Date: Wed, 9 Dec 2009 18:42:13 -0500 Subject: Graph library for Python In-Reply-To: References: <4B1D35BC.5000002@egenix.com> <4B1D5CB3.8030805@egenix.com> <4B1D8FB1.5010703@egenix.com> Message-ID: On Wed, Dec 9, 2009 at 6:04 PM, Rhodri James wrote: > On Wed, 09 Dec 2009 03:47:03 -0000, geremy condra > wrote: > >> On Tue, Dec 8, 2009 at 8:42 PM, Rhodri James >> wrote: >>> >>> g = Graph( >>> ? nodes=[Node("a", colour="red"), >>> ? ? ? ? ?Node("b", colour="white"), >>> ? ? ? ? ?Node("c", colour="blue")], >>> ? edges=[Edge("a", "b", "ab", weight=2), >>> ? ? ? ? ?Edge("a", "c", "ac", is_directed=True), >>> ? ? ? ? ?Edge("b", "c", "bc", style="dotted")], >>> ? is_directed=True) >>> >>> I could see a use for this tracking a database structure using a constant >>> graph, hence all set up in one go for preference. >> >> While I agree with the rationale, I think we need to find another way. >> Aesthetics aside, directly instantiating edges by giving only node names >> requires that the edge be aware of what graph its in to provide expected >> behavior, which creates a bit of a chicken-or-the-egg dilemma. > > Oops. ?I missed that, sorry. > >> How about this: the constructor can take any type of iterable, and >> assumes that it follows my earlier format unless it specifies a .items() >> method, in which case it takes the values as follows: > > isinstance(x, collections.Mapping) is perhaps the right test? The code I kludged together last night just tries __getitem__ and it seems to work, so unless theres something I'm missing I'll probably just leave it at that. >> g = Graph( >> ? ?nodes={'a':{'colour':'red'}, >> ? ? ? ? ? ? ? 'b':{'colour':'white'}, >> ? ? ? ? ? ? ? 'c':{'colour':'blue'}}, >> ? ?edges={('a', 'b'):{'name':'ab', 'weight':2}, >> ? ? ? ? ? ? ? ('a', 'c'):{'name':'ac'}, >> ? ? ? ? ? ? ? ('b', 'c'):{'name':'bc', 'style':'dotted'}} >> ) > > That's OK for nodes, but for consistency with add_edges I would have > expected the name to be the optional third element of the key tuples. ?It > works either way, but I can't help feel it's beginning to look a bit ugly. I have to admit, I prefer it the other way, but patrick (our test guru and chief bug squasher) likes your proposal better. I'm going to get in touch with robbie tonight and see what he says. Since this is not a feature I'll use much, if he agrees with you then I'll go ahead and implement the change tonight and merge it back into mainline. If not, I'd appreciate it if you'd take another look at it and figure out if its something you can live with, or if theres another syntax you'd prefer, etc. Fair enough? Geremy Condra From n00m at narod.ru Wed Dec 9 18:52:30 2009 From: n00m at narod.ru (n00m) Date: Wed, 9 Dec 2009 15:52:30 -0800 (PST) Subject: Brent's variation of a factorization algorithm References: <4b202e78$0$22943$e4fe514c@news.xs4all.nl> Message-ID: On Dec 10, 1:11?am, Irmen de Jong wrote: > 999999999 > == 27 * 37037037 > > What gives? Isn't this thing supposed to factor numbers into the product > of two primes? > > -irmen Only if you yield to it a SEMIprime =) > 27 * 37037037 Now you can apply brent() to these numbers, and so on From gervaz at gmail.com Wed Dec 9 18:53:43 2009 From: gervaz at gmail.com (mattia) Date: 09 Dec 2009 23:53:43 GMT Subject: KeyboardInterrupt Message-ID: <4b203886$0$34595$4fafbaef@reader1.news.tin.it> Hi all, can you provide me a simple code snippet to interrupt the execution of my program catching the KeyboardInterrupt signal? Thanks, Mattia From dkeeper09 at yahoo.com Wed Dec 9 18:55:01 2009 From: dkeeper09 at yahoo.com (Daniel) Date: Wed, 9 Dec 2009 15:55:01 -0800 (PST) Subject: Immediate Help with python program! Message-ID: <1be06077-3173-41ca-a679-8d723eaff0c8@9g2000yqa.googlegroups.com> i am making a tic-tac-toe game using python. i am pretty new to it, but cant seem to figure this one out. Here is my code: X = "X" O = "O" empty = " " tie = "Tie" squares = 9 def display(): print """Welcome to Tic-Tac-Toe. Player will play against the computer. \nYou will move by typing in the number to the corresponding square below: 0 | 1 | 2 ------------- 3 | 4 | 5 ------------- 6 | 7 | 8 \n""" def select(): question = ask("Do you want to go first? (y/n)") if question == "y": player = X computer = O else: computer = X player = O return computer, player def newBoard(): board = [] for i in range(squares): board.append(empty) return board def displayBoard(board): print "\n\t", board[0], "|", board[1], "|", board[2] print "\t", "---------" print "\t", board[3], "|", board[4], "|", board[5] print "\t", "---------" print "\t", board[6], "|", board[7], "|", board[8], "\n" def boardMoves(board): moves = [] for i in range(squares): if board[i] == empty: moves.append(i) return moves def findWinner(board): win = ((0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6)) for i in win: if board[i[0]] == board[i[1]] == board[i[2]] != empty: winner = board[i[0]] return winner if empty not in board: return tie return None def askMove(question, low, high): response = None while response not in range(low, high): response = int(raw_input(question)) return response def playerMove(board, player): legal = boardMoves(board) move = None while move not in legal: move = askMove("Pick a number where you want to move(0-8):", 0, squares) if move not in legal: print "\nThat move is taken already. Pick another." return move def compMove(board, computer, player): board = board[:] strategy = (4, 0, 2, 6, 8, 1, 3, 5, 7) print "Computer chooses:", # if computer can win, take that move for move in boardMoves(board): board[move] = computer if findWinner(board) == computer: print move return move board[move] = empty # if human can win, block that move for move in boardMoves(board): board[move] = player if findWinner(board) == player: print move return move board[move] = empty # If no one can win pick best open square for move in strategy: if move in boardMoves(board): print move return move def nextTurn(turn): if turn == X: return 0 else: return X def gameWinner(winner, computer, player): if winner == computer: print "Computer Wins. Better luck next time" elif winner == player: print "You win. Good job!" elif winner == tie: print "Tie game. Play again." def main(): display() computer, player = select() turn = X board = newBoard() displayBoard(board) while not findWinner(board): if turn == player: move = playerMove(board, player) board[move] = player else: move = compMove(board, computer, player) board[move] = computer displayBoard(board) turn = nextTurn(turn) winner = findWinner(board) gameWinner(winner, computer, player) main() Here is my problem: If you hit 'n' at the beginning prompt, the computer does four moves automatically and wins- you can't input anything. If you hit 'y' at the beginning prompt, you can play but cannot win. I got three x's in a row and it didn't let me win. It just keeps letting you input numbers until the computer wins even if you have three in a row. If anyone can help please do asap. Thank you! From python at bdurham.com Wed Dec 9 19:00:56 2009 From: python at bdurham.com (python at bdurham.com) Date: Wed, 09 Dec 2009 19:00:56 -0500 Subject: Recommendation for small, fast, Python based web server In-Reply-To: <4B201636.7010104@tim.thechases.com> References: <1260387281.5558.1349282363@webmail.messagingengine.com> <4B201636.7010104@tim.thechases.com> Message-ID: <1260403256.14498.1349338433@webmail.messagingengine.com> Tim, > I've used WebStack[1] for this in the past. It allows for stand-alone serving as well as plugging nicely into various "real" servers (apache+mod_python, etc) with a small tweak in how it's configured. Thanks for that recommendation. > I'm not sure what caused the slowness you've experienced (... with running local versions of Python web servers) Thanks to a past post by "Christoph Zwerschke" , I was able to identify the problem. Windows (XP, Vista, Windows 7) tries to do a IPV6 connection which times out after a second followed by an IPV4 connection which is almost instantaneous. Apparently this is a known problem that is a Windows issue [1] - not a Python problem. Two workarounds: 1. Use 127.0.0.1 as your URL vs. localhost -OR- 2. Edit your Windows hosts file (c:\windows\system32\drivers\etc\hosts) and create a virtual domain name, eg. put the following on a line by itself: 127.0.0.1 mydomain.someext And then use mydomain.someext vs. localhost Note: Editing your hosts file requires admin rights under Vista and Windows 7. Regards, Malcolm [1] http://schotime.net/blog/index.php/2008/05/27/slow-tcpclient-connection-sockets/ From rhodri at wildebst.demon.co.uk Wed Dec 9 19:02:22 2009 From: rhodri at wildebst.demon.co.uk (Rhodri James) Date: Thu, 10 Dec 2009 00:02:22 -0000 Subject: Graph library for Python In-Reply-To: References: <4B1D35BC.5000002@egenix.com> <4B1D5CB3.8030805@egenix.com> <4B1D8FB1.5010703@egenix.com> Message-ID: On Wed, 09 Dec 2009 23:42:13 -0000, geremy condra wrote: > On Wed, Dec 9, 2009 at 6:04 PM, Rhodri James > wrote: >> On Wed, 09 Dec 2009 03:47:03 -0000, geremy condra >> wrote: >>> g = Graph( >>> nodes={'a':{'colour':'red'}, >>> 'b':{'colour':'white'}, >>> 'c':{'colour':'blue'}}, >>> edges={('a', 'b'):{'name':'ab', 'weight':2}, >>> ('a', 'c'):{'name':'ac'}, >>> ('b', 'c'):{'name':'bc', 'style':'dotted'}} >>> ) >> >> That's OK for nodes, but for consistency with add_edges I would have >> expected the name to be the optional third element of the key tuples. >> It >> works either way, but I can't help feel it's beginning to look a bit >> ugly. > > I have to admit, I prefer it the other way, but patrick (our test guru > and > chief bug squasher) likes your proposal better. I'm going to get in touch > with robbie tonight and see what he says. Since this is not a feature > I'll > use much, if he agrees with you then I'll go ahead and implement the > change tonight and merge it back into mainline. If not, I'd appreciate > it if you'd take another look at it and figure out if its something you > can > live with, or if theres another syntax you'd prefer, etc. Fair enough? Fair enough. Don't take my word as having much weight; I'm not likely to use graphs much for graph theory purposes (having skipped the topology courses in the Maths part of my degree), it just happens to be clearly the right datastructure for a project I'm fiddling with at home. Here's a thought: are g.add_edge("a", "b", "ab") and g.add_edge("a", "b", name="ab") equivalent? If so, there's no reason not to have both forms of the initialiser. If not, that weighs against having 'name' as a dictionary key. -- Rhodri James *-* Wildebeest Herder to the Masses From python at bdurham.com Wed Dec 9 19:05:44 2009 From: python at bdurham.com (python at bdurham.com) Date: Wed, 09 Dec 2009 19:05:44 -0500 Subject: Recommendation for small, fast, Python based web server In-Reply-To: References: <1260387281.5558.1349282363@webmail.messagingengine.com> Message-ID: <1260403544.15238.1349339781@webmail.messagingengine.com> Daniel, > I'm using cherrypy for this purpose, actually together with turbogears 1. My research has constantly pointed back to cherrypy as a tool of choice for building local web servers. My initial impression was that cherrypy was too big and complicated for my simple task. However, I'm going to re-examine this assumption and take another look at cherrypy. Thanks for your help! Regards, Malcolm From joncle at googlemail.com Wed Dec 9 19:18:14 2009 From: joncle at googlemail.com (Jon Clements) Date: Wed, 9 Dec 2009 16:18:14 -0800 (PST) Subject: Immediate Help with python program! References: <1be06077-3173-41ca-a679-8d723eaff0c8@9g2000yqa.googlegroups.com> Message-ID: On Dec 9, 11:55?pm, Daniel wrote: > i am making a tic-tac-toe game using python. i am pretty new to it, > but cant seem to figure this one out. > Here is my code: > > X = "X" > O = "O" > empty = " " > tie = "Tie" > squares = 9 > > def display(): > ? ? print """Welcome to Tic-Tac-Toe. Player will play against the > computer. > ? ? ? ? ? ? \nYou will move by typing in the number to the > corresponding square below: > > ? ? ? ? ? ? ? ? ? 0 | 1 | 2 > ? ? ? ? ? ? ? ? ------------- > ? ? ? ? ? ? ? ? ? 3 | 4 | 5 > ? ? ? ? ? ? ? ? ------------- > ? ? ? ? ? ? ? ? ? 6 | 7 | 8 \n""" > > def select(): > ? ? question = ask("Do you want to go first? (y/n)") > ? ? if question == "y": > ? ? ? ? player = X > ? ? ? ? computer = O > ? ? else: > ? ? ? ? computer = X > ? ? ? ? player = O > ? ? return computer, player > > def newBoard(): > ? ? board = [] > ? ? for i in range(squares): > ? ? ? ? board.append(empty) > ? ? return board > > def displayBoard(board): > ? ? print "\n\t", board[0], "|", board[1], "|", board[2] > ? ? print "\t", "---------" > ? ? print "\t", board[3], "|", board[4], "|", board[5] > ? ? print "\t", "---------" > ? ? print "\t", board[6], "|", board[7], "|", board[8], "\n" > > def boardMoves(board): > ? ? moves = [] > ? ? for i in range(squares): > ? ? ? ? if board[i] == empty: > ? ? ? ? ? ? moves.append(i) > ? ? return moves > > def findWinner(board): > ? ? win = ((0, 1, 2), > ? ? ? ? ? ?(3, 4, 5), > ? ? ? ? ? ?(6, 7, 8), > ? ? ? ? ? ?(0, 3, 6), > ? ? ? ? ? ?(1, 4, 7), > ? ? ? ? ? ?(2, 5, 8), > ? ? ? ? ? ?(0, 4, 8), > ? ? ? ? ? ?(2, 4, 6)) > > ? ? for i in win: > ? ? ? ? if board[i[0]] == board[i[1]] == board[i[2]] != empty: > ? ? ? ? ? ? winner = board[i[0]] > ? ? ? ? ? ? return winner > ? ? ? ? if empty not in board: > ? ? ? ? ? ? return tie > ? ? ? ? return None > > def askMove(question, low, high): > ? ? response = None > ? ? while response not in range(low, high): > ? ? ? ? response = int(raw_input(question)) > ? ? return response > > def playerMove(board, player): > ? ? legal = boardMoves(board) > ? ? move = None > ? ? while move not in legal: > ? ? ? ? move = askMove("Pick a number where you want to move(0-8):", > 0, squares) > ? ? ? ? if move not in legal: > ? ? ? ? ? ? print "\nThat move is taken already. Pick another." > ? ? return move > > def compMove(board, computer, player): > ? ? board = board[:] > ? ? strategy = (4, 0, 2, 6, 8, 1, 3, 5, 7) > ? ? print "Computer chooses:", > > ? ? # if computer can win, take that move > ? ? for move in boardMoves(board): > ? ? ? ? board[move] = computer > ? ? ? ? if findWinner(board) == computer: > ? ? ? ? ? ? print move > ? ? ? ? ? ? return move > ? ? ? ? board[move] = empty > > ? ? # if human can win, block that move > ? ? for move in boardMoves(board): > ? ? ? ? board[move] = player > ? ? ? ? if findWinner(board) == player: > ? ? ? ? ? ? print move > ? ? ? ? ? ? return move > ? ? ? ? board[move] = empty > > ? ? # If no one can win pick best open square > ? ? for move in strategy: > ? ? ? ? if move in boardMoves(board): > ? ? ? ? ? ? print move > ? ? ? ? ? ? return move > > def nextTurn(turn): > ? ? if turn == X: > ? ? ? ? return 0 > ? ? else: > ? ? ? ? return X > > def gameWinner(winner, computer, player): > ? ? if winner == computer: > ? ? ? ? print "Computer Wins. Better luck next time" > ? ? elif winner == player: > ? ? ? ? print "You win. Good job!" > ? ? elif winner == tie: > ? ? ? ? print "Tie game. Play again." > > def main(): > ? ? display() > ? ? computer, player = select() > ? ? turn = X > ? ? board = newBoard() > ? ? displayBoard(board) > > ? ? while not findWinner(board): > ? ? ? ? if turn == player: > ? ? ? ? ? ? move = playerMove(board, player) > ? ? ? ? ? ? board[move] = player > ? ? ? ? else: > ? ? ? ? ? ? move = compMove(board, computer, player) > ? ? ? ? ? ? board[move] = computer > ? ? ? ? displayBoard(board) > ? ? ? ? turn = nextTurn(turn) > ? ? winner = findWinner(board) > ? ? gameWinner(winner, computer, player) > > main() > > Here is my problem: > If you hit 'n' at the beginning prompt, the computer does four moves > automatically and wins- you can't input anything. If you hit 'y' at > the beginning prompt, you can play but cannot win. I got three x's in > a row and it didn't let me win. It just keeps letting > you input numbers until the computer wins even if you have three in a > row. > > If anyone can help please do asap. > Thank you! Someone's homework assignment is overdue/due very soon? And, I don't believe for a second this is your code. In fact, just searching for (the obvious Java based) function names leads me to believe you've 'butchered' it from Java code (do you not think your teacher/lecturer can do the same?). Someone might well help out, but I'd be surprised if you got a "here's how to fix it response", as from my POV you haven't done any work. Of course, I'm occasionally wrong, Jon. From joncle at googlemail.com Wed Dec 9 19:19:24 2009 From: joncle at googlemail.com (Jon Clements) Date: Wed, 9 Dec 2009 16:19:24 -0800 (PST) Subject: KeyboardInterrupt References: <4b203886$0$34595$4fafbaef@reader1.news.tin.it> Message-ID: <0a336844-ac41-4d80-9310-4e1f63701eb6@u7g2000yqm.googlegroups.com> On Dec 9, 11:53?pm, mattia wrote: > Hi all, can you provide me a simple code snippet to interrupt the > execution of my program catching the KeyboardInterrupt signal? > > Thanks, > Mattia Errr, normally you can just catch the KeyboardInterrupt exception -- is that what you mean? Jon. From dkeeper09 at yahoo.com Wed Dec 9 19:21:18 2009 From: dkeeper09 at yahoo.com (Daniel) Date: Wed, 9 Dec 2009 16:21:18 -0800 (PST) Subject: Immediate Help with python program! References: <1be06077-3173-41ca-a679-8d723eaff0c8@9g2000yqa.googlegroups.com> Message-ID: On Dec 9, 6:18?pm, Jon Clements wrote: > On Dec 9, 11:55?pm, Daniel wrote: > > > > > i am making a tic-tac-toe game using python. i am pretty new to it, > > but cant seem to figure this one out. > > Here is my code: > > > X = "X" > > O = "O" > > empty = " " > > tie = "Tie" > > squares = 9 > > > def display(): > > ? ? print """Welcome to Tic-Tac-Toe. Player will play against the > > computer. > > ? ? ? ? ? ? \nYou will move by typing in the number to the > > corresponding square below: > > > ? ? ? ? ? ? ? ? ? 0 | 1 | 2 > > ? ? ? ? ? ? ? ? ------------- > > ? ? ? ? ? ? ? ? ? 3 | 4 | 5 > > ? ? ? ? ? ? ? ? ------------- > > ? ? ? ? ? ? ? ? ? 6 | 7 | 8 \n""" > > > def select(): > > ? ? question = ask("Do you want to go first? (y/n)") > > ? ? if question == "y": > > ? ? ? ? player = X > > ? ? ? ? computer = O > > ? ? else: > > ? ? ? ? computer = X > > ? ? ? ? player = O > > ? ? return computer, player > > > def newBoard(): > > ? ? board = [] > > ? ? for i in range(squares): > > ? ? ? ? board.append(empty) > > ? ? return board > > > def displayBoard(board): > > ? ? print "\n\t", board[0], "|", board[1], "|", board[2] > > ? ? print "\t", "---------" > > ? ? print "\t", board[3], "|", board[4], "|", board[5] > > ? ? print "\t", "---------" > > ? ? print "\t", board[6], "|", board[7], "|", board[8], "\n" > > > def boardMoves(board): > > ? ? moves = [] > > ? ? for i in range(squares): > > ? ? ? ? if board[i] == empty: > > ? ? ? ? ? ? moves.append(i) > > ? ? return moves > > > def findWinner(board): > > ? ? win = ((0, 1, 2), > > ? ? ? ? ? ?(3, 4, 5), > > ? ? ? ? ? ?(6, 7, 8), > > ? ? ? ? ? ?(0, 3, 6), > > ? ? ? ? ? ?(1, 4, 7), > > ? ? ? ? ? ?(2, 5, 8), > > ? ? ? ? ? ?(0, 4, 8), > > ? ? ? ? ? ?(2, 4, 6)) > > > ? ? for i in win: > > ? ? ? ? if board[i[0]] == board[i[1]] == board[i[2]] != empty: > > ? ? ? ? ? ? winner = board[i[0]] > > ? ? ? ? ? ? return winner > > ? ? ? ? if empty not in board: > > ? ? ? ? ? ? return tie > > ? ? ? ? return None > > > def askMove(question, low, high): > > ? ? response = None > > ? ? while response not in range(low, high): > > ? ? ? ? response = int(raw_input(question)) > > ? ? return response > > > def playerMove(board, player): > > ? ? legal = boardMoves(board) > > ? ? move = None > > ? ? while move not in legal: > > ? ? ? ? move = askMove("Pick a number where you want to move(0-8):", > > 0, squares) > > ? ? ? ? if move not in legal: > > ? ? ? ? ? ? print "\nThat move is taken already. Pick another." > > ? ? return move > > > def compMove(board, computer, player): > > ? ? board = board[:] > > ? ? strategy = (4, 0, 2, 6, 8, 1, 3, 5, 7) > > ? ? print "Computer chooses:", > > > ? ? # if computer can win, take that move > > ? ? for move in boardMoves(board): > > ? ? ? ? board[move] = computer > > ? ? ? ? if findWinner(board) == computer: > > ? ? ? ? ? ? print move > > ? ? ? ? ? ? return move > > ? ? ? ? board[move] = empty > > > ? ? # if human can win, block that move > > ? ? for move in boardMoves(board): > > ? ? ? ? board[move] = player > > ? ? ? ? if findWinner(board) == player: > > ? ? ? ? ? ? print move > > ? ? ? ? ? ? return move > > ? ? ? ? board[move] = empty > > > ? ? # If no one can win pick best open square > > ? ? for move in strategy: > > ? ? ? ? if move in boardMoves(board): > > ? ? ? ? ? ? print move > > ? ? ? ? ? ? return move > > > def nextTurn(turn): > > ? ? if turn == X: > > ? ? ? ? return 0 > > ? ? else: > > ? ? ? ? return X > > > def gameWinner(winner, computer, player): > > ? ? if winner == computer: > > ? ? ? ? print "Computer Wins. Better luck next time" > > ? ? elif winner == player: > > ? ? ? ? print "You win. Good job!" > > ? ? elif winner == tie: > > ? ? ? ? print "Tie game. Play again." > > > def main(): > > ? ? display() > > ? ? computer, player = select() > > ? ? turn = X > > ? ? board = newBoard() > > ? ? displayBoard(board) > > > ? ? while not findWinner(board): > > ? ? ? ? if turn == player: > > ? ? ? ? ? ? move = playerMove(board, player) > > ? ? ? ? ? ? board[move] = player > > ? ? ? ? else: > > ? ? ? ? ? ? move = compMove(board, computer, player) > > ? ? ? ? ? ? board[move] = computer > > ? ? ? ? displayBoard(board) > > ? ? ? ? turn = nextTurn(turn) > > ? ? winner = findWinner(board) > > ? ? gameWinner(winner, computer, player) > > > main() > > > Here is my problem: > > If you hit 'n' at the beginning prompt, the computer does four moves > > automatically and wins- you can't input anything. If you hit 'y' at > > the beginning prompt, you can play but cannot win. I got three x's in > > a row and it didn't let me win. It just keeps letting > > you input numbers until the computer wins even if you have three in a > > row. > > > If anyone can help please do asap. > > Thank you! > > Someone's homework assignment is overdue/due very soon? And, I don't > believe for a second this is your code. In fact, just searching for > (the obvious Java based) function names leads me to believe you've > 'butchered' it from Java code (do you not think your teacher/lecturer > can do the same?). > > Someone might well help out, but I'd be surprised if you got a "here's > how to fix it response", as from my POV you haven't done any work. > > Of course, I'm occasionally wrong, > > Jon. Just lookin for some help man. It is my code. but im here because i needed help and i dont know whats wrong with it. Figured someone would offer a hand. Thanks anyway. From unlearned at gmail.com Wed Dec 9 19:21:47 2009 From: unlearned at gmail.com (Intchanter / Daniel Fackrell) Date: Wed, 9 Dec 2009 16:21:47 -0800 (PST) Subject: Immediate Help with python program! References: <1be06077-3173-41ca-a679-8d723eaff0c8@9g2000yqa.googlegroups.com> Message-ID: On Dec 9, 5:18?pm, Jon Clements wrote: > Someone's homework assignment is overdue/due very soon? And, I don't > believe for a second this is your code. In fact, just searching for > (the obvious Java based) function names leads me to believe you've > 'butchered' it from Java code (do you not think your teacher/lecturer > can do the same?). > > Someone might well help out, but I'd be surprised if you got a "here's > how to fix it response", as from my POV you haven't done any work. > > Of course, I'm occasionally wrong, > > Jon. I also got the impression that it was a homework assignment. I'll just add that trying to bring attention to your request for help with exclamation points and words that indicate urgency is pretty bad form in a volunteer support community. From mal at egenix.com Wed Dec 9 19:22:52 2009 From: mal at egenix.com (M.-A. Lemburg) Date: Thu, 10 Dec 2009 01:22:52 +0100 Subject: Graph library for Python In-Reply-To: References: <4B18F685.8050102@egenix.com> <4B1CFA36.9060805@egenix.com> <4B1D35BC.5000002@egenix.com> <4B1D5CB3.8030805@egenix.com> <4B1D8FB1.5010703@egenix.com> Message-ID: <4B203F5C.6000803@egenix.com> geremy condra wrote: > On Mon, Dec 7, 2009 at 6:28 PM, M.-A. Lemburg wrote: >>>> * Graph.__init__ should be able to take a list or set >>>> of nodes and edges as initializer >>> >>> The format of this will need to be thought all the way >>> through before being implemented. To date, we haven't >>> come up with anything completely satisfactory, but >>> AFAIK everybody involved is still open to suggestions >>> on this. >> >> I wasn't thinking of anything clever :-) ... >> >> g = Graph( >> [Node("a"), Node("b"), Node("c")], >> [Edge(Node("a"), Node("b"), "ab"), >> Edge(Node("a"), Node("c"), "ac"), >> Edge(Node("b"), Node("c"), "bc"), >> ]) >> >> The main motivation here is to get lists, sets and dicts >> play nice together. > > Generally, we've tried to discourage people from instantiating > nodes and edges directly, in favor of having them controlled > through the graph. Maybe something along the lines of: > > g = Graph(nodes=['a', 'b', 'c'], edges=[('a', 'b'), ('a', 'c'), ('b', 'c')]) > > ? That would work as well, but you then miss out on the extra parameters you can pass to Edge() and Node(). In another email you wrote that Edge() and Node() constructors should not be used directly, since they have to know the Graph to which they belong. Wouldn't it be possible to implement this kind of parent- referencing in a lazy way, ie. by postponing all the init- processing until the Graph instance is known ? >>>> * Graph.__setitem__ could be mapped to .add_node() for >>>> convenience >>> >>> This may be a question of playing around with it. ATM I'm >>> not sold on the idea, but I'll implement it and see how it >>> turns out in practice. >> >> Thinking about it some more, I agree, it's not all that useful. >> >>>> * Graph.__length__ could be mapped to .size() for >>>> convenience >>> >>> We decided not to do this due to the ambiguity between >>> whether .size() or .order() was the intended operation, >>> and looking back I'm not sure that was entirely unjustified. >>> Do you see there being any confusion on that score? >> >> There is an ambiguity here, indeed. My thinking was that >> the edges define the graph and can be mapped to a dictionary, >> e.g. >> >> d = {"ab": ("a", "b"), >> "ac": ("a", "c"), >> "bc": ("b", "c")} >> >> len(d) == 3 >> len(g) == 3 >> >> A graph without edges is also what you typically call an empty >> graph, ie. >> >> if not g: >> print 'empty' >> >> http://mathworld.wolfram.com/EmptyGraph.html >> >> Still, perhaps it's better to just not go down this route. > > I'd rather avoid it if possible, since there are many > potential interpretations of this in different contexts. > Again, I'm open to to the idea, but not convinced. > >>>> * Graph.__iter__ could be mapped to an iterator using >>>> the fastest traversal method for the graph nodes >>>> (ie. order does not matter, it's only important that >>>> all nodes are found as fast as possible) >>> >>> Again, it seems ambiguous as to whether nodes or >>> edges are the intended target here, and while the >>> API can obviously dictate that, it seems a bit like >>> a case of "in the face of ambiguity, refuse the >>> temptation to guess" to me. >> >> Right, but sometimes "practicalty beats purity" ;-) We had >> the same situation for dictionaries and then decided that >> iteration over keys would be more natural than iterating over >> items (key, value) or values. >> >> It's also important to note that: >> >> for n in g: print n >> >> and >> >> n in g >> >> match up in terms of semantics. >> >> Since n in g already uses the "node in graph" approach, >> the for-loop should use the same logic. > > Beware, that doesn't just match nodes. > > g = Graph() > g.add_node('a') > g.add_node('b') > g.add_edge('a', 'b', 'ab') > 'ab' in g # returns true I'd avoid such an ambiguity. It could easily hide programming errors (testing for edges instead of nodes). OTOH, you could also regard the graph as a set of nodes and edges (as you apparently already do). In that case, you'd define for x in g: print x as iteration of both nodes and edges in some arbitrary order and then use the more specific: for n in g.nodes: print x for e in g.edges: print x for iteration over just the nodes or edges. >>>> * Graph could also benefit from some bulk update methods, >>>> e.g. to update weights on all edges or nodes by passing >>>> in a dictionary mapping names to attribute values >>> >>> Sounds good. Again, the format will need some careful >>> thought, but you're right that this would improve it >>> greatly. >> >> This is only an optimization, but could lead to some great >> performance improvements by avoiding function call overhead. > > Agreed. > >>>> * Graph could benefit from some bulk query methods, >>>> such as .get_node_attributes() and .add_edges(). >>> >>> I'm not sure how the first is different from the existing >>> .data, what did you have in mind? >> >> The second one was a typo. It should have been >> .get_edge_attributes(). >> >> In both cases I was thinking of being able to quickly >> extract a number of node/edge attributes, e.g. >> >>>>> g.get_edge_attributes('weight', 'color') >> {"ab": {"weight": 3, "color": "blue"}, >> "ac": {"weight": 2, "color": "green"}, >> "bc": {"weight": 1, "color": "red"}} >> >> Again, the idea is to reduce call overhead and later >> on be able to move these lookups to C. > > Entirely doable, but I'm not sure I see the use case. > Would you mind providing a more realistic example? The idea is that you use the Graph representation of the data to implement some algorithm e.g. optimizing weights for example. The algorithm could be implemented in C to be fast enough for large data sets. The above two methods would then be used to quickly push the original data into the graph and extract it again after the algorithm has run. >>>> * Node.__getitem__ could be mapped to .data.__getitem__ >>>> (following the approach taken by ElementTree); same >>>> for Edge.__getitem__ >>> >>>> * Node.__setitem__ could be mapped to .data.__setitem__ >>>> (following the approach taken by ElementTree); same >>>> for Edge.__setitem__ >>> >>> .data is just a property that returns a dictionary of non >>> private members right now, so if you're wanting to just say >>> node.this = 'stuff', you can already do that. Or am I >>> misreading your intent? >> >> Right, but with attributes you are restricted to Python >> identifiers, e.g. keywords (e.g. "from", "pass") are not allowed. >> The above approach bypasses this restriction. > > Hmm. Sounds like a plausible use case to me, although I'm > not sure its one that should be encouraged. The bigger > question in my mind is whether all attribute lookups should > have to pay the extra lookup cost to support a somewhat > narrow need. I'll definitely have to talk with the other devs > about this one, and run a little bit of timing besides. This would only be an optional second way of accessing the .data dictionary. node.data['pass'] = 1 node.data['from'] = 'Las Vegas' node.data['to'] = 'New York' would work without such modifications. -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Dec 10 2009) >>> 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 our new mxODBC.Connect Python Database Interface 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 http://www.egenix.com/company/contact/ From reeeh2000 at gmail.com Wed Dec 9 19:24:51 2009 From: reeeh2000 at gmail.com (Patrick Laban) Date: Wed, 9 Dec 2009 16:24:51 -0800 Subject: Graph library for Python In-Reply-To: References: <4B1D5CB3.8030805@egenix.com> <4B1D8FB1.5010703@egenix.com> Message-ID: <616bd5240912091624w6ec3b552u365926d6da152036@mail.gmail.com> On Wed, Dec 9, 2009 at 4:02 PM, Rhodri James wrote: > > Here's a thought: are > > g.add_edge("a", "b", "ab") > > and > > g.add_edge("a", "b", name="ab") > > equivalent? If so, there's no reason not to have both forms of the > initialiser. If not, that weighs against having 'name' as a dictionary key. > > > -- > Rhodri James *-* Wildebeest Herder to the Masses > -- > http://mail.python.org/mailman/listinfo/python-list > Both methods are equivalent. Patrick Laban -------------- next part -------------- An HTML attachment was scrubbed... URL: From debatem1 at gmail.com Wed Dec 9 19:27:28 2009 From: debatem1 at gmail.com (geremy condra) Date: Wed, 9 Dec 2009 19:27:28 -0500 Subject: Graph library for Python In-Reply-To: References: <4B1D5CB3.8030805@egenix.com> <4B1D8FB1.5010703@egenix.com> Message-ID: On Wed, Dec 9, 2009 at 7:02 PM, Rhodri James wrote: > On Wed, 09 Dec 2009 23:42:13 -0000, geremy condra > wrote: > >> On Wed, Dec 9, 2009 at 6:04 PM, Rhodri James >> wrote: >>> >>> On Wed, 09 Dec 2009 03:47:03 -0000, geremy condra >>> wrote: > >>>> g = Graph( >>>> ? nodes={'a':{'colour':'red'}, >>>> ? ? ? ? ? ? ?'b':{'colour':'white'}, >>>> ? ? ? ? ? ? ?'c':{'colour':'blue'}}, >>>> ? edges={('a', 'b'):{'name':'ab', 'weight':2}, >>>> ? ? ? ? ? ? ?('a', 'c'):{'name':'ac'}, >>>> ? ? ? ? ? ? ?('b', 'c'):{'name':'bc', 'style':'dotted'}} >>>> ) >>> >>> That's OK for nodes, but for consistency with add_edges I would have >>> expected the name to be the optional third element of the key tuples. ?It >>> works either way, but I can't help feel it's beginning to look a bit >>> ugly. >> >> I have to admit, I prefer it the other way, but patrick (our test guru and >> chief bug squasher) likes your proposal better. I'm going to get in touch >> with robbie tonight and see what he says. Since this is not a feature I'll >> use much, if he agrees with you then I'll go ahead and implement the >> change tonight and merge it back into mainline. If not, I'd appreciate >> it if you'd take another look at it and figure out if its something you >> can >> live with, or if theres another syntax you'd prefer, etc. Fair enough? > > Fair enough. ?Don't take my word as having much weight; I'm not likely to > use graphs much for graph theory purposes (having skipped the topology > courses in the Maths part of my degree), it just happens to be clearly the > right datastructure for a project I'm fiddling with at home. > > Here's a thought: are > > ?g.add_edge("a", "b", "ab") > > and > > ?g.add_edge("a", "b", name="ab") > > equivalent? ?If so, there's no reason not to have both forms of the > initialiser. ?If not, that weighs against having 'name' as a dictionary key. You're right, of course- the obvious way to do this is just to apply tuple unpacking to each element in the edges argument. I've applied the change, although testing and documentation will need to be updated before I can merge it back into mainline, and I doubt I'll get to that tonight. Geremy Condra From david.birdsong at gmail.com Wed Dec 9 19:27:33 2009 From: david.birdsong at gmail.com (birdsong) Date: Wed, 9 Dec 2009 16:27:33 -0800 (PST) Subject: Recommendation for small, fast, Python based web server References: <1260387281.5558.1349282363@webmail.messagingengine.com> Message-ID: On Dec 9, 4:05?pm, pyt... at bdurham.com wrote: > Daniel, > > > I'm using cherrypy for this purpose, actually together with turbogears 1. > > My research has constantly pointed back to cherrypy as a tool of choice > for building local web servers. My initial impression was that cherrypy > was too big and complicated for my simple task. However, I'm going to > re-examine this assumption and take another look at cherrypy. > > Thanks for your help! > > Regards, > Malcolm tornado all the way, it is teh radness: http://www.tornadoweb.org/ epoll based python server. fun to hack on. def check it out. From gervaz at gmail.com Wed Dec 9 19:29:45 2009 From: gervaz at gmail.com (mattia) Date: 10 Dec 2009 00:29:45 GMT Subject: KeyboardInterrupt References: <4b203886$0$34595$4fafbaef@reader1.news.tin.it> <0a336844-ac41-4d80-9310-4e1f63701eb6@u7g2000yqm.googlegroups.com> Message-ID: <4b2040f9$0$34595$4fafbaef@reader1.news.tin.it> Il Wed, 09 Dec 2009 16:19:24 -0800, Jon Clements ha scritto: > On Dec 9, 11:53?pm, mattia wrote: >> Hi all, can you provide me a simple code snippet to interrupt the >> execution of my program catching the KeyboardInterrupt signal? >> >> Thanks, >> Mattia > > Errr, normally you can just catch the KeyboardInterrupt exception -- is > that what you mean? > > Jon. Ouch, so the simplest solution is just insert in the 'main' function a try/catch? I believed there was the necessity to create a signal and than attach the KeyboardInterrupt to it... From rhodri at wildebst.demon.co.uk Wed Dec 9 19:37:54 2009 From: rhodri at wildebst.demon.co.uk (Rhodri James) Date: Thu, 10 Dec 2009 00:37:54 -0000 Subject: Immediate Help with python program! In-Reply-To: <1be06077-3173-41ca-a679-8d723eaff0c8@9g2000yqa.googlegroups.com> References: <1be06077-3173-41ca-a679-8d723eaff0c8@9g2000yqa.googlegroups.com> Message-ID: Ahem. This is a newsgroup/mailing list, not IM. I happen to have seen this within half an hour of you posting it, but that's just luck. Expecting an "immediate" response is unrealistic. Furthermore, this is comp.lang.python, a group right up there in pedantry terms with cam.misc. Wandering in and demanding "immediate" help is just begging for half a dozen replies that give you detailed and mind-boggling versions of exactly what you asked for, especially if it's got nothing to do with the answer you actually need. So... On Wed, 09 Dec 2009 23:55:01 -0000, Daniel wrote: > i am making a tic-tac-toe game using python. i am pretty new to it, > but cant seem to figure this one out. > Here is my code: > > X = "X" > O = "O" > empty = " " > tie = "Tie" > squares = 9 There's a convention (PEP 8, why not go to www.python.org and read it?) that constants should be given names in CAPITAL_LETTERS_AND_UNDERSCORES so that you can tell at a glance that they aren't supposed to be changed. PEP 8 also has things to say about function names. [snip rest of program] > Here is my problem: > If you hit 'n' at the beginning prompt, the computer does four moves > automatically and wins- you can't input anything. Sounds like you have a bug in your end-of-turn function. To be fair, it took me a couple of minutes to be sure I'd spotted this correctly. > If you hit 'y' at > the beginning prompt, you can play but cannot win. I got three x's in > a row and it didn't let me win. It just keeps letting > you input numbers until the computer wins even if you have three in a > row. Sounds like you have a bug in your check-for-a-win function. That should be all the hint you need. -- Rhodri James *-* Wildebeest Herder to the Masses From gm41lu53r at gmail.com Wed Dec 9 19:39:34 2009 From: gm41lu53r at gmail.com (my name) Date: Wed, 9 Dec 2009 19:39:34 -0500 Subject: web crawler in python Message-ID: <1497b7590912091639i1dcc928fp360f8de410fffe11@mail.gmail.com> I'm currently planning on writing a web crawler in python but have a question as far as how I should design it. My goal is speed and maximum efficient use of the hardware\bandwidth I have available. As of now I have a Dual 2.4ghz xeon box, 4gb ram, 500gb sata and a 20mbps bandwidth cap (for now) . Running FreeBSD. What would be the best way to design the crawler? Using the thread module? Would I be able to max out this connection with the hardware listed above using python threads? Thank you kindly. -------------- next part -------------- An HTML attachment was scrubbed... URL: From debatem1 at gmail.com Wed Dec 9 19:41:11 2009 From: debatem1 at gmail.com (geremy condra) Date: Wed, 9 Dec 2009 19:41:11 -0500 Subject: Graph library for Python In-Reply-To: <4B203F5C.6000803@egenix.com> References: <4B1CFA36.9060805@egenix.com> <4B1D35BC.5000002@egenix.com> <4B1D5CB3.8030805@egenix.com> <4B1D8FB1.5010703@egenix.com> <4B203F5C.6000803@egenix.com> Message-ID: >> Generally, we've tried to discourage people from instantiating >> nodes and edges directly, in favor of having them controlled >> through the graph. Maybe something along the lines of: >> >> g = Graph(nodes=['a', 'b', 'c'], edges=[('a', 'b'), ('a', 'c'), ('b', 'c')]) >> >> ? > > That would work as well, but you then miss out on the extra > parameters you can pass to Edge() and Node(). Just pushed a change that will allow that. > In another email you wrote that Edge() and Node() constructors > should not be used directly, since they have to know the Graph > to which they belong. > > Wouldn't it be possible to implement this kind of parent- > referencing in a lazy way, ie. by postponing all the init- > processing until the Graph instance is known ? While possible, I'm wary of this. We tried it in an initial prototype (all nodes and edges descended naturally from a Universe graph until otherwise stated) and that way lie madness. Perhaps at some point someone would like to give another shot at it, though. >> Beware, that doesn't just match nodes. >> >> g = Graph() >> g.add_node('a') >> g.add_node('b') >> g.add_edge('a', 'b', 'ab') >> 'ab' in g # returns true > > I'd avoid such an ambiguity. It could easily hide programming > errors (testing for edges instead of nodes). > > OTOH, you could also regard the graph as a set of nodes > and edges (as you apparently already do). In that case, > you'd define > > for x in g: print x > > as iteration of both nodes and edges in some arbitrary > order and then use the more specific: > > for n in g.nodes: print x > for e in g.edges: print x > > for iteration over just the nodes or edges. Yup, that's exactly what we do. >>>>>> g.get_edge_attributes('weight', 'color') >>> {"ab": {"weight": 3, "color": "blue"}, >>> ?"ac": {"weight": 2, "color": "green"}, >>> ?"bc": {"weight": 1, "color": "red"}} >>> >>> Again, the idea is to reduce call overhead and later >>> on be able to move these lookups to C. >> >> Entirely doable, but I'm not sure I see the use case. >> Would you mind providing a more realistic example? > > The idea is that you use the Graph representation of the > data to implement some algorithm e.g. optimizing weights > for example. > > The algorithm could be implemented in C to be fast enough > for large data sets. > > The above two methods would then be used to quickly push the > original data into the graph and extract it again after > the algorithm has run. I can see this, but I think the cleaner way is just to iterate over nodes and edges. Having said that, if somebody wants to come up with some timing data and it seems to provide a big advantage, I think robbie for one would make the change. >> Hmm. Sounds like a plausible use case to me, although I'm >> not sure its one that should be encouraged. The bigger >> question in my mind is whether all attribute lookups should >> have to pay the extra lookup cost to support a somewhat >> narrow need. I'll definitely have to talk with the other devs >> about this one, and run a little bit of timing besides. > > This would only be an optional second way of accessing > the .data dictionary. > > node.data['pass'] = 1 > node.data['from'] = 'Las Vegas' > node.data['to'] = 'New York' > > would work without such modifications. Yes, but the change is not reflected on the node. For example: >>> g = Graph(nodes={'a':{'spotted':True}}) >>> g['a'].data['spotted'] = False >>> g['a'].data['spotted'] True I can see how this would represent a gotcha, though. Is there a general opinion on whether this is a plus or a minus? Geremy Condra From afriere at yahoo.co.uk Wed Dec 9 19:45:42 2009 From: afriere at yahoo.co.uk (Asun Friere) Date: Wed, 9 Dec 2009 16:45:42 -0800 (PST) Subject: switch References: <335204.99872.qm@web57905.mail.re3.yahoo.com> Message-ID: <5c4d8258-f1fa-4fee-ab67-bc88f4ac040e@u25g2000prh.googlegroups.com> On Dec 9, 5:39?pm, Steven D'Aprano wrote: > On Tue, 08 Dec 2009 21:36:23 -0800, Asun Friere wrote: > > On Dec 9, 4:02?pm, Kee Nethery wrote: > >> I string together a bunch of elif statements to simulate a switch > > >> if foo == True: > >> ? ? ? ? blah > >> elif bar == True: > >> ? ? ? ? blah blah > >> elif bar == False: > >> ? ? ? ? blarg > >> elif .... > > > This code is probably symptomatic of poor design. (Not to mention that > > your condition tests). ?For which reason python has no 'case' statement > > and why no decent OO language should. > > That's a provocative statement. > My reply was lost in the aether, so here goes again. If it's provocative, it is at least hedged. It is merely symptomatic and only probably so, because there are numerous instances where case logic is the only sensible solution. I'm not advocating some cargo- cult rule for the elimination of all uses of elif. If I were I would rightly be presented with numerous code examples where a switch is a sensible option, much as happens when someone pronounces against the humble goto statement. > > It is a principle of OO design that "an object should know what to do > > itself." ?Rather running an object though a series of tests, it is > > better to send the object a message, relying on polymorphism or duck- > > typing, and deal with any exceptions thrown. > > Perhaps that's true, but you'll note that the example given above doesn't > run a single object through a series of tests, but runs a series of tests > on DIFFERENT objects, to find the first which matches. > Well actually two objects with one being tested twice. But you are right, I was being sloppy when I wrote "running an object" especially in light of the fact that the following clause makes more sense when run against objects of potentially different class. Same for dispatch mechanisms of course. What I'm saying is that when you find a large if/elif/else in your code, regard it with suspicion and "consider" whether better design might not eliminate it. And I'm speaking as someone who still has to maintain some code (in perl not python) which has an if/elif/else statement spanning 5 A4 pages. What's worse, I was the one who did this to myself some 8 years ago. What I'm also saying is "learn about dispatch mechanisms," they are about the most useful patterns out there (next to the State pattern). As a matter of practice I have found that more often than not, large case statements can better be solved using double-dispatch. Obviously not all. Obviously! > But putting that aside, I find myself wondering how you would deal with > the following switch-like series of tests. > > def print_grades(score): > ? ? if not 0 <= score <= 100: > ? ? ? ? raise ValueError("score must be between 0 and 100") > ? ? if score < 50: > ? ? ? ? print "You have failed." > ? ? ? ? consider_suspension() > ? ? elif score == 50: > ? ? ? ? print "You have just passed by the skin of your teeth." > ? ? elif score < 60: > ? ? ? ? print "You have scored a D. You need to try harder." > ? ? elif score < 70: > ? ? ? ? print "You have scored a C." > ? ? elif score < 80: > ? ? ? ? print "You have scored a B. Well done." > ? ? elif score < 100: > ? ? ? ? print "Congratulations, you have scored an A." > ? ? else: > ? ? ? ? assert score == 100 > ? ? ? ? print "You have scored a PERFECT 100% SCORE!!!" > ? ? ? ? if not evidence_of_cheating(): > ? ? ? ? ? ? call_newspapers() > > Obviously that could, with a non-trivial amount of work, be turned into a > dictionary dispatch, but is the benefit worth the extra effort? > Probably not. Depending on the nature of the app, I'd probably be calling score.print_grades() and using cutoff values of 85, 75, 60 and 50 (perhaps not even hardcoded into the logic), but sure this is a fine example of a place where a solution other than a simple switch would be overkill. As such this example would be a good counter to the absolute repudiation of case logic I did not make. I doubt, however, that it is of great pedagogic value in alerting programmers to the design options available to them in overcomming what the perceive as a lack in the language. From python at mrabarnett.plus.com Wed Dec 9 19:50:09 2009 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 10 Dec 2009 00:50:09 +0000 Subject: Immediate Help with python program! In-Reply-To: <1be06077-3173-41ca-a679-8d723eaff0c8@9g2000yqa.googlegroups.com> References: <1be06077-3173-41ca-a679-8d723eaff0c8@9g2000yqa.googlegroups.com> Message-ID: <4B2045C1.7030304@mrabarnett.plus.com> Daniel wrote: > i am making a tic-tac-toe game using python. i am pretty new to it, > but cant seem to figure this one out. > Here is my code: > [snip] You problem is due to your choice of variable names, because '0' looks too much like 'O'. You also don't define 'ask'. From irmen.NOSPAM at xs4all.nl Wed Dec 9 19:59:04 2009 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Thu, 10 Dec 2009 01:59:04 +0100 Subject: Brent's variation of a factorization algorithm In-Reply-To: References: <4b202e78$0$22943$e4fe514c@news.xs4all.nl> Message-ID: <4b2047db$0$22942$e4fe514c@news.xs4all.nl> On 12/10/09 12:52 AM, n00m wrote: > On Dec 10, 1:11 am, Irmen de Jong wrote: >> 999999999 >> == 27 * 37037037 >> >> What gives? Isn't this thing supposed to factor numbers into the product >> of two primes? >> >> -irmen > > Only if you yield to it a SEMIprime =) A 'semiprime' being a product of 2 prime numbers, I suppose. >> 27 * 37037037 > Now you can apply brent() to these numbers, and so on Right :) I more or less expected it to do that by itself (didn't look at the algorithm) But you wrote that it might run indefinately if you feed it a prime number. There's no safeguard then against getting into an endless loop if you keep applying brent() to the factors it produces? Because in the end one or both factors will be prime... -irmen From afriere at yahoo.co.uk Wed Dec 9 20:02:22 2009 From: afriere at yahoo.co.uk (Asun Friere) Date: Wed, 9 Dec 2009 17:02:22 -0800 (PST) Subject: switch References: <335204.99872.qm@web57905.mail.re3.yahoo.com> <68e6e315-f3c7-4e52-a56f-802e99d75e6a@y32g2000prd.googlegroups.com> Message-ID: <46ec89b7-6a5c-4710-af30-04fe549f7470@u25g2000prh.googlegroups.com> On Dec 9, 7:08?pm, Carl Banks wrote: > What if the object is a string you just read from a file? > > How do you dispatch using polymorphism in that case? This would be a pertinent question, were I advocating that _all_ switch statements should, or even can, be replaced with "dispatch using polymorphism." What if, instead of reading strings from a file, you are parsing, say xml, into an object framework isomorphic to the file's schema? And no, this is not a contrived example. Now you want to print out the structure, or a branch thereof. To make matters interesting you want to be able to print it out in a number of different formats. So we have: 5 def print_out (element, fmnt) : 6 if element.__class__ is schema.Title : 7 if str(fmnt) == 'html' : 8 print_out_spam_title(element) 9 elif str(fmnt) == 'txt' : 10 print_out_ham_title(element) 11 elif .... 12 elif element.__class__ is schema.Paragraph : 13 if str(fmnt) == 'html' : 14 print_out_spam_paragraph(element) 15 elif str(fmnt) == 'txt' : 16 print_out_ham_paragraph(element) 17 elif ... 18 elif element.__class__ is ... 19 ... 20 And so on for a dozen or so tags and 3 formats. And imagine the joy of adding the 4th or 5th format. Now I guess you already realise that applying a dispatch mechanism here will improve the design and result in code that is dryer, far more easily extensible and arguably (but only arguably) more readible? From dkeeper09 at yahoo.com Wed Dec 9 20:23:18 2009 From: dkeeper09 at yahoo.com (Daniel) Date: Wed, 9 Dec 2009 17:23:18 -0800 (PST) Subject: Immediate Help with python program! References: <1be06077-3173-41ca-a679-8d723eaff0c8@9g2000yqa.googlegroups.com> Message-ID: <9c4ad5a6-4eb6-43e2-9a8c-13b3f7ac204a@s31g2000yqs.googlegroups.com> On Dec 9, 6:50?pm, MRAB wrote: > Daniel wrote: > > i am making a tic-tac-toe game using python. i am pretty new to it, > > but cant seem to figure this one out. > > Here is my code: > > [snip] > You problem is due to your choice of variable names, because '0' looks > too much like 'O'. > > You also don't define 'ask'. Appreciate the help guys. Sorry about postin it here, mistake on my part. Thanks again. From n00m at narod.ru Wed Dec 9 20:37:27 2009 From: n00m at narod.ru (n00m) Date: Wed, 9 Dec 2009 17:37:27 -0800 (PST) Subject: Brent's variation of a factorization algorithm References: <4b202e78$0$22943$e4fe514c@news.xs4all.nl> <4b2047db$0$22942$e4fe514c@news.xs4all.nl> Message-ID: On Dec 10, 2:59?am, Irmen de Jong wrote: > On 12/10/09 12:52 AM, n00m wrote: > > > On Dec 10, 1:11 am, Irmen de Jong ?wrote: > >> 999999999 > >> == 27 * 37037037 > > >> What gives? Isn't this thing supposed to factor numbers into the product > >> of two primes? > > >> -irmen > > > Only if you yield to it a SEMIprime =) > > A 'semiprime' being a product of 2 prime numbers, I suppose. > > >> 27 * 37037037 > > Now you can apply brent() to these numbers, and so on > > Right :) ? I more or less expected it to do that by itself (didn't look > at the algorithm) > > But you wrote that it might run indefinately if you feed it a prime > number. There's no safeguard then against getting into an endless loop > if you keep applying brent() to the factors it produces? Because in the > end one or both factors will be prime... > > -irmen Just to use e.g. Rabin-Miller's before supplying a number to brent() > A 'semiprime' being a product of 2 prime numbers, I suppose. Aha, exactly. ============================== Also it's worthy to test a num is it a perfect square? But all this is obvious trifles... From bearophileHUGS at lycos.com Wed Dec 9 20:59:34 2009 From: bearophileHUGS at lycos.com (Bearophile) Date: Wed, 9 Dec 2009 17:59:34 -0800 (PST) Subject: Graph library for Python References: <4B18F685.8050102@egenix.com> <4B1CFA36.9060805@egenix.com> <4B1D35BC.5000002@egenix.com> <4B1D5CB3.8030805@egenix.com> <00a70ac5$0$15659$c3e8da3@news.astraweb.com> Message-ID: <4b928074-3018-4f1b-a546-1a7c4bdc62fe@a32g2000yqm.googlegroups.com> Robin Becker: > There are already very many implementations eg > > http://code.google.com/p/igraphhttp://www.boost.org/doc/libs/release/libs/graphhttp://ernst-schroeder.uni.lu/Digraph/doc/http://code.google.com/p/python-graphhttp://compbio.washington.edu/~zach/py_graph/doc/html/public/py_graph... > > and many others......some of the above already seem to be very useful. There's mine too: http://sourceforge.net/projects/pynetwork/ API: http://code.activestate.com/recipes/466329/ Bye, bearophile From rmcorrespond at gmail.com Wed Dec 9 21:11:22 2009 From: rmcorrespond at gmail.com (rm) Date: Wed, 9 Dec 2009 18:11:22 -0800 (PST) Subject: Python for Newbies Message-ID: Here is a new tutorial that may be a good starting point for learning Python. http://www.themaemo.com/python-for-newbies/ From alfps at start.no Wed Dec 9 21:46:39 2009 From: alfps at start.no (Alf P. Steinbach) Date: Thu, 10 Dec 2009 03:46:39 +0100 Subject: Python for Newbies In-Reply-To: References: Message-ID: * rm: > Here is a new tutorial that may be a good starting point for learning > Python. > > http://www.themaemo.com/python-for-newbies/ Looks nice. I have two comments: (1) what is "the N900"?, and (2) the naming convention, using 'Num' for a variable and 'clsAddress' for a class, is opposite of the usual Python convention where one'd write 'num' and 'Address'. Shameless plug for my own writings, an introduction to /programming/ for newbies, using Python -- this work is progressing slowly but steadily: which is in Google Docs; a table of contents available as text file (it's not complete wrt. to latest stuff I added) and also in the PDF files themselves. Comments very welcome! :-) Cheers, - Alf PS: The last three or four paragraphs in ch 2 were sort of negative so I've replaced them with one single short much more upbeat paragraph. Working... From pavlovevidence at gmail.com Wed Dec 9 22:00:59 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 9 Dec 2009 19:00:59 -0800 (PST) Subject: switch References: <335204.99872.qm@web57905.mail.re3.yahoo.com> <68e6e315-f3c7-4e52-a56f-802e99d75e6a@y32g2000prd.googlegroups.com> <46ec89b7-6a5c-4710-af30-04fe549f7470@u25g2000prh.googlegroups.com> Message-ID: <40c4aae1-1f90-4d50-9d68-8d15cae0457b@k4g2000yqb.googlegroups.com> On Dec 9, 5:02?pm, Asun Friere wrote: > On Dec 9, 7:08?pm, Carl Banks wrote: > > > What if the object is a string you just read from a file? > > > How do you dispatch using polymorphism in that case? > > This would be a pertinent question, were I advocating that _all_ > switch statements should, or even can, be replaced with "dispatch > using polymorphism." Then why did you claim that a decent OO should never have a switch statement then? You argued that a decent language OO should never have a switch statement because polymorphic dispatch is the right way to handle it in OO languages, which implies that polymorphism can and should take the place of any switch statement. > What if, instead of reading strings from a file, Why don't you answer my question first, then I'll entertain whatever point you are trying to make with this example? Carl Banks From python at mrabarnett.plus.com Wed Dec 9 22:11:36 2009 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 10 Dec 2009 03:11:36 +0000 Subject: Python for Newbies In-Reply-To: References: Message-ID: <4B2066E8.3010306@mrabarnett.plus.com> Alf P. Steinbach wrote: > * rm: >> Here is a new tutorial that may be a good starting point for learning >> Python. >> >> http://www.themaemo.com/python-for-newbies/ > > Looks nice. > > I have two comments: (1) what is "the N900"?, and (2) the naming > convention, using 'Num' for a variable and 'clsAddress' for a class, is > opposite of the usual Python convention where one'd write 'num' and > 'Address'. > [snip] (1) Nokia N900. (2) I agree that the naming convention is nonPythonic. From rmcorrespond at gmail.com Wed Dec 9 22:11:45 2009 From: rmcorrespond at gmail.com (rm) Date: Wed, 9 Dec 2009 19:11:45 -0800 (PST) Subject: Python for Newbies References: Message-ID: On Dec 9, 9:46?pm, "Alf P. Steinbach" wrote: > * rm: > > > Here is a new tutorial that may be a good starting point for learning > > Python. > > >http://www.themaemo.com/python-for-newbies/ > > Looks nice. > > I have two comments: (1) what is "the N900"?, and (2) the naming convention, > using 'Num' for a variable and 'clsAddress' for a class, is opposite of the > usual Python convention where one'd write 'num' and 'Address'. > > Shameless plug for my own writings, an introduction to /programming/ for > newbies, using Python ?-- ?this work is progressing slowly but steadily: > > ? ? > > which is in Google Docs; a table of contents available as text file (it's not > complete wrt. to latest stuff I added) and also in the PDF files themselves. > > Comments very welcome! :-) > > Cheers, > > - Alf > > PS: The last three or four paragraphs in ch 2 were sort of negative so I've > replaced them with one single short much more upbeat paragraph. Working... The N900 is what I consider the coolest portable device ever: http://temporaryland.wordpress.com/2009/10/09/nokian900-not-just-an-itoy/ http://www.themaemo.com/and-now-for-something-completely-different-the-n900-and-its-killer-feature/ This tutorial is also a work in progress. We welcome the help. In fact there is a Google Wave already set up for this purpose. I'll take a look at your writings. What license are you making them available with. From rmcorrespond at gmail.com Wed Dec 9 22:56:21 2009 From: rmcorrespond at gmail.com (rm) Date: Wed, 9 Dec 2009 19:56:21 -0800 (PST) Subject: Python for Newbies References: Message-ID: <3356e371-71d4-4ebd-9f8d-b498f67d634a@v25g2000yqk.googlegroups.com> On Dec 9, 9:46?pm, "Alf P. Steinbach" wrote: > * rm: > > > Here is a new tutorial that may be a good starting point for learning > > Python. > > >http://www.themaemo.com/python-for-newbies/ > > Looks nice. > > I have two comments: (1) what is "the N900"?, and (2) the naming convention, > using 'Num' for a variable and 'clsAddress' for a class, is opposite of the > usual Python convention where one'd write 'num' and 'Address'. > > Shameless plug for my own writings, an introduction to /programming/ for > newbies, using Python ?-- ?this work is progressing slowly but steadily: > > ? ? > > which is in Google Docs; a table of contents available as text file (it's not > complete wrt. to latest stuff I added) and also in the PDF files themselves. > > Comments very welcome! :-) > > Cheers, > > - Alf > > PS: The last three or four paragraphs in ch 2 were sort of negative so I've > replaced them with one single short much more upbeat paragraph. Working... One of the reasons I started writing this tutorial was because I found the lot of existing tutorials lacking in their approachability by people new to programming. Just about all of them were either not comprehensive enough, or seemed written by geniuses for geniuses. I hope you will allow me to quote a little excerpt from your tutorial that makes my point quite eloquently: "I have to use as-yet-unexplained language features in order to present examples that do relevant things, because it would be too much to explain the language features & concepts here. These features are explained in later chapters, so for now you can just adopt a very casual attitude, hey, it works!" Don't get me wrong, your approach probably works for a certain type of people. But there are a lot of us that find this approach very difficult to follow. The approach of this tutorial is gradually introduce new concepts so that the student can follow along at a logical and pleasant pace. Yes, it has a disadvantage. The examples can't be too elaborate. But, the purpose of tutorial, to teach the language, is better accomplished this way. If I was teaching a group of people the English language, I would not go about doing so with a George Gordon Byron poem. From debatem1 at gmail.com Wed Dec 9 23:09:26 2009 From: debatem1 at gmail.com (geremy condra) Date: Wed, 9 Dec 2009 23:09:26 -0500 Subject: Graph library for Python In-Reply-To: <4b928074-3018-4f1b-a546-1a7c4bdc62fe@a32g2000yqm.googlegroups.com> References: <4B1D35BC.5000002@egenix.com> <4B1D5CB3.8030805@egenix.com> <00a70ac5$0$15659$c3e8da3@news.astraweb.com> <4b928074-3018-4f1b-a546-1a7c4bdc62fe@a32g2000yqm.googlegroups.com> Message-ID: On Wed, Dec 9, 2009 at 8:59 PM, Bearophile wrote: > Robin Becker: > >> There are already very many implementations eg >> >> http://code.google.com/p/igraphhttp://www.boost.org/doc/libs/release/libs/graphhttp://ernst-schroeder.uni.lu/Digraph/doc/http://code.google.com/p/python-graphhttp://compbio.washington.edu/~zach/py_graph/doc/html/public/py_graph... >> >> and many others......some of the above already seem to be very useful. > > There's mine too: > http://sourceforge.net/projects/pynetwork/ > API: > http://code.activestate.com/recipes/466329/ > > Bye, > bearophile Huh, I don't think I've ever seen that before, and I'm pretty sure I'd remember if I had. With your permission, I'd like to go ahead and start integrating some of the features from that into graphine, especially a topo traversal. Do you mind? Geremy Condra From yjoshi at starentnetworks.com Wed Dec 9 23:14:50 2009 From: yjoshi at starentnetworks.com (Joshi, Yateen) Date: Thu, 10 Dec 2009 09:44:50 +0530 Subject: Issues with multiprocessing Message-ID: <3BD53621E5C8E54594130AF5459379EE135B9197@exchindia4.starentnetworks.com> Hi, I have an application that uses multiprocessing pools (multiprocessing.Pool(processes=.....)). There are multiple such pools and each pool has configurable number of processes. Once the process is spawned, it keeps on executing and does the needed processing. If there is nothing to process (like ftp'ing files from some source, if the files are not there, the process would sleep for some time, and then again check for files, that way, it is a infinite loop with some sleep), the process 'sleeps' for some time and continues. I am using a T5220, Solaris box with Solaris 10. Problem -there are multiple pools and multiple processes, i am seeing that not all the processes get spawned. They get spawned when the sleep time is increased (say from 0.1 sec to 1 sec). If I further increase the number of processes, again some process do not get spawned. For that, I further need to increase the sleep time (say to 2 sec), then the processes get spawned. Typically, in a multiprocessing I would expect that if a process sleeps for even a small time, other processes should get their chance to execute, but this does not seem to be happening here. Can you please throw some light on it? Thanks and Regards, Yateen V. Joshi This email and any attachments may contain legally privileged and/or confidential information of Starent Networks, Corp. and is intended only for the individual or entity named in the message. The information transmitted may not be used to create or change any contractual obligations of Starent Networks, Corp. Any review, retransmission, dissemination or other use of, or taking of any action in reliance upon this e-mail and its attachments by persons or entities other than the intended recipient is prohibited. If you are not the intended recipient, please notify the sender immediately -- by replying to this message or by sending an email to postmaster at starentnetworks.com -- and destroy all copies of this message and any attachments without reading or disclosing their contents. Thank you. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alfps at start.no Wed Dec 9 23:34:06 2009 From: alfps at start.no (Alf P. Steinbach) Date: Thu, 10 Dec 2009 05:34:06 +0100 Subject: Python for Newbies In-Reply-To: <3356e371-71d4-4ebd-9f8d-b498f67d634a@v25g2000yqk.googlegroups.com> References: <3356e371-71d4-4ebd-9f8d-b498f67d634a@v25g2000yqk.googlegroups.com> Message-ID: * rm: > On Dec 9, 9:46 pm, "Alf P. Steinbach" wrote: >> * rm: >> >>> Here is a new tutorial that may be a good starting point for learning >>> Python. >>> http://www.themaemo.com/python-for-newbies/ >> Looks nice. >> >> I have two comments: (1) what is "the N900"?, and (2) the naming convention, >> using 'Num' for a variable and 'clsAddress' for a class, is opposite of the >> usual Python convention where one'd write 'num' and 'Address'. >> >> Shameless plug for my own writings, an introduction to /programming/ for >> newbies, using Python -- this work is progressing slowly but steadily: >> >> >> >> which is in Google Docs; a table of contents available as text file (it's not >> complete wrt. to latest stuff I added) and also in the PDF files themselves. >> >> Comments very welcome! :-) >> >> Cheers, >> >> - Alf >> >> PS: The last three or four paragraphs in ch 2 were sort of negative so I've >> replaced them with one single short much more upbeat paragraph. Working... > > One of the reasons I started writing this tutorial was because I found > the lot of existing tutorials lacking in their approachability by > people new to programming. Just about all of them were either not > comprehensive enough, or seemed written by geniuses for geniuses. I > hope you will allow me to quote a little excerpt from your tutorial > that makes my point quite eloquently: > > "I have to use as-yet-unexplained language features in order to > present examples that do relevant things, because it would be too much > to explain the language features & concepts here. These features are > explained in later chapters, so for now you can just adopt a very > casual attitude, hey, it works!" > > Don't get me wrong, your approach probably works for a certain type of > people. But there are a lot of us that find this approach very > difficult to follow. The approach of this tutorial is gradually > introduce new concepts so that the student can follow along at a > logical and pleasant pace. Well, we agree on that. :-) You just quoted the above a little out of context. It's about the code examples in ch 1. Ch 1 is /not/ about programming: it's about tool usage, getting started, and next to nothing about the language or programming is discussed. So from my POV as author that criticism is like criticizing a bus driver for not explaining the technical workings of the bus when he's taking potential new bus drivers on a tour of the bus routes they may/will be driving later. Of course if the potential new drivers expect to be educated about the bus' technical stuff on that tour, just ignoring or not registering the up-front information about the tour, then they may grumble about only being shown some scenery, and what's this all about places and distances and routes? So, I think you read that with wrong expectations. > Yes, it has a disadvantage. The examples > can't be too elaborate. But here we disagree somewhat. If you look at ch 2 you'll see that with Python examples can be quite impressive without using more than just the tiniest little subset of the language. That is, when one has room to discuss things (difficult in an web based tutorial like yours, or like my once-upon-a-time C++ tutorial, but now I do have that room for discussion and guidance!) then a student's first examples do not need to be text only or dry academic. :-) > But, the purpose of tutorial, to teach the > language, is better accomplished this way. If I was teaching a group > of people the English language, I would not go about doing so with a > George Gordon Byron poem. Oh, I think you should! Especially considering that his daughter Augusta Ada was the world's first programmer and could be suspected of having an affair with Augustus de Morgan (who together with George Boole invented boolean logic, they published their works in the same week, and anyway was Augusta's private math tutor). Or perhaps start more easy, with Augustus de Morgan's infamous recursive fleas poem (ah, one may suspect some connection to Lord Byron there)! Cheers, - Alf From debatem1 at gmail.com Wed Dec 9 23:56:30 2009 From: debatem1 at gmail.com (geremy condra) Date: Wed, 9 Dec 2009 23:56:30 -0500 Subject: Python for Newbies In-Reply-To: References: Message-ID: > The N900 is what I consider the coolest portable device ever: > > http://temporaryland.wordpress.com/2009/10/09/nokian900-not-just-an-itoy/ > > http://www.themaemo.com/and-now-for-something-completely-different-the-n900-and-its-killer-feature/ Dunno if you intended to, but in the last link you imply that you can't run Python on android, when you can do so either via ASE or through the JNI. Geremy Condra From FearsomeDragonfly at gmail.com Wed Dec 9 23:56:33 2009 From: FearsomeDragonfly at gmail.com (Brad Harms) Date: Thu, 10 Dec 2009 04:56:33 GMT Subject: KeyboardInterrupt References: <4b203886$0$34595$4fafbaef@reader1.news.tin.it> <0a336844-ac41-4d80-9310-4e1f63701eb6@u7g2000yqm.googlegroups.com> <4b2040f9$0$34595$4fafbaef@reader1.news.tin.it> Message-ID: <5c%Tm.61315$We2.28453@newsfe09.iad> On Thu, 10 Dec 2009 00:29:45 +0000, mattia wrote: > Il Wed, 09 Dec 2009 16:19:24 -0800, Jon Clements ha scritto: > >> On Dec 9, 11:53?pm, mattia wrote: >>> Hi all, can you provide me a simple code snippet to interrupt the >>> execution of my program catching the KeyboardInterrupt signal? >>> >>> Thanks, >>> Mattia >> >> Errr, normally you can just catch the KeyboardInterrupt exception -- is >> that what you mean? >> >> Jon. > > Ouch, so the simplest solution is just insert in the 'main' function a > try/catch? I believed there was the necessity to create a signal and > than attach the KeyboardInterrupt to it... KeyboardInterrupt is just an exception that gets raised when CTLR+C (or the OS's equivalent keyboard combo) gets pressed. It can occur at any point in a script since you never know when the user will press it, which is why you put the try: except KeyboardInterrupt: around as much of your script as possible. The signal that the OS sends to the Python interpreter is irrelevant. -- Brad Harms -- http://alphaios.net From debatem1 at gmail.com Thu Dec 10 00:39:05 2009 From: debatem1 at gmail.com (geremy condra) Date: Thu, 10 Dec 2009 00:39:05 -0500 Subject: Graph library for Python In-Reply-To: References: <4B1D35BC.5000002@egenix.com> <4B1D5CB3.8030805@egenix.com> <00a70ac5$0$15659$c3e8da3@news.astraweb.com> <4b928074-3018-4f1b-a546-1a7c4bdc62fe@a32g2000yqm.googlegroups.com> Message-ID: On Wed, Dec 9, 2009 at 11:09 PM, geremy condra wrote: > On Wed, Dec 9, 2009 at 8:59 PM, Bearophile wrote: >> Robin Becker: >> >>> There are already very many implementations eg >>> >>> http://code.google.com/p/igraphhttp://www.boost.org/doc/libs/release/libs/graphhttp://ernst-schroeder.uni.lu/Digraph/doc/http://code.google.com/p/python-graphhttp://compbio.washington.edu/~zach/py_graph/doc/html/public/py_graph... >>> >>> and many others......some of the above already seem to be very useful. >> >> There's mine too: >> http://sourceforge.net/projects/pynetwork/ >> API: >> http://code.activestate.com/recipes/466329/ >> >> Bye, >> bearophile > > Huh, I don't think I've ever seen that before, and I'm pretty > sure I'd remember if I had. With your permission, I'd like to > go ahead and start integrating some of the features from > that into graphine, especially a topo traversal. Do you > mind? > > Geremy Condra > Since that's released under the python license, I'm going to go ahead and commit the version that includes the topo traversal, but if you have any objections you only need to say the word and I'll take it down. Geremy Condra From steven at REMOVE.THIS.cybersource.com.au Thu Dec 10 00:47:19 2009 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 10 Dec 2009 05:47:19 GMT Subject: switch References: <335204.99872.qm@web57905.mail.re3.yahoo.com> Message-ID: On Wed, 09 Dec 2009 18:50:29 +0000, Nobody wrote: > On Tue, 08 Dec 2009 21:02:44 -0800, Kee Nethery wrote: > >> I string together a bunch of elif statements to simulate a switch >> >> if foo == True: >> blah >> elif bar == True: >> blah blah >> elif bar == False: >> blarg >> elif .... > > This isn't what would normally be considered a switch (i.e. what C > considers a switch). Anyone would think that C was the only programming language in existence... > A switch tests the value of an expression against a > set of constants. In C. Things may be different in other languages. For example, I recall the so-called "4GL" (remember when that was the marketing term of choice for interpreted programming languages?) Hyperscript from Informix. I can't check the exact syntax right now, but it had a switch statement which allowed you to do either C-like tests against a single expression, or if-like multiple independent tests. Moving away from obsolete languages, we have Ruby which does much the same thing: if you provide a test value, the case expression does a C- like test against that expression, and if you don't, it does if-like multiple tests. http://www.skorks.com/2009/08/how-a-ruby-case-statement-works-and-what- you-can-do-with-it/ > If you were writing the above in C, you would need to > use a chain of if/else statements; you couldn't use a switch. > > Compiled languages' switch statements typically require constant labels > as this enables various optimisations. Pascal, for example, can test against either single values, enumerated values, or a range of values: case n of 0: writeln('zero'); 1, 2: writeln('one or two'); 3...10: writeln('something between three and ten'); else writeln('something different'); end; -- Steven From frank at chagford.com Thu Dec 10 01:21:34 2009 From: frank at chagford.com (Frank Millman) Date: Thu, 10 Dec 2009 08:21:34 +0200 Subject: How do I Block Events in wxPython References: <6854a0bb-9edc-4392-9761-d2f3cf98f89e@k4g2000yqb.googlegroups.com> Message-ID: Wanderer wrote: >I have a wxPython program which does some calculations and displays > the results. During these calculations if I click the mouse inside the > dialog the program locks up. If I leave the dialog alone the process > completes fine. I have tried running the function from a separate > dialog with Show Modal and I have tried using SetEvtHandlerEnabled all > to no avail. The program is long and occupies several files so I won't > show the whole thing but here is the calculation part. How do I block > events? > I also need to block events in my wxPython app, though the time duration is very short. I have a separate thread that sends notification of gui events to a server, and waits for a response. I do not want the user to do anything until the response is received. I use threading.Event() for this - import threading event_waiting = threading.Event() event_waiting.set() # set event to True In the gui thread, when I want to block, I have this - event_waiting.clear() # set event to False event_waiting.wait() # block until event becomes True In the worker thread, when the response has been received and acted upon, I have - event_waiting.set() # set event to True, which unblocks the gui thread HTH Frank Millman From rob.hooft at gmail.com Thu Dec 10 01:47:04 2009 From: rob.hooft at gmail.com (rwwh) Date: Wed, 9 Dec 2009 22:47:04 -0800 (PST) Subject: Creating a local variable scope. References: <4b12f20c@dnews.tpgi.com.au> Message-ID: On Nov 30, 1:26?am, markolopa wrote: > I would be much happier with the smaller namespace. To fix the code > that you show I would impose > > s = None > while True: > ? ? ?s = raw_input("enter something: ") > ? ? ?if s not in ('q', 'quit', 'exit'): break > print s So you propose: if the variable exists in a wider scope, you ideal python would not create it in an inner scope. How is this helping your original case? I remind you: class ValueColumn(AbstractColumn): def __init__(self, name, header, domain_names): if type(domain_names) != tuple: raise ValueError('blub') for name in domain_names: if type(name) != str: raise ValueError('blub') self.domain_names = domain_names super(ValueColumn, self).__init__(name, header) When "for name" is reached, "name" already exists and no local variable would be created. How does this help you? From patrickstinson.lists at gmail.com Thu Dec 10 02:44:02 2009 From: patrickstinson.lists at gmail.com (Patrick Stinson) Date: Thu, 10 Dec 2009 00:44:02 -0700 Subject: freeze in python3 Message-ID: <6214d7a20912092344ga7ec4bav7aea69f55134114a@mail.gmail.com> NOTE: This is related but is not a duplicate of my post from yesterday. Has anyone used Tools/freeze/freeze.py in python3? I tried it with a clean source distribution and for some reason freeze.py is generating code that uses the old naming convention for module init functions. I get the following unresolved symbols for the default hello.py: Undefined symbols for architecture i386: "_init_codecs", referenced from: __PyImport_Inittab in config.o "_init_functools", referenced from: __PyImport_Inittab in config.o "_init_thread", referenced from: __PyImport_Inittab in config.o "_initerrno", referenced from: __PyImport_Inittab in config.o "_initposix", referenced from: __PyImport_Inittab in config.o "_initgc", referenced from: __PyImport_Inittab in config.o "_init_locale", referenced from: __PyImport_Inittab in config.o "_init_io", referenced from: __PyImport_Inittab in config.o "_init_sre", referenced from: __PyImport_Inittab in config.o "_initimp", referenced from: __PyImport_Inittab in config.o "_initpwd", referenced from: __PyImport_Inittab in config.o "_init_weakref", referenced from: __PyImport_Inittab in config.o "_initsignal", referenced from: __PyImport_Inittab in config.o "_initzipimport", referenced from: __PyImport_Inittab in config.o For example, initerrno should now be PyInit_errno. Am I missing something? From apt.shansen at gmail.com Thu Dec 10 02:57:59 2009 From: apt.shansen at gmail.com (Stephen Hansen) Date: Wed, 9 Dec 2009 23:57:59 -0800 Subject: How do I Block Events in wxPython In-Reply-To: References: <6854a0bb-9edc-4392-9761-d2f3cf98f89e@k4g2000yqb.googlegroups.com> Message-ID: <7a9c25c20912092357i7fb0e327gf88919a85fdf3482@mail.gmail.com> On Wed, Dec 9, 2009 at 10:21 PM, Frank Millman wrote: > Wanderer wrote: > > >I have a wxPython program which does some calculations and displays > > the results. During these calculations if I click the mouse inside the > > dialog the program locks up. If I leave the dialog alone the process > > completes fine. I have tried running the function from a separate > > dialog with Show Modal and I have tried using SetEvtHandlerEnabled all > > to no avail. The program is long and occupies several files so I won't > > show the whole thing but here is the calculation part. How do I block > > events? > > > > I also need to block events in my wxPython app, though the time duration is > very short. I have a separate thread that sends notification of gui events > to a server, and waits for a response. I do not want the user to do > anything > until the response is received. > > I don't think "blocking" events is the right way to think about this. If you need to halt new input for some reason (bearing in mind that its best to run such things in a background task, but yes, sometimes blocking the UI is important), then there's a couple ways to go about it. But trying to mess with the event loop isn't it. First, you always want a visual indicator-- use SetCursor on your top level window to set a busy cursor. You never want any sort of block-ish action to happen without the user being able to see "something is going on"; if its more then a second or so I /really/ think you should throw up a progress indicator dialog, even if its an infinate one. To actually 'block' the events themselves, you can just call wnd.Enable(False). Just be sure to Enable(True) when you want to process stuff again. Another approach is to use wnd.CaptureMouse() on a particular control which doesn't really respond to anything. Just be sure to ReleaseMouse() later and follow the instructions in the docs about capturing that cancel-capture event. HTH, --S -------------- next part -------------- An HTML attachment was scrubbed... URL: From nagle at animats.com Thu Dec 10 03:18:13 2009 From: nagle at animats.com (John Nagle) Date: Thu, 10 Dec 2009 00:18:13 -0800 Subject: When will Python 3 be fully deployed In-Reply-To: References: Message-ID: <4b20ac0a$0$1596$742ec2ed@news.sonic.net> Luis M. Gonz?lez wrote: > On Dec 6, 3:21 pm, vsoler wrote: >> I recently read that many libraries, including Numpy have not been >> ported to Python 3. >> >> When do you think that Python 3 will be fully deployed? >> >> Should I stick, so far, to Python 2.6? >> >> Regards >> >> Vicente Soler > > You'll have some answers here: http://jessenoller.com/2009/12/04/pythons-moratorium-lets-think-about-this/ I'd argue against using Python 2.6 for production work. Either use Python 2.5, which is stable, or 3.x, which is bleeding-edge. 2.6 has some of the features of Python 3.x, but not all of them, and is neither fish nor fowl as a result. 2.6 is really more of a sideline that was used for trying out new features, not something suitable for production. I think the idea is to run your 2.5 code through '2to3" and see if it works in 3.x. Anyway, it will be years, if ever, before Python 3.x gets any real support. Too many major packages still aren't fully supported on it, and some popular packages, like SGMLlib and Feedparser, are being dropped. When a few major Linux distros ship with Python 3.x and enough of the binary packages to run a web site, take a look at it again. John Nagle From nad at acm.org Thu Dec 10 03:42:21 2009 From: nad at acm.org (Ned Deily) Date: Thu, 10 Dec 2009 00:42:21 -0800 Subject: When will Python 3 be fully deployed References: <4b20ac0a$0$1596$742ec2ed@news.sonic.net> Message-ID: In article <4b20ac0a$0$1596$742ec2ed at news.sonic.net>, John Nagle wrote: > I'd argue against using Python 2.6 for production work. Either use > Python > 2.5, which is stable, or 3.x, which is bleeding-edge. 2.6 has some of the > features of Python 3.x, but not all of them, and is neither fish nor fowl > as a result. 2.6 is really more of a sideline that was used for trying > out new features, not something suitable for production. I disagree with that advice, strongly. 2.6 not only has new features but it has many bug fixes that have not and will not be applied to 2.5. It is hardly a sideline. See http://www.python.org/download/releases/2.5.4/ for the official policy on 2.5, in particular: "Future releases of Python 2.5 [ -- that is, should the need arise -- ] will only contain security patches; no new features are being added, and no 'regular' bugs will be fixed anymore." "If you want the latest production version of Python, use Python 2.6.1 or later." [2.6.4 is the latest version]. Then see http://www.python.org/download/releases/2.6.4/ Note that Python 2.6 is considered the stable version and is "now in bugfix-only mode; no new features are being added". Per normal python development policy, new features are added to the next major release cycles, now under development: Python 2.7 and Python 3.2. -- Ned Deily, nad at acm.org From michele.simionato at gmail.com Thu Dec 10 04:13:47 2009 From: michele.simionato at gmail.com (Michele Simionato) Date: Thu, 10 Dec 2009 01:13:47 -0800 (PST) Subject: "file" does not work with the "with" statement! Message-ID: <96de036d-9da8-41df-b395-0a51775efbfa@j4g2000yqe.googlegroups.com> I have just discovered that the syntax with file(name, 'w') as f: do_something(f) does not close the file at the end of the with statement! On the contrary with open(name, 'w') as f: do_something(f) works fine. The docs say "When opening a file, it?s preferable to use open() instead of invoking this constructor directly." but perhaps they should mention why :( From jspies at sun.ac.za Thu Dec 10 04:15:19 2009 From: jspies at sun.ac.za (Johann Spies) Date: Thu, 10 Dec 2009 11:15:19 +0200 Subject: Parsing html with Beautifulsoup Message-ID: <20091210091519.GA14175@sun.ac.za> I am trying to get csv-output from a html-file. With this code I had a little success: ========================= from BeautifulSoup import BeautifulSoup from string import replace, join import re f = open("configuration.html","r") g = open("configuration.csv",'w') soup = BeautifulSoup(f) t = soup.findAll('table') for table in t: rows = table.findAll('tr') for th in rows[0]: t = th.find(text=True) g.write(t) g.write(',') # print(','.join(t)) for tr in rows: cols = tr.findAll('td') for td in cols: try: t = td.find(text=True).replace(' ','') g.write(t) except: g.write ('') g.write(",") g.write("\n") =============================== producing output like this: RULE,SOURCE,DESTINATION,SERVICES,ACTION,TRACK,TIME,INSTALL ON,COMMENTS, 1,,,,drop,Log,Any,,, 2,All Users at Any,,Any,clientencrypt,Log,Any,,, 3,Any,Any,,drop,None,Any,,, 4,,,,drop,None,Any,,, ... It left out all the non-plaintext parts of I then tried using t.renderContents and then got something like this (one line broken into many for the sake of this email): 1,  sunetint
,  href=#OBJ_Rainwall_Cluster >Rainwall_Cluster
, src=icons/udp.png> IKE
,  drop,  Log ,  Any
 ,  Rainwall_Cluster
 ,  How do I get Beautifulsoup to render (taking the above line as example) sunentint for  sunetint
and still provide the text-parts in the 's with plain text? I have experimented a little bit with regular expressions, but could so far not find a solution. Regards Johann -- Johann Spies Telefoon: 021-808 4599 Informasietegnologie, Universiteit van Stellenbosch "Lo, children are an heritage of the LORD: and the fruit of the womb is his reward." Psalms 127:3 From ernst.karner at gmail.com Thu Dec 10 04:50:09 2009 From: ernst.karner at gmail.com (diego) Date: Thu, 10 Dec 2009 01:50:09 -0800 (PST) Subject: Connecting to Python COM server from Excel VBA does not work Message-ID: <740e0649-958a-4a7b-ac33-d26e5adb732d@b2g2000yqi.googlegroups.com> I ran this script: --------------------------- class Example(object): _public_methods_ = ['Add','Mul'] _reg_progid_ = 'MyPython.Example' _reg_clsid_ = '{E39ECD8C-7FAF-48B0-B914-1202319499D4}' def Add(self,a,b): return a+b def Mul(self,a,b): return a*b if __name__ == '__main__': import win32com.server.register win32com.server.register.UseCommandLine(Example) --------------------------------- connecting to this COM server works with following VBS-script: --------------------------------- Set ex = CreateObject("MyPython.Example") msgbox ex.Add(1, 2) --------------------------------- when i run following VBA script in excel --------------------------------- Sub Testit() Set ex = CreateObject("MyPython.Example") MsgBox ex.Add(1, 2) End Sub --------------------------------- i get the error: Run-time error '-2137024770 (8007007e)': Automation error The specified module could not be found Any ideas what the problem could be? Already searched a long time for solutions but did not find any.... thanks, diego From __peter__ at web.de Thu Dec 10 04:59:03 2009 From: __peter__ at web.de (Peter Otten) Date: Thu, 10 Dec 2009 10:59:03 +0100 Subject: "file" does not work with the "with" statement! References: <96de036d-9da8-41df-b395-0a51775efbfa@j4g2000yqe.googlegroups.com> Message-ID: Michele Simionato wrote: > I have just discovered that the syntax > > with file(name, 'w') as f: > do_something(f) > > does not close the file at the end of the with statement! On the > contrary > > with open(name, 'w') as f: > do_something(f) > > works fine. The docs say "When opening a file, it?s preferable to use > open() instead of invoking this constructor directly." but perhaps > they should mention why :( Are you sure? Python 2.6.4 (r264:75706, Nov 2 2009, 14:44:17) [GCC 4.4.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> with file("tmp.txt", "w") as f: ... print >> f, "whatever" ... >>> f.write("something") Traceback (most recent call last): File "", line 1, in ValueError: I/O operation on closed file Peter From H.Schaathun at surrey.ac.uk Thu Dec 10 05:02:22 2009 From: H.Schaathun at surrey.ac.uk (Hans Georg Schaathun) Date: Thu, 10 Dec 2009 10:02:22 +0000 Subject: DCT transform (API)? (scipy or otherwise) Message-ID: I am looking for a 2-D DCT transform function for use in python. Does anyone have any good pointers? I see that one is promised in scipy 0.8.0, but I cannot find any details on how close that is to being released. I am not sure if running bleeding-edge scipy would solve my problem; I should have liked more experience with numerical programming before I tried that, especially since I do not otherwise use the C and fortran libraries it is based on. Are there alternatives to scipy for this particular feature? TIA for any pointers :-- George From deets at nospam.web.de Thu Dec 10 05:04:40 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 10 Dec 2009 11:04:40 +0100 Subject: "file" does not work with the "with" statement! References: <96de036d-9da8-41df-b395-0a51775efbfa@j4g2000yqe.googlegroups.com> Message-ID: <7obvdoF3ki9u5U1@mid.uni-berlin.de> Michele Simionato wrote: > I have just discovered that the syntax > > with file(name, 'w') as f: > do_something(f) > > does not close the file at the end of the with statement! On the > contrary > > with open(name, 'w') as f: > do_something(f) > > works fine. The docs say "When opening a file, it?s preferable to use > open() instead of invoking this constructor directly." but perhaps > they should mention why :( Are you sure? For me on python2.5, it works as advertised: from __future__ import with_statement def test(outf): with outf: outf.write("test\n") try: outf.write("test\n") assert False, "Not closed" except ValueError: pass outf = open("/tmp/foo", "w") test(outf) outf = file("/tmp/bar", "w") test(outf) Which Python do you use? Diez From bearophileHUGS at lycos.com Thu Dec 10 05:18:26 2009 From: bearophileHUGS at lycos.com (Bearophile) Date: Thu, 10 Dec 2009 02:18:26 -0800 (PST) Subject: Graph library for Python References: <4B1D35BC.5000002@egenix.com> <4B1D5CB3.8030805@egenix.com> <00a70ac5$0$15659$c3e8da3@news.astraweb.com> <4b928074-3018-4f1b-a546-1a7c4bdc62fe@a32g2000yqm.googlegroups.com> Message-ID: <9ed4268c-46d7-48ba-a841-25df6d938fdb@g7g2000yqa.googlegroups.com> geremy condra: > Since that's released under the python license, I'm going to > go ahead and commit the version that includes the topo > traversal, but if you have any objections you only need to > say the word and I'll take it down. No objections :-) Bye, bearophile From __peter__ at web.de Thu Dec 10 05:24:04 2009 From: __peter__ at web.de (Peter Otten) Date: Thu, 10 Dec 2009 11:24:04 +0100 Subject: relative imports with the __import__ function References: Message-ID: Chris Colbert wrote: > It seems the relative import level is dependent on the location of the > main entry module. I thought the whole idea of relative imports was to > make the import independent of the entry point? You don't have to specify it explicitly, so you can move a module containing from .foo import bar into another package without changing its source code (provided there is a foo submodule with a bar attribute). This includes the trivial case of renaming the parent package. Of course Python has to know the importing module's location, just like you cannot meet me one block north and three blocks west unless you know where I currently am. See also http://www.python.org/dev/peps/pep-0328/#rationale-for-relative-imports Peter From michele.simionato at gmail.com Thu Dec 10 05:29:20 2009 From: michele.simionato at gmail.com (Michele Simionato) Date: Thu, 10 Dec 2009 02:29:20 -0800 (PST) Subject: "file" does not work with the "with" statement! References: <96de036d-9da8-41df-b395-0a51775efbfa@j4g2000yqe.googlegroups.com> <7obvdoF3ki9u5U1@mid.uni-berlin.de> Message-ID: On Dec 10, 11:04?am, "Diez B. Roggisch" wrote: > Are you sure? For me on python2.5, it works as advertised: > > from __future__ import with_statement > > def test(outf): > ? ? with outf: > ? ? ? ? outf.write("test\n") > ? ? try: > ? ? ? ? outf.write("test\n") > ? ? ? ? assert False, "Not closed" > ? ? except ValueError: > ? ? ? ? pass > > outf = open("/tmp/foo", "w") > test(outf) > outf = file("/tmp/bar", "w") > test(outf) > > Which Python do you use? > > Diez Python 2.5, but it could be an artifact of the way I am looking if a file is closed. I have subclassed the file builtin, added a .close method and it was not called by the "with" statement. This during debugging, but now I have found another reason to explain why I was running out of file descriptors, (I was opening too many connections to the db). It is entirely possible that the problem was not with the "with" statement. From deets at nospam.web.de Thu Dec 10 05:35:18 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 10 Dec 2009 11:35:18 +0100 Subject: "file" does not work with the "with" statement! References: <96de036d-9da8-41df-b395-0a51775efbfa@j4g2000yqe.googlegroups.com> <7obvdoF3ki9u5U1@mid.uni-berlin.de> Message-ID: <7oc176F3nvt85U1@mid.uni-berlin.de> Michele Simionato wrote: > On Dec 10, 11:04?am, "Diez B. Roggisch" wrote: >> Are you sure? For me on python2.5, it works as advertised: >> >> from __future__ import with_statement >> >> def test(outf): >> with outf: >> outf.write("test\n") >> try: >> outf.write("test\n") >> assert False, "Not closed" >> except ValueError: >> pass >> >> outf = open("/tmp/foo", "w") >> test(outf) >> outf = file("/tmp/bar", "w") >> test(outf) >> >> Which Python do you use? >> >> Diez > > Python 2.5, but it could be an artifact of the way I am looking if a > file is closed. The above ran on python2.5 for me, no hitch. > I have subclassed the file builtin, added a .close method and it was > not called by the > "with" statement. This during debugging, but now I have found another > reason to explain why I was > running out of file descriptors, (I was opening too many connections > to the db). > It is entirely possible that the problem was not with the "with" > statement. Probably. Closing a file through with might not involve calling close() - it might be implemented differently in __exit__. So overload *that*, too. Diez From enleverLesX_XXmcX at XmclavXeauX.com.invalid Thu Dec 10 05:52:55 2009 From: enleverLesX_XXmcX at XmclavXeauX.com.invalid (Michel Claveau - MVP) Date: Thu, 10 Dec 2009 11:52:55 +0100 Subject: Connecting to Python COM server from Excel VBA does not work References: <740e0649-958a-4a7b-ac33-d26e5adb732d@b2g2000yqi.googlegroups.com> Message-ID: <4b20d30d$0$17502$ba4acef3@news.orange.fr> Hi ! Warning with lower/uppercases! Try to make two versions of your methods (ex.: "add" & "ADD"), for study. @+ -- MCI From __peter__ at web.de Thu Dec 10 05:55:53 2009 From: __peter__ at web.de (Peter Otten) Date: Thu, 10 Dec 2009 11:55:53 +0100 Subject: "file" does not work with the "with" statement! References: <96de036d-9da8-41df-b395-0a51775efbfa@j4g2000yqe.googlegroups.com> <7obvdoF3ki9u5U1@mid.uni-berlin.de> Message-ID: Michele Simionato wrote: > On Dec 10, 11:04 am, "Diez B. Roggisch" wrote: >> Are you sure? For me on python2.5, it works as advertised: >> >> from __future__ import with_statement >> >> def test(outf): >> with outf: >> outf.write("test\n") >> try: >> outf.write("test\n") >> assert False, "Not closed" >> except ValueError: >> pass >> >> outf = open("/tmp/foo", "w") >> test(outf) >> outf = file("/tmp/bar", "w") >> test(outf) >> >> Which Python do you use? >> >> Diez > > Python 2.5, but it could be an artifact of the way I am looking if a > file is closed. > I have subclassed the file builtin, added a .close method and it was > not called by the > "with" statement. This during debugging, but now I have found another > reason to explain why I was > running out of file descriptors, (I was opening too many connections > to the db). > It is entirely possible that the problem was not with the "with" > statement. Subclassing file doesn't work properly: http://mail.python.org/pipermail/python-list/2005-April/920562.html Peter From lists at cheimes.de Thu Dec 10 05:59:55 2009 From: lists at cheimes.de (Christian Heimes) Date: Thu, 10 Dec 2009 11:59:55 +0100 Subject: "file" does not work with the "with" statement! In-Reply-To: References: <96de036d-9da8-41df-b395-0a51775efbfa@j4g2000yqe.googlegroups.com> <7obvdoF3ki9u5U1@mid.uni-berlin.de> Message-ID: <4B20D4AB.5020008@cheimes.de> Michele Simionato wrote: > Python 2.5, but it could be an artifact of the way I am looking if a > file is closed. > I have subclassed the file builtin, added a .close method and it was > not called by the > "with" statement. This during debugging, but now I have found another > reason to explain why I was > running out of file descriptors, (I was opening too many connections > to the db). > It is entirely possible that the problem was not with the "with" > statement. In Python 2.5 you have to implement your own __enter__ and __exit__ methods if you subclass from file. The file.__exit__ function doesn't call f.close(). The minor inconsistency has been fixed in Python 2.6. Python 2.5: static PyObject * file_exit(PyFileObject *f, PyObject *args) { PyObject *ret = file_close(f); if (!ret) /* If error occurred, pass through */ return NULL; Py_DECREF(ret); /* We cannot return the result of close since a true * value will be interpreted as "yes, swallow the * exception if one was raised inside the with block". */ Py_RETURN_NONE; } Python 2.6: static PyObject * file_exit(PyObject *f, PyObject *args) { PyObject *ret = PyObject_CallMethod(f, "close", NULL); if (!ret) /* If error occurred, pass through */ return NULL; Py_DECREF(ret); /* We cannot return the result of close since a true * value will be interpreted as "yes, swallow the * exception if one was raised inside the with block". */ Py_RETURN_NONE; } From emekamicro at gmail.com Thu Dec 10 06:01:32 2009 From: emekamicro at gmail.com (Emeka) Date: Thu, 10 Dec 2009 11:01:32 +0000 Subject: C to Python Message-ID: <89c38c820912100301r7c31b434k466b8a6f4d394ae5@mail.gmail.com> Hello All, I am finding it difficult getting my head around PyObject_CallObject(x,y). I need a gentle and thorough introduction to it. I also need examples. Could someone come to my need? Thanks. Janus. -------------- next part -------------- An HTML attachment was scrubbed... URL: From feliphil at gmx.net Thu Dec 10 06:32:41 2009 From: feliphil at gmx.net (Wolfgang Keller) Date: Thu, 10 Dec 2009 12:32:41 +0100 Subject: Generating diagrams from PostgreSQL with Python (Re: postgresql_autodoc in Python?) References: <20091206150742.45d0c4aa.feliphil@gmx.net> Message-ID: <20091210123241.fe3e781a.feliphil@gmx.net> Hello, I will re-precise my question: Has anyone ever implemented a script in Python that generates documentation (especially diagrams, in a format such as e.g. Dia, Inkscape SVG or Tikz) for a PostgreSQL database either from an SQL script or by connecting to the database? Postgresql_autodoc is unfortunately written in Perl. >;-> TIA, And, btw., please respect my .sig, Sincerely, Wolfgang Keller -- NO "Courtesy Copies" PLEASE! From afriere at yahoo.co.uk Thu Dec 10 06:34:53 2009 From: afriere at yahoo.co.uk (Asun Friere) Date: Thu, 10 Dec 2009 03:34:53 -0800 (PST) Subject: switch References: <335204.99872.qm@web57905.mail.re3.yahoo.com> <68e6e315-f3c7-4e52-a56f-802e99d75e6a@y32g2000prd.googlegroups.com> <46ec89b7-6a5c-4710-af30-04fe549f7470@u25g2000prh.googlegroups.com> <40c4aae1-1f90-4d50-9d68-8d15cae0457b@k4g2000yqb.googlegroups.com> Message-ID: <67b225de-8fc3-415a-819a-61370fecff47@a10g2000pre.googlegroups.com> On Dec 10, 2:00 pm, Carl Banks wrote: > On Dec 9, 5:02 pm, Asun Friere wrote: > > > On Dec 9, 7:08 pm, Carl Banks wrote: > > > > What if the object is a string you just read from a file? > > > > How do you dispatch using polymorphism in that case? > > > This would be a pertinent question, were I advocating that _all_ > > switch statements should, or even can, be replaced with "dispatch > > using polymorphism." > > Then why did you claim that a decent OO should never have a switch > statement then? The mere fact that it is possible to demonstrate a use of the 'goto' statement, which does not offend against a program's structural integrity, does not mean it's necessarily a good idea to have it lying about given that in the large majority of cases it leads to (encourages?) bad code. Python sagely declined to implement 'goto'. I feel the same considerations apply in regard to the switch/case statement in the context of a true* OO (ie python but not java ;>). Imo the decision not to implement a switch statement was wise. This is not to deny that a traditional switch is not in often a sane solution. I just think that if your elifs are getting unwieldy enough to require the application of the proverbial layer of abstraction, then a switch statement fails to deliver sufficient abstraction. > You argued that a decent language OO should never > have a switch statement because polymorphic dispatch is the right way > to handle it in OO languages, which implies that polymorphism can and > should take the place of any switch statement. That is a misreading. I wrote, that the case logic is "probably" symptomatic of poor design. I advocated "considering" whether an OO solution might be more appropriate. You misunderstand my intent. I'm not here to postulate some ultimate OO truths, but to provide practical advice (aimed here mainly at Hong and Kee). In regard elif chains, this is my advice. If you see too many elifs in your code (or if you find yourself wishing for a switch statement) alarm bells should start to go off. STOP, give serious consideration as to whether applying some patterns or similar will improve the design, and HINT: first consider whether that pattern might be something resembling a dispatch mechanism, it's just downright spooky how in real-life programming situations this turns out to be the answer. Obviously the answers to these questions are not invariably 'yes.' Often enough they are. > > > What if, instead of reading strings from a file, > > Why don't you answer my question first, Because, as I have already explained, I object to the question. It presupposes my holding a position I don't. But look perhaps I'm being unfair to you Carl. I presumed your question was rhetorical, or at least you supposed it disproved whatever it is you were attacking. If instead you were asking for clarification, the short answer is "wrap as you read." A longer answer is in the response to Tim, I'll send in a while. cheers From deets at nospam.web.de Thu Dec 10 06:48:17 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 10 Dec 2009 12:48:17 +0100 Subject: Generating diagrams from PostgreSQL with Python (Re: postgresql_autodoc in Python?) References: <20091206150742.45d0c4aa.feliphil@gmx.net> <20091210123241.fe3e781a.feliphil@gmx.net> Message-ID: <7oc5g1F3po3e7U1@mid.uni-berlin.de> Wolfgang Keller wrote: > Hello, > > I will re-precise my question: > > Has anyone ever implemented a script in Python that generates > documentation (especially diagrams, in a format such as e.g. Dia, Inkscape > SVG or Tikz) for a PostgreSQL database either from an SQL script or by > connecting to the database? I've written a schemadiff-tool for postgres based on SQLAlchemy reflection, which is a branch of SQLAlchemy and which should become part of the upcoming SA 0.6. http://svn.sqlalchemy.org/sqlalchemy/branches/reflection It allows you to extract information about the schema of the DB. This could be the foundation of your tool. > > Postgresql_autodoc is unfortunately written in Perl. >;-> > > TIA, > > And, btw., please respect my .sig, Which is supposed to mean what? Never heard the term courtesy copy. Diez From almar.klein at gmail.com Thu Dec 10 06:50:43 2009 From: almar.klein at gmail.com (Almar Klein) Date: Thu, 10 Dec 2009 12:50:43 +0100 Subject: freeze in python3 In-Reply-To: <6214d7a20912092344ga7ec4bav7aea69f55134114a@mail.gmail.com> References: <6214d7a20912092344ga7ec4bav7aea69f55134114a@mail.gmail.com> Message-ID: Hi Patrick, It's not exactly what you asked, but I've been able to freeze a Python 3 project using cx_Freeze. Almar 2009/12/10 Patrick Stinson : > NOTE: This is related but is not a duplicate of my post from yesterday. > > Has anyone used Tools/freeze/freeze.py in python3? I tried it with a > clean source distribution and for some reason freeze.py is generating > code that uses the old naming convention for module init functions. I > get the following unresolved symbols for the default hello.py: > > Undefined symbols for architecture i386: > ?"_init_codecs", referenced from: > ? ? ?__PyImport_Inittab in config.o > ?"_init_functools", referenced from: > ? ? ?__PyImport_Inittab in config.o > ?"_init_thread", referenced from: > ? ? ?__PyImport_Inittab in config.o > ?"_initerrno", referenced from: > ? ? ?__PyImport_Inittab in config.o > ?"_initposix", referenced from: > ? ? ?__PyImport_Inittab in config.o > ?"_initgc", referenced from: > ? ? ?__PyImport_Inittab in config.o > ?"_init_locale", referenced from: > ? ? ?__PyImport_Inittab in config.o > ?"_init_io", referenced from: > ? ? ?__PyImport_Inittab in config.o > ?"_init_sre", referenced from: > ? ? ?__PyImport_Inittab in config.o > ?"_initimp", referenced from: > ? ? ?__PyImport_Inittab in config.o > ?"_initpwd", referenced from: > ? ? ?__PyImport_Inittab in config.o > ?"_init_weakref", referenced from: > ? ? ?__PyImport_Inittab in config.o > ?"_initsignal", referenced from: > ? ? ?__PyImport_Inittab in config.o > ?"_initzipimport", referenced from: > ? ? ?__PyImport_Inittab in config.o > > For example, initerrno should now be PyInit_errno. Am I missing something? > -- > http://mail.python.org/mailman/listinfo/python-list > From michele.simionato at gmail.com Thu Dec 10 06:59:31 2009 From: michele.simionato at gmail.com (Michele Simionato) Date: Thu, 10 Dec 2009 03:59:31 -0800 (PST) Subject: "file" does not work with the "with" statement! References: <96de036d-9da8-41df-b395-0a51775efbfa@j4g2000yqe.googlegroups.com> <7obvdoF3ki9u5U1@mid.uni-berlin.de> Message-ID: <30a8e551-8554-417c-991e-489b9d4be5af@f16g2000yqm.googlegroups.com> On Dec 10, 11:59?am, Christian Heimes wrote: > In Python 2.5 you have to implement your own __enter__ and __exit__ > methods if you subclass from file. The file.__exit__ function doesn't > call f.close(). Yes, that was my problem. From joaopcf at gmail.com Thu Dec 10 07:16:40 2009 From: joaopcf at gmail.com (=?ISO-8859-1?Q?Jo=E3o?=) Date: Thu, 10 Dec 2009 04:16:40 -0800 (PST) Subject: plain text parsing to html (newbie problem) References: <6664c88b-ec93-4b6c-a536-8a6b5959cd5e@a21g2000yqc.googlegroups.com> <35a19377-d2d4-4fb1-ad58-b999e0b9ff8f@u16g2000pru.googlegroups.com> Message-ID: <4a58a2cf-32e1-4170-a962-cd81aeb2c7c7@m16g2000yqc.googlegroups.com> Thanks for the output. akean, I've installed ipython and I'm exploring it. Thanks. Terry, from what I've read stringIO allows us to store strings in a 'virtual' file. Can you please write just 2 lines exemplifying a write to and a read from an OS level file? MRAB, that 'mail' object should've been the os level 'mail' file. But as I'm a beginner I was using it wrong.. Thanks From joaopcf at gmail.com Thu Dec 10 07:17:19 2009 From: joaopcf at gmail.com (=?ISO-8859-1?Q?Jo=E3o?=) Date: Thu, 10 Dec 2009 04:17:19 -0800 (PST) Subject: plain text parsing to html (newbie problem) References: <6664c88b-ec93-4b6c-a536-8a6b5959cd5e@a21g2000yqc.googlegroups.com> <35a19377-d2d4-4fb1-ad58-b999e0b9ff8f@u16g2000pru.googlegroups.com> Message-ID: <0f2e4a9a-284e-425f-9f02-045f32268d16@n35g2000yqm.googlegroups.com> Thanks for the output. akean, I've installed ipython and I'm exploring it. Thanks. Terry, from what I've read stringIO allows us to store strings in a 'virtual' file. Can you please write just 2 lines exemplifying a write to and a read from an OS level file? MRAB, that 'mail' object should've been the os level 'mail' file. But as I'm a beginner I was using it wrong.. Thanks From clp2 at rebertia.com Thu Dec 10 07:18:00 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Thu, 10 Dec 2009 04:18:00 -0800 Subject: Generating diagrams from PostgreSQL with Python (Re: postgresql_autodoc in Python?) In-Reply-To: <7oc5g1F3po3e7U1@mid.uni-berlin.de> References: <20091206150742.45d0c4aa.feliphil@gmx.net> <20091210123241.fe3e781a.feliphil@gmx.net> <7oc5g1F3po3e7U1@mid.uni-berlin.de> Message-ID: <50697b2c0912100418m1f5f5cd0q99704acf8820f5f8@mail.gmail.com> On Thu, Dec 10, 2009 at 3:48 AM, Diez B. Roggisch wrote: > Wolfgang Keller wrote: > >> Hello, >> >> I will re-precise my question: >> >> Has anyone ever implemented a script in Python that generates >> documentation (especially diagrams, in a format such as e.g. Dia, Inkscape >> SVG or Tikz) for a PostgreSQL database either from an SQL script or by >> connecting to the database? > > I've written a schemadiff-tool for postgres based on SQLAlchemy reflection, > which is a branch of SQLAlchemy and which should become part of the > upcoming SA 0.6. > > http://svn.sqlalchemy.org/sqlalchemy/branches/reflection > > It allows you to extract information about the schema of the DB. This could > be the foundation of your tool. > >> >> Postgresql_autodoc is unfortunately written in Perl. >;-> >> >> TIA, >> >> And, btw., please respect my .sig, > > Which is supposed to mean what? Never heard the term courtesy copy. It appears to be an incorrect expansion of "Cc", which is actually Carbon copy. Apparently he means all replies should be directly to the list and not Cc his individual email address. Which seems strange, because usually mailinglists are smart enough not to send the author duplicate copies if they're named in the To or Cc fields. Cheers, Chris -- http://blog.rebertia.com From ernst.karner at gmail.com Thu Dec 10 07:26:03 2009 From: ernst.karner at gmail.com (diego) Date: Thu, 10 Dec 2009 04:26:03 -0800 (PST) Subject: Connecting to Python COM server from Excel VBA does not work References: <740e0649-958a-4a7b-ac33-d26e5adb732d@b2g2000yqi.googlegroups.com> <4b20d30d$0$17502$ba4acef3@news.orange.fr> Message-ID: On 10 Dez., 11:52, "Michel Claveau - MVP" wrote: > Hi ! > > Warning with lower/uppercases! > Try to make two versions of your methods (ex.: "add" & "ADD"), for study. > > @+ > -- > MCI The error comes already at the first line of Excel/VBA code: Set ex = CreateObject("MyPython.Example") rgds,e From ernst.karner at gmail.com Thu Dec 10 07:27:54 2009 From: ernst.karner at gmail.com (diego) Date: Thu, 10 Dec 2009 04:27:54 -0800 (PST) Subject: Connecting to Python COM server from Excel VBA does not work References: <740e0649-958a-4a7b-ac33-d26e5adb732d@b2g2000yqi.googlegroups.com> <4b20d30d$0$17502$ba4acef3@news.orange.fr> Message-ID: <3815e11c-26b5-4607-929e-bf4e31c1b0f2@j24g2000yqa.googlegroups.com> On 10 Dez., 11:52, "Michel Claveau - MVP" wrote: > Hi ! > > Warning with lower/uppercases! > Try to make two versions of your methods (ex.: "add" & "ADD"), for study. > > @+ > -- > MCI The error comes already at the first line of Excel/VBA code: Set ex = CreateObject("MyPython.Example") rgds,e From afriere at yahoo.co.uk Thu Dec 10 07:29:37 2009 From: afriere at yahoo.co.uk (Asun Friere) Date: Thu, 10 Dec 2009 04:29:37 -0800 (PST) Subject: switch References: <335204.99872.qm@web57905.mail.re3.yahoo.com> <68e6e315-f3c7-4e52-a56f-802e99d75e6a@y32g2000prd.googlegroups.com> Message-ID: <9010003a-d129-46b4-9535-88b03f0bc121@w19g2000pre.googlegroups.com> On Dec 10, 6:57 am, Tim Chase wrote: > Carl Banks wrote: > > What if the object is a string you just read from a file? > > > How do you dispatch using polymorphism in that case? > > This is where I most miss a switch/case statement in Python...I > do lots of text-file processing (cellular provider data), so I > have lots of code (for each provider's individual format) that > looks like > > phones = {} > for row in csv.DictReader(file('data.txt', 'rb')): > phonenumber = row['phonenumber'] > if phonenumber not in phones: > phones[phonenumber] = Phone(phonenumber) > phone = phones[phonenumber] > rectype = rectype > if rectype == '01': > phone.international += Decimal(row['internationalcost']) > elif rectype == '02': > phone.text_messaging += ( > int(row['textmessages sent']) + > int(row['pages received']) + > int(row['textmessages sent']) + > int(row['pages received']) > elif rectype == ... > ... > else: > raise WhatTheHeckIsThis() > Great example Tim. This is something that many of us must be dealing with on a daily basis. The problem has enough details (bar one), to allow an answer and not so detailed as to be confusing. And for me it's a particularly good example, because your need accommodate mulitple provider formats makes me feel right at home. > which would nicely change into something like > > switch row['recordtype']: > case '01': > phone.international += Decimal(row['internationalcost']) > // optionally a "break" here depending on > // C/C++/Java/PHP syntax vs. Pascal syntax which > // doesn't have fall-through > case '02': > phone.text_messaging += ( > int(row['textmessages sent']) + > int(row['pages received']) + > int(row['textmessages sent']) + > int(row['pages received']) > ... > default: > raise WhatTheHeckIsThis() Cleaner yes. But, with respect, not so clean as to justify the construct. Following my advice you might express that switch statement like so: phone.update_from_record(record) It is, in this context, completely irrelevant observe that 'dispatch' originally referred specifically to the dismissal of ambassadors. It may be slightly more to the point to tap into the wisdom of Henry Ford and turn your design inside out. This switch statement belongs to one guy. One guy who wants to know how to do everything that needs to be done to Phones no matter who asks. Let's install a conveyor belt instead! Standard Disclaimer: Untested (obviously); just a sketch; I don't really know your problem only the code you've posted; etc etc. First some minimal "architecture": --- #The first class your already have. We just need one more method class Phone (object) : ... def update_from_record (self, rec) : return rec.updatePhone(self) #and then some "data source" classes class RecType (dict) : def __init__ (self, row) : ... class RecType_001 (RecType) : def updatePhone(self, phone) : phone.interational += Decimal(self['internationalcost']) class RecType_002 (RecType) : def updatePhone(self, phone) : phone.text_messaging += ( int(self['textmessages sent']) + int(self['pages received']) + ... #and if we must ... rectypes = {'01':RecType_001, '02': RecType_002, ...} # The one thing I'm sure I don't understand from the code is where the original rectypes comes into the process. #I would prefer, if it's possible, just thowing the appropriate class in rather than looking up this dict to instantiate. --- Now the different providor types, previously the bane of your existence, are your staff. Your original code will now read something like: phones = {} for row in csv.DictReader(open('data.txt', 'rb')) : try : record = rectypes[rectype](row) except KeyError : raise WhatTheHeckIsThisError('unknown rectype: %s' % rectype) phonenumber = record.phonenumber if phonenumber not in phones : phones[phonenumber] = Phone(phonenumber) phone = phones[phonenumber] phone.update_from_record(record) I wonder if you agree that it's bit cleaner now? It's an effective solution. I'm making no representation that it's the best. I like think largely because it contains the knowledge accessibly. If you have "lots of code" that deal with this kind of thing, chances are library of core data source classage could reduce much of it to a simple (and legible!) one liner. A provider "enhances" their format, or a new provider format is added, code in one class, not in every switch they might be involved in. But sorry, I don't mean to patronise, I'm sure you know the spiel. Asun From tiago at forked.de Thu Dec 10 07:48:27 2009 From: tiago at forked.de (Tiago de Paula Peixoto) Date: Thu, 10 Dec 2009 13:48:27 +0100 Subject: Graph library for Python In-Reply-To: <4B1E464B.6090408@chamonix.reportlab.co.uk> References: <4B18F685.8050102@egenix.com> <4B1CFA36.9060805@egenix.com> <4B1D35BC.5000002@egenix.com> <4B1D5CB3.8030805@egenix.com> <00a70ac5$0$15659$c3e8da3@news.astraweb.com> <4B1E464B.6090408@chamonix.reportlab.co.uk> Message-ID: On 12/08/2009 01:27 PM, Robin Becker wrote: > I don't want to sound pessimistic, but graph and digraph theory has a > lot of history, especially in computer science. There are already very > many implementations eg > > http://code.google.com/p/igraph > http://www.boost.org/doc/libs/release/libs/graph > http://ernst-schroeder.uni.lu/Digraph/doc/ > http://code.google.com/p/python-graph > http://compbio.washington.edu/~zach/py_graph/doc/html/public/py_graph-module.html I would like to point out the following two projects as additions to this list: http://graph-tool.forked.de (my own project) http://networkx.lanl.gov The graph-tool module uses the Boost Graph Library internally to achieve good numerical performance, while networkx has a more python-only approach. Cheers, Tiago -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 262 bytes Desc: OpenPGP digital signature URL: From debatem1 at gmail.com Thu Dec 10 07:56:45 2009 From: debatem1 at gmail.com (geremy condra) Date: Thu, 10 Dec 2009 07:56:45 -0500 Subject: Graph library for Python In-Reply-To: <9ed4268c-46d7-48ba-a841-25df6d938fdb@g7g2000yqa.googlegroups.com> References: <4B1D5CB3.8030805@egenix.com> <00a70ac5$0$15659$c3e8da3@news.astraweb.com> <4b928074-3018-4f1b-a546-1a7c4bdc62fe@a32g2000yqm.googlegroups.com> <9ed4268c-46d7-48ba-a841-25df6d938fdb@g7g2000yqa.googlegroups.com> Message-ID: On Thu, Dec 10, 2009 at 5:18 AM, Bearophile wrote: > geremy condra: > >> Since that's released under the python license, I'm going to >> go ahead and commit the version that includes the topo >> traversal, but if you have any objections you only need to >> say the word and I'll take it down. > > No objections :-) I appreciate it. I don't seem to be having any luck emailing you offlist, so please feel free to email me privately if you'd rather this not be indexed, but is there a particular way you want your attribution line to read? Geremy Condra From jeanmichel at sequans.com Thu Dec 10 07:57:51 2009 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Thu, 10 Dec 2009 13:57:51 +0100 Subject: accessing local variables from the pdb debugger Message-ID: <4B20F04F.5030507@sequans.com> Guys, I have some problem changing method locals with pdb: import pdb def test(): foo = 'foo' pdb.set_trace() test() --Return-- > /home/jeanmichel/trunk/tnt/test.py(5)test()->None -> pdb.set_trace() (Pdb) print foo foo (Pdb) foo = 'bar' (Pdb) print foo foo (Pdb) I tried using locals() but it returns a copy of the locals. So changing locals['foo'] won't do any good. (Pdb) locals() Out[6]: {'__return__': None, 'foo': 'foo'} Any idea ? I'm starting to wonder if it is possible. JM From deets at nospam.web.de Thu Dec 10 08:04:08 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 10 Dec 2009 14:04:08 +0100 Subject: accessing local variables from the pdb debugger References: Message-ID: <7oc9u8F3onimoU1@mid.uni-berlin.de> Jean-Michel Pichavant wrote: > Guys, > > I have some problem changing method locals with pdb: > > import pdb > > def test(): > foo = 'foo' > pdb.set_trace() > > test() > --Return-- > > /home/jeanmichel/trunk/tnt/test.py(5)test()->None > -> pdb.set_trace() > (Pdb) print foo > foo > (Pdb) foo = 'bar' > (Pdb) print foo > foo > (Pdb) > > > I tried using locals() but it returns a copy of the locals. So changing > locals['foo'] won't do any good. > (Pdb) locals() > Out[6]: {'__return__': None, 'foo': 'foo'} > > > Any idea ? I'm starting to wonder if it is possible. I recall having some issues with local variables sometimes, but actually your example works fine for me: def test(): foo = "foo" import pdb; pdb.set_trace() print foo test() And the session: $ python /tmp/test.py > /tmp/test.py(9)test() -> print foo (Pdb) pp foo 'foo' (Pdb) foo = "bar" (Pdb) n bar --Return-- > /tmp/test.py(9)test()->None -> print foo (Pdb) c Diez From rmcorrespond at gmail.com Thu Dec 10 08:07:05 2009 From: rmcorrespond at gmail.com (rm) Date: Thu, 10 Dec 2009 05:07:05 -0800 (PST) Subject: Python for Newbies References: Message-ID: <5dc0bfb7-5642-4399-8d3c-0ab1c80e4e5b@y24g2000yqb.googlegroups.com> On Dec 9, 11:56?pm, geremy condra wrote: > > The N900 is what I consider the coolest portable device ever: > > >http://temporaryland.wordpress.com/2009/10/09/nokian900-not-just-an-i... > > >http://www.themaemo.com/and-now-for-something-completely-different-th... > > Dunno if you intended to, but in the last link you imply that you can't run > Python on android, when you can do so either via ASE or through the > JNI. > > Geremy Condra The article you mention says: "I realize that there is an effort in Android to make Python and other scripting languages available to some degree, but from what I have seen they are relegated to macro like functionality. In other words, you wont be able to create full blown stand alone Python applications in Android. The N900, on the other hand, will allow this. Even the GUI side of the applications can be created with well known Python toolkits like PyGTK and PyQt." That impression came from this blog: http://google-opensource.blogspot.com/2009/06/introducing-android-scripting.html Are you saying that one can write full blown stand alone Android applications in Python, GUI and all. From philip at semanchuk.com Thu Dec 10 08:24:11 2009 From: philip at semanchuk.com (Philip Semanchuk) Date: Thu, 10 Dec 2009 08:24:11 -0500 Subject: web crawler in python In-Reply-To: <1497b7590912091639i1dcc928fp360f8de410fffe11@mail.gmail.com> References: <1497b7590912091639i1dcc928fp360f8de410fffe11@mail.gmail.com> Message-ID: On Dec 9, 2009, at 7:39 PM, my name wrote: > I'm currently planning on writing a web crawler in python but have a > question as far as how I should design it. My goal is speed and > maximum > efficient use of the hardware\bandwidth I have available. > > As of now I have a Dual 2.4ghz xeon box, 4gb ram, 500gb sata and a > 20mbps > bandwidth cap (for now) . Running FreeBSD. > > What would be the best way to design the crawler? Using the thread > module? > Would I be able to max out this connection with the hardware listed > above > using python threads? I wrote a web crawler in Python (under FreeBSD, in fact) and I chose to do it using separate processes. Process A would download pages and write them to disk, process B would attempt to convert them to Unicode, process C would evaluate the content, etc. That worked well for me because the processes were very independent of one another so they had very little data to share. Each process had a work queue (Postgres database table); process A would feed B's queue, B would feed C & D's queues, etc. I should point out that my crawler spidered one site at a time. As a result the downloading process spent a lot of time waiting (in order to be polite to the remote Web server). This sounds pretty different from what you want to do (an indeed from most crawlers). Figuring out the best design for your crawler depends on a host of factors that you haven't mentioned. (What are you doing with the pages you download? Is the box doing anything else? Are you storing the pages long term or discarding them? etc.) I don't think we can do it for you -- I know *I* can't; I have a day job. ;) But I encourage you to try something out. If you find your code isn't giving what you want, come back to the list with a specific problem. It's always easier to help with specific than with general problems. Good luck Philip From pavlovevidence at gmail.com Thu Dec 10 08:25:45 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 10 Dec 2009 05:25:45 -0800 (PST) Subject: switch References: <335204.99872.qm@web57905.mail.re3.yahoo.com> <68e6e315-f3c7-4e52-a56f-802e99d75e6a@y32g2000prd.googlegroups.com> <46ec89b7-6a5c-4710-af30-04fe549f7470@u25g2000prh.googlegroups.com> <40c4aae1-1f90-4d50-9d68-8d15cae0457b@k4g2000yqb.googlegroups.com> <67b225de-8fc3-415a-819a-61370fecff47@a10g2000pre.googlegroups.com> Message-ID: <0d8b807d-c9ed-4df8-a427-e0e3b49aabf9@f18g2000prf.googlegroups.com> On Dec 10, 3:34?am, Asun Friere wrote: > On Dec 10, 2:00 pm, Carl Banks wrote: [snip most of questionable, verly verbose reply] > > You argued that a decent language OO should never > > have a switch statement because polymorphic dispatch is the right way > > to handle it in OO languages, which implies that polymorphism can and > > should take the place of any switch statement. > > That is a misreading. ?I wrote, that the case logic is "probably" > symptomatic of poor design. I advocated "considering" whether an OO > solution might be more appropriate. ?You misunderstand my intent. ?I'm > not here to postulate some ultimate OO truths, but to provide > practical advice (aimed here mainly at Hong and Kee). ?In regard elif > chains, this is my advice. Even granting that your post wasn't as drastic as it sounded (and enough people reacted to your first post that you should should "probably" "consider" whether it came off a little more strongly than you intended), I think you are still overstating it by a lot. OO polymorphic dispatching is good for some stuff, and simpler dispatching such with if...else, a dict, or a hypotheical switch, is good for some stuff. That's it. Having a bunch of if...elses is not "probably" wrong, and it's not a red flag, unless you're not a good programmer and have already missed a bunch of other more pertinent red flags. Carl Banks From jeanmichel at sequans.com Thu Dec 10 08:37:37 2009 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Thu, 10 Dec 2009 14:37:37 +0100 Subject: accessing local variables from the pdb debugger In-Reply-To: <7oc9u8F3onimoU1@mid.uni-berlin.de> References: <7oc9u8F3onimoU1@mid.uni-berlin.de> Message-ID: <4B20F9A1.9070800@sequans.com> Diez B. Roggisch wrote: > Jean-Michel Pichavant wrote: > > >> Guys, >> >> I have some problem changing method locals with pdb: >> >> import pdb >> >> def test(): >> foo = 'foo' >> pdb.set_trace() >> >> test() >> --Return-- >> > /home/jeanmichel/trunk/tnt/test.py(5)test()->None >> -> pdb.set_trace() >> (Pdb) print foo >> foo >> (Pdb) foo = 'bar' >> (Pdb) print foo >> foo >> (Pdb) >> >> >> I tried using locals() but it returns a copy of the locals. So changing >> locals['foo'] won't do any good. >> (Pdb) locals() >> Out[6]: {'__return__': None, 'foo': 'foo'} >> >> >> Any idea ? I'm starting to wonder if it is possible. >> > > I recall having some issues with local variables sometimes, but actually > your example works fine for me: > > > > def test(): > foo = "foo" > > > import pdb; pdb.set_trace() > > print foo > > test() > > > And the session: > > $ python /tmp/test.py > >> /tmp/test.py(9)test() >> > -> print foo > (Pdb) pp foo > 'foo' > (Pdb) foo = "bar" > (Pdb) n > bar > --Return-- > >> /tmp/test.py(9)test()->None >> > -> print foo > (Pdb) c > > > Diez > You're right, it can work, eventually... Take a look at sessions below: def test(): foo = 'foo' pdb.set_trace() print 'This is the test method displaying foo:', foo In [3]: test() > /home/jeanmichel/trunk/tnt/test.py(6)test() -> print 'This is the test method displaying foo:', foo (Pdb) foo='bar' (Pdb) c This is the test method displaying foo: bar In [5]: test() > /home/jeanmichel/trunk/tnt/test.py(6)test() -> print 'This is the test method displaying foo:', foo (Pdb) foo='bar' (Pdb) print foo foo (Pdb) c This is the test method displaying foo: foo By just inserting the print foo statement right after changing foo's value, I've rolled back the value to 'foo' ??? A hell of a wtf pdb feature ! JM PS : using python 2.5 From frank at chagford.com Thu Dec 10 09:01:28 2009 From: frank at chagford.com (Frank Millman) Date: Thu, 10 Dec 2009 16:01:28 +0200 Subject: How do I Block Events in wxPython References: <6854a0bb-9edc-4392-9761-d2f3cf98f89e@k4g2000yqb.googlegroups.com> <7a9c25c20912092357i7fb0e327gf88919a85fdf3482@mail.gmail.com> Message-ID: Stephen Hansen wrote: > On Wed, Dec 9, 2009 at 10:21 PM, Frank Millman wrote: > >> I also need to block events in my wxPython app, though the time duration >> is >> very short. I have a separate thread that sends notification of gui >> events >> to a server, and waits for a response. I do not want the user to do >> anything until the response is received. >> > I don't think "blocking" events is the right way to think about this. > > If you need to halt new input for some reason (bearing in mind that its > best > to run such things in a background task, but yes, sometimes blocking the > UI > is important), then there's a couple ways to go about it. But trying to > mess > with the event loop isn't it. In fact my method does not work. All that happens is that the events are queued, and as soon as I release the lock the events are processed in a bunch. Not clever :-( > > First, you always want a visual indicator-- use SetCursor on your top > level > window to set a busy cursor. You never want any sort of block-ish action > to > happen without the user being able to see "something is going on"; if its > more then a second or so I /really/ think you should throw up a progress > indicator dialog, even if its an infinate one. > Agreed. > To actually 'block' the events themselves, you can just call > wnd.Enable(False). Just be sure to Enable(True) when you want to process > stuff again. This may work for the OP, but would not really work for me, because it changes the visual appearance of all the controls. In my case the time duration for blocking is usually very short, so it could result in flicker. > > Another approach is to use wnd.CaptureMouse() on a particular control > which > doesn't really respond to anything. Just be sure to ReleaseMouse() later > and > follow the instructions in the docs about capturing that cancel-capture > event. > I like this. Unfortunately it does not block keyboard input. However, I have a keyboard event handler on virtually all my controls, so it should be easy to set a flag and tell it to ignore keystrokes while in a 'blocked' state. > HTH, It certainly does - thanks. Frank From debatem1 at gmail.com Thu Dec 10 09:13:40 2009 From: debatem1 at gmail.com (geremy condra) Date: Thu, 10 Dec 2009 09:13:40 -0500 Subject: Graph library for Python In-Reply-To: References: <4B1D35BC.5000002@egenix.com> <4B1D5CB3.8030805@egenix.com> <00a70ac5$0$15659$c3e8da3@news.astraweb.com> <4B1E464B.6090408@chamonix.reportlab.co.uk> Message-ID: On Thu, Dec 10, 2009 at 7:48 AM, Tiago de Paula Peixoto wrote: > On 12/08/2009 01:27 PM, Robin Becker wrote: >> I don't want to sound pessimistic, but graph and digraph theory has a >> lot of history, especially in computer science. There are already very >> many implementations eg >> >> http://code.google.com/p/igraph >> http://www.boost.org/doc/libs/release/libs/graph >> http://ernst-schroeder.uni.lu/Digraph/doc/ >> http://code.google.com/p/python-graph >> http://compbio.washington.edu/~zach/py_graph/doc/html/public/py_graph-module.html > > I would like to point out the following two projects as additions to > this list: > > http://graph-tool.forked.de (my own project) > http://networkx.lanl.gov > > The graph-tool module uses the Boost Graph Library internally to achieve > good numerical performance, while networkx has a more python-only > approach. > > Cheers, > Tiago Well, we all seem to have reinvented the wheel differently ;) Bearophile, Tiago- any interest in trying to combine the best parts of our libraries, with an eye towards eventual integration into the standard library? Geremy Condra From python.list at tim.thechases.com Thu Dec 10 09:38:31 2009 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 10 Dec 2009 08:38:31 -0600 Subject: switch In-Reply-To: <9010003a-d129-46b4-9535-88b03f0bc121@w19g2000pre.googlegroups.com> References: <335204.99872.qm@web57905.mail.re3.yahoo.com> <68e6e315-f3c7-4e52-a56f-802e99d75e6a@y32g2000prd.googlegroups.com> <9010003a-d129-46b4-9535-88b03f0bc121@w19g2000pre.googlegroups.com> Message-ID: <4B2107E7.8040206@tim.thechases.com> > Great example Tim. This is something that many of us must be dealing > with on a daily basis. The problem has enough details (bar one), to > allow an answer and not so detailed as to be confusing. And for me > it's a particularly good example, because your need accommodate > mulitple provider formats makes me feel right at home. > >> which would nicely change into something like >> >> switch row['recordtype']: >> case '01': >> phone.international += Decimal(row['internationalcost']) >> // optionally a "break" here depending on >> // C/C++/Java/PHP syntax vs. Pascal syntax which >> // doesn't have fall-through >> case '02': >> phone.text_messaging += ( >> int(row['textmessages sent']) + >> int(row['pages received']) + >> int(row['textmessages sent']) + >> int(row['pages received']) >> ... >> default: >> raise WhatTheHeckIsThis() > > Cleaner yes. But, with respect, not so clean as to justify the > construct. Following my advice you might express that switch > statement like so: > > phone.update_from_record(record) > > This switch statement belongs to one guy. One guy who wants to know > how to do everything that needs to be done to Phones no matter who > asks This is where you make a false assumption -- the contents and parsing of the "switch" are provider-specific in this case, mapping to a common ontology of the Phone object: class MonopolyProvider1Parser: ... switch row['recordtype']: case '01': phone.international += Decimal(row['internationalcost']) // optionally a "break" here depending on // C/C++/Java/PHP syntax vs. Pascal syntax which // doesn't have fall-through case '02': phone.text_messaging += ( int(row['textmessages sent']) + int(row['pages received']) + int(row['textmessages sent']) + int(row['pages received']) ... default: raise WhatTheHeckIsThis() class MonopolyProvider2Parser: ... switch row['recordtype']: case 'abc': phone.international += ( Decimal(row['canada cost']) + Decimal(row['eu cost']) + Decimal(row['mexico cost']) + Decimal(row['other intl cost']) ) case 'xyz': phone.text_messaging += int(row['textmessages']) ... default: raise WhatTheHeckIsThis() > # The one thing I'm sure I don't understand from the code is where the > original rectypes comes into the process. From the provider data -- sometimes CSV files, sometimes tab-delimited text files, sometimes MS Access MDB files, sometimes a web service...varies per-provider (and some providers have multiple formats, like Verizon has MyBIZ and IBAS; ATT has their WinCD and Premier; etc). No two formats are the same, so the logic needed to parse the data into our internal homogenized Phone data structure varies per each one. And the logic (or lack thereof) used by many providers in creating their formats require reverse-engineering most of them through trial-and-error, and huge ugly if/elif/else chains. > I wonder if you agree that it's bit cleaner now? It's an effective > solution. I'm making no representation that it's the best. It's clean if it were the solution to my problem -- however, the mess comes from the profusion of provider formats. > simple (and legible!) one liner. A provider "enhances" their format, > or a new provider format is added, code in one class, not in every > switch they might be involved in. But sorry, I don't mean to > patronise, I'm sure you know the spiel. Yes, having been programming since I was in middle-school (quick calculation yields a "boy I'm old" estimate of about 20 years...does anybody miss 360k 5.25" floppy disks? :) and have my degree in CS. So it's not my lack of programming skill/knowledge, but rather your misunderstanding of the problem-space. Not to patronize ;-) -tkc From ecir.hana at gmail.com Thu Dec 10 09:55:20 2009 From: ecir.hana at gmail.com (Ecir Hana) Date: Thu, 10 Dec 2009 06:55:20 -0800 (PST) Subject: Redirect stdout to a buffer [Errno 9] References: <7c067b92-8d37-45e1-8b2e-bb79daff6a4c@v30g2000yqm.googlegroups.com> <745efa54-d7d1-45de-a830-296e4e221e1f@m38g2000yqd.googlegroups.com> <32d3502c-f335-42a7-be1c-bb8ddf72d568@d10g2000yqh.googlegroups.com> Message-ID: I tried to replace official Python dll with the one built with MinGW and it works. The problem is, that port is very old and so far it seems that official support for building Python under MinGW is nowhere near. I really don't want to use MSVC, so if there's any other way around this, please, let me know. From invalid.emal at at.address Thu Dec 10 09:56:22 2009 From: invalid.emal at at.address (Joe) Date: Thu, 10 Dec 2009 08:56:22 -0600 Subject: no module named error In-Reply-To: <7o7jvbF3ojs9uU1@mid.uni-berlin.de> References: <7o78kuF3p45l7U1@mid.uni-berlin.de> <7o79huF3l4v9uU1@mid.uni-berlin.de> <7o7h4mF3o100mU1@mid.uni-berlin.de> <7o7jvbF3ojs9uU1@mid.uni-berlin.de> Message-ID: > No, the import-mechanism of python doesn't take LD_LIBRARY_PATH into > account, and even if it did - _moda.la is a simple archive-file, not a > shared library. It can't be dynamically loaded. Something in your > build-process is not working. So how should my stuff find these libs? Here's what I've recently learned ... So if I have the dir path of my c libs inside my exported LD_LIBRARY_PATH (which includes the following files), along w/ the dir to the *.la file ... _moda.a _moda.la -> ../_moda.la _moda.lai _moda.so -> _moda.so.2.0.1 _moda.so.2 -> _moda.so.2.0.1 _moda.so.2.0.1 _moda.so.2.0.1T _moda_la-moda_wrap.o I get the 'ImportError: No module named _moda' error as in previous post. But as I think your saying above, this should not work because LD_LIBRARY_PATH doesn't get used. I was at the python command line '>>>' and I did the following command. import sys sys.path.append('/home/me/my/c/libs/path/.libs') # this is the path to the above listed files, and then when I did ... import moda Everything worked just fine. But I'm not quite sure how to fix it in my script or env. From benjamin.kaplan at case.edu Thu Dec 10 10:09:43 2009 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Thu, 10 Dec 2009 10:09:43 -0500 Subject: no module named error In-Reply-To: References: <7o78kuF3p45l7U1@mid.uni-berlin.de> <7o79huF3l4v9uU1@mid.uni-berlin.de> <7o7h4mF3o100mU1@mid.uni-berlin.de> <7o7jvbF3ojs9uU1@mid.uni-berlin.de> Message-ID: On Thu, Dec 10, 2009 at 9:56 AM, Joe wrote: >> No, the import-mechanism of python doesn't take LD_LIBRARY_PATH into >> account, and even if it did - _moda.la is a simple archive-file, not a >> shared library. It can't be dynamically loaded. Something in your >> build-process is not working. > > So how should my stuff find these libs? > > Here's what I've recently learned ... > > So if I have the dir path of my c libs inside my exported > LD_LIBRARY_PATH (which includes the following files), ?along w/ the dir > to the *.la file ... > > _moda.a > _moda.la -> ../_moda.la > _moda.lai > _moda.so -> _moda.so.2.0.1 > _moda.so.2 -> _moda.so.2.0.1 > _moda.so.2.0.1 > _moda.so.2.0.1T > _moda_la-moda_wrap.o > > I get the 'ImportError: No module named _moda' error as in previous > post. But as I think your saying above, this should not work because > LD_LIBRARY_PATH doesn't get used. > > I was at the python command line '>>>' and I did the following command. > > import sys > sys.path.append('/home/me/my/c/libs/path/.libs') > # this is the path to the above listed files, and then when I did ... > > ? import moda > > Everything worked just fine. > > But I'm not quite sure how to fix it in my script or env. > -- > http://mail.python.org/mailman/listinfo/python-list > http://docs.python.org/library/sys.html """ sys.path A list of strings that specifies the search path for modules. Initialized from the environment variable PYTHONPATH, plus an installation-dependent default. As initialized upon program startup, the first item of this list, path[0], is the directory containing the script that was used to invoke the Python interpreter. If the script directory is not available (e.g. if the interpreter is invoked interactively or if the script is read from standard input), path[0] is the empty string, which directs Python to search modules in the current directory first. Notice that the script directory is inserted before the entries inserted as a result of PYTHONPATH. A program is free to modify this list for its own purposes. Changed in version 2.3: Unicode strings are no longer ignored. """ Python uses the PYTHONPATH variable to find modules/libraries, not LD_LIBRARY_PATH. From scream.ru at gmail.com Thu Dec 10 10:13:15 2009 From: scream.ru at gmail.com (scream.ru at gmail.com) Date: Thu, 10 Dec 2009 07:13:15 -0800 (PST) Subject: Runtime load python modules from memory Message-ID: Hello! Is it possible to load python module from memory? For example, I can read python .pyc file into memory, preprocess it ( decrypt :-) ), and then import it. Is it possible? From kiorky at cryptelium.net Thu Dec 10 10:25:34 2009 From: kiorky at cryptelium.net (kiorky) Date: Thu, 10 Dec 2009 16:25:34 +0100 Subject: ctypes / cygwin / django+geos Message-ID: <4B2112EE.4090702@cryptelium.net> I am encountering errors with ctypes and geos. The same configuration (geos-3.0 or geos-3.2) runs fine under classical unixes like freebsd, mac or linux but do not pass with cygwin with 'free' function not found. My configuration is 2.6.4 Release, and a little patch for ctypes which lets all its test pass (loading cygpythonxx.dll instead of libpython.dll): Testing package ctypes.test ('2.6.4 (r264:75706, Dec 6 2009, 16:44:34) \n[GCC 4.3.4 20090804 (release) 1]', 'cygwin', 'posix') ...................................................................................................................................................................................................................................................................................................................................... ---------------------------------------------------------------------- Ran 326 tests in 1.671s (0 modules skipped) Unavailable resources: printing, refcount Then, using it by hand with an helloword library makes no problem. However, using it in my real world UseCase [1], make me think that there is a problem with ctypes. Indeed, geos is compiled and its huge test coverage pass. But then, trying to use ctypes over geos do not work. $ cat geos.py from django.contrib.gis.tests import test_geos test_geos.run() $ /minitage/dependencies/python-2.6/parts/part/bin/python bin/djangopy geos.py Testing WKT output. ... ERROR Testing HEX output. ... ERROR Testing KML output. ... ERROR Testing the Error handlers. ... BEGIN - expecting GEOS_ERROR; safe to ignore. GEOS_ERROR: ParseException: Expected number but encountered ',' GEOS_ERROR: ParseException: Unknown WKB type 255 END - expecting GEOS_ERROR; safe to ignore. GEOS_ERROR: ParseException: Unexpected EOF parsing WKB ok Testing WKB output. ... ERROR Testing creation from HEX. ... ERROR Testing creation from WKB. ... ERROR Testing EWKT. ... ERROR Testing GeoJSON input/output (via GDAL). ... ok Testing equivalence. ... ERROR Testing Point objects. ... ERROR Testing MultiPoint objects. ... ERROR Testing LineString objects. ... ERROR Testing MultiLineString objects. ... ERROR Testing LinearRing objects. ... ERROR Testing Polygon objects. ... ERROR Testing MultiPolygon objects. ... BEGIN - expecting GEOS_NOTICE; safe to ignore. ERROR Testing Geometry __del__() on rings and polygons. ... ERROR Testing Coordinate Sequence objects. ... ok Testing relate() and relate_pattern(). ... ERROR Testing intersects() and intersection(). ... ok Testing union(). ... ok Testing difference(). ... ok Testing sym_difference(). ... ok Testing buffer(). ... ok Testing the SRID property and keyword. ... ERROR Testing the mutability of Polygons and Geometry Collections. ... ERROR Testing three-dimensional geometries. ... ok Testing the distance() function. ... ok Testing the length property. ... ok Testing empty geometries and collections. ... ERROR Testing `ogr` and `srs` properties. ... ok Testing use with the Python `copy` module. ... ok Testing `transform` method. ... ok Testing `extent` method. ... ok Testing pickling and unpickling support. ... ERROR ====================================================================== ERROR: Testing WKT output. ---------------------------------------------------------------------- Traceback (most recent call last): File "/cygdrive/e/minitage2/eggs/cache/Django-1.0.2_final_ZMinitagePatched_DjangoCchb-py2.6.egg/django/contrib/gis/tests/test_geos.py", line 28, in test01a_wkt self.assertEqual(g.ewkt, geom.wkt) File "/cygdrive/e/minitage2/eggs/cache/Django-1.0.2_final_ZMinitagePatched_DjangoCchb-py2.6.egg/django/contrib/gis/geos/base.py", line 378, in wkt return to_wkt(self.ptr) File "/cygdrive/e/minitage2/eggs/cache/Django-1.0.2_final_ZMinitagePatched_DjangoCchb-py2.6.egg/django/contrib/gis/geos/prototypes/errcheck.py", line 67, in check_string libc.free(result) File "/minitage/dependencies/python-2.6/parts/part/lib/python2.6/ctypes/__init__.py", line 366, in __getattr__ func = self.__getitem__(name) File "/minitage/dependencies/python-2.6/parts/part/lib/python2.6/ctypes/__init__.py", line 371, in __getitem__ func = self._FuncPtr((name_or_ordinal, self)) AttributeError: function 'free' not found (*?) -- Cordialement, KiOrKY GPG Key FingerPrint: 0x1A1194B7681112AF -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 262 bytes Desc: OpenPGP digital signature URL: From aahz at pythoncraft.com Thu Dec 10 10:27:05 2009 From: aahz at pythoncraft.com (Aahz) Date: 10 Dec 2009 07:27:05 -0800 Subject: Question on Python as career References: <614b8dde-324b-4d54-8e73-7a96e4c0b1cf@a21g2000yqc.googlegroups.com> Message-ID: In article , Tim Roberts wrote: > >There are very, very few full-time Python jobs anywhere in the world, >although many people use Python as one tool in their toolbox. Depending on how you define "Python job", I disagree with you. All my employment in the last decade, including three different full-time jobs at three different companies, has had Python as the primary job skill requirement and is what I spent more time working with than anything else. I don't think I'm particularly unusual. My company has been trying to hire a person with Python and Linux sysadmin experience for more than three months -- in the San Francisco Bay Area -- with little luck. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ The best way to get information on Usenet is not to ask a question, but to post the wrong information. From kiorky at cryptelium.net Thu Dec 10 10:30:25 2009 From: kiorky at cryptelium.net (kiorky) Date: Thu, 10 Dec 2009 16:30:25 +0100 Subject: ctypes / cygwin / django+geos In-Reply-To: <4B2112EE.4090702@cryptelium.net> References: <4B2112EE.4090702@cryptelium.net> Message-ID: <4B211411.7030303@cryptelium.net> Oups, i forgot to say that the tests i am excuting are from Django. (django.gis.tests.test_geos, tag 1.0.2) You can have it online here: http://code.djangoproject.com/browser/django/tags/releases/1.0.2/django/contrib/gis/tests/test_geos.py -- Cordialement, KiOrKY GPG Key FingerPrint: 0x1A1194B7681112AF -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 262 bytes Desc: OpenPGP digital signature URL: From kiorky at cryptelium.net Thu Dec 10 10:37:52 2009 From: kiorky at cryptelium.net (kiorky) Date: Thu, 10 Dec 2009 16:37:52 +0100 Subject: ctypes / cygwin / django+geos Message-ID: <4B2115D0.3040606@cryptelium.net> I am encountering errors with ctypes and geos. The same configuration (geos-3.0 or geos-3.2) runs fine under classical unixes like freebsd, mac or linux but do not pass with cygwin with 'free' function not found. My configuration is 2.6.4 Release, and a little patch for ctypes which lets all its test pass (loading cygpythonxx.dll instead of libpython.dll): Testing package ctypes.test ('2.6.4 (r264:75706, Dec 6 2009, 16:44:34) \n[GCC 4.3.4 20090804 (release) 1]', 'cygwin', 'posix') ...................................................................................................................................................................................................................................................................................................................................... ---------------------------------------------------------------------- Ran 326 tests in 1.671s (0 modules skipped) Unavailable resources: printing, refcount Then, using it by hand with an helloword library makes no problem. However, using it in my real world UseCase [1], make me think that there is a problem with ctypes. Indeed, geos is compiled and its huge test coverage pass. But then, trying to use ctypes over geos do not work. $ cat geos.py from django.contrib.gis.tests import test_geos test_geos.run() $ /minitage/dependencies/python-2.6/parts/part/bin/python bin/djangopy geos.py Testing WKT output. ... ERROR Testing HEX output. ... ERROR Testing KML output. ... ERROR Testing the Error handlers. ... BEGIN - expecting GEOS_ERROR; safe to ignore. GEOS_ERROR: ParseException: Expected number but encountered ',' GEOS_ERROR: ParseException: Unknown WKB type 255 END - expecting GEOS_ERROR; safe to ignore. GEOS_ERROR: ParseException: Unexpected EOF parsing WKB ok Testing WKB output. ... ERROR Testing creation from HEX. ... ERROR Testing creation from WKB. ... ERROR Testing EWKT. ... ERROR Testing GeoJSON input/output (via GDAL). ... ok Testing equivalence. ... ERROR Testing Point objects. ... ERROR Testing MultiPoint objects. ... ERROR Testing LineString objects. ... ERROR Testing MultiLineString objects. ... ERROR Testing LinearRing objects. ... ERROR Testing Polygon objects. ... ERROR Testing MultiPolygon objects. ... BEGIN - expecting GEOS_NOTICE; safe to ignore. ERROR Testing Geometry __del__() on rings and polygons. ... ERROR Testing Coordinate Sequence objects. ... ok Testing relate() and relate_pattern(). ... ERROR Testing intersects() and intersection(). ... ok Testing union(). ... ok Testing difference(). ... ok Testing sym_difference(). ... ok Testing buffer(). ... ok Testing the SRID property and keyword. ... ERROR Testing the mutability of Polygons and Geometry Collections. ... ERROR Testing three-dimensional geometries. ... ok Testing the distance() function. ... ok Testing the length property. ... ok Testing empty geometries and collections. ... ERROR Testing `ogr` and `srs` properties. ... ok Testing use with the Python `copy` module. ... ok Testing `transform` method. ... ok Testing `extent` method. ... ok Testing pickling and unpickling support. ... ERROR ====================================================================== ERROR: Testing WKT output. ---------------------------------------------------------------------- Traceback (most recent call last): File "/cygdrive/e/minitage2/eggs/cache/Django-1.0.2_final_ZMinitagePatched_DjangoCchb-py2.6.egg/django/contrib/gis/tests/test_geos.py", line 28, in test01a_wkt self.assertEqual(g.ewkt, geom.wkt) File "/cygdrive/e/minitage2/eggs/cache/Django-1.0.2_final_ZMinitagePatched_DjangoCchb-py2.6.egg/django/contrib/gis/geos/base.py", line 378, in wkt return to_wkt(self.ptr) File "/cygdrive/e/minitage2/eggs/cache/Django-1.0.2_final_ZMinitagePatched_DjangoCchb-py2.6.egg/django/contrib/gis/geos/prototypes/errcheck.py", line 67, in check_string libc.free(result) File "/minitage/dependencies/python-2.6/parts/part/lib/python2.6/ctypes/__init__.py", line 366, in __getattr__ func = self.__getitem__(name) File "/minitage/dependencies/python-2.6/parts/part/lib/python2.6/ctypes/__init__.py", line 371, in __getitem__ func = self._FuncPtr((name_or_ordinal, self)) AttributeError: function 'free' not found (*?) -- Cordialement, KiOrKY GPG Key FingerPrint: 0x1A1194B7681112AF -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 262 bytes Desc: OpenPGP digital signature URL: From deets at nospam.web.de Thu Dec 10 10:45:06 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 10 Dec 2009 16:45:06 +0100 Subject: no module named error References: <7o78kuF3p45l7U1@mid.uni-berlin.de> <7o79huF3l4v9uU1@mid.uni-berlin.de> <7o7h4mF3o100mU1@mid.uni-berlin.de> <7o7jvbF3ojs9uU1@mid.uni-berlin.de> Message-ID: <7ocjc2F3o5t6iU1@mid.uni-berlin.de> Joe wrote: >> No, the import-mechanism of python doesn't take LD_LIBRARY_PATH into >> account, and even if it did - _moda.la is a simple archive-file, not a >> shared library. It can't be dynamically loaded. Something in your >> build-process is not working. > > So how should my stuff find these libs? > > Here's what I've recently learned ... > > So if I have the dir path of my c libs inside my exported > LD_LIBRARY_PATH (which includes the following files), along w/ the dir > to the *.la file ... > > _moda.a > _moda.la -> ../_moda.la > _moda.lai > _moda.so -> _moda.so.2.0.1 > _moda.so.2 -> _moda.so.2.0.1 > _moda.so.2.0.1 > _moda.so.2.0.1T > _moda_la-moda_wrap.o > > I get the 'ImportError: No module named _moda' error as in previous > post. But as I think your saying above, this should not work because > LD_LIBRARY_PATH doesn't get used. > > I was at the python command line '>>>' and I did the following command. > > import sys > sys.path.append('/home/me/my/c/libs/path/.libs') > # this is the path to the above listed files, and then when I did ... > > import moda > > Everything worked just fine. > > But I'm not quite sure how to fix it in my script or env. Your installation process is botched (no idea why, you don't show us setup.py or anything else I asked for). All that is missing is what I've asked you now several times before: _moda.so is *NOT* alongside moda.py inside your python's site-packages directory. Copy it in there, and the import will work *without* any sys.path-hackery. Of course you shouldn't do this by hand every time you need to, but instead fix the whole package do to this when python setup.py install is invoked. Diez From ernst.karner at gmail.com Thu Dec 10 10:55:57 2009 From: ernst.karner at gmail.com (diego) Date: Thu, 10 Dec 2009 07:55:57 -0800 (PST) Subject: Connecting to Python COM server from Excel VBA does not work References: <740e0649-958a-4a7b-ac33-d26e5adb732d@b2g2000yqi.googlegroups.com> <4b20d30d$0$17502$ba4acef3@news.orange.fr> Message-ID: <40e274ca-6949-4207-9c2a-56a3e42a6630@s31g2000yqs.googlegroups.com> the problem was that i had never installed python on my workstation. just had a Python25 folder with a batch-file that was adjustin the PATH and executing %PYTHONHOME%python.exe installed Python properly and now everything works fine.... From bearophileHUGS at lycos.com Thu Dec 10 10:57:00 2009 From: bearophileHUGS at lycos.com (Bearophile) Date: Thu, 10 Dec 2009 07:57:00 -0800 (PST) Subject: Graph library for Python References: <4B1D35BC.5000002@egenix.com> <4B1D5CB3.8030805@egenix.com> <00a70ac5$0$15659$c3e8da3@news.astraweb.com> <4B1E464B.6090408@chamonix.reportlab.co.uk> Message-ID: Geremy Condra: > is there a particular way you want your attribution line to read? You can just use my nickname (in all lowercase), with the list of parts you have used. Don't worry. > Well, we all seem to have reinvented the wheel differently ;) Maybe also because they are designed for different purposes. > Bearophile, Tiago- any interest in trying to combine the > best parts of our libraries, with an eye towards eventual > integration into the standard library? The first thing to do is to ask Guido and Hettinger if they are willing to put a "good" graph module into the std lib. If their answer is positive for some definition of "good", then we can think about doing something. Several years ago I have suggested to put a graph module in the std lib, and the answer was something like: "Put the lib online, and if people use it a lot, we'll see to put it into the std lib." In the meantime my lib was used by no one and ten other graph libs are used (networkx seems among the most used), but I think no one of them has shown a strong usage. (In the meantime Hettinger has written and added two or three or four GOOD data structures to the std lib using a "fast lane", avoiding the step of popular usage test). Bye, bearophile From apt.shansen at gmail.com Thu Dec 10 11:16:15 2009 From: apt.shansen at gmail.com (Stephen Hansen) Date: Thu, 10 Dec 2009 08:16:15 -0800 Subject: How do I Block Events in wxPython In-Reply-To: References: <6854a0bb-9edc-4392-9761-d2f3cf98f89e@k4g2000yqb.googlegroups.com> <7a9c25c20912092357i7fb0e327gf88919a85fdf3482@mail.gmail.com> Message-ID: <7a9c25c20912100816y59e023e3kb35a87aa10c80913@mail.gmail.com> On Thu, Dec 10, 2009 at 6:01 AM, Frank Millman wrote: > > Another approach is to use wnd.CaptureMouse() on a particular control > > which > > doesn't really respond to anything. Just be sure to ReleaseMouse() later > > and > > follow the instructions in the docs about capturing that cancel-capture > > event. > > > > I like this. Unfortunately it does not block keyboard input. However, I > have > a keyboard event handler on virtually all my controls, so it should be easy > to set a flag and tell it to ignore keystrokes while in a 'blocked' state. > Hm, that's a point. Well if you have a legitimate case for pre-empting the event loop with these periodic regular short blocking moments (it seems you may), I think what you want to do is overwrite FilterEvent on your App object. You can then make that flag something you set on the app, and while it's true, returning False (or True, I really don't know the differenced between telling wx 'Ok, I processed this event you can ignore it' and 'Ok, I'm not going to process this event and neither should you'). Otherwise, return -1. --S > > HTH, > > It certainly does - thanks. > > Frank > > > > -- > http://mail.python.org/mailman/listinfo/python-list > --S -------------- next part -------------- An HTML attachment was scrubbed... URL: From invalid at invalid.invalid Thu Dec 10 12:28:42 2009 From: invalid at invalid.invalid (Grant Edwards) Date: Thu, 10 Dec 2009 17:28:42 +0000 (UTC) Subject: Immediate Help with python program! References: <1be06077-3173-41ca-a679-8d723eaff0c8@9g2000yqa.googlegroups.com> Message-ID: On 2009-12-10, Rhodri James wrote: > Ahem. This is a newsgroup/mailing list, not IM. I happen to have seen > this within half an hour of you posting it, but that's just luck. > Expecting an "immediate" response is unrealistic. > > Furthermore, this is comp.lang.python, a group right up there in pedantry > terms with cam.misc. Wandering in and demanding "immediate" help is just > begging for half a dozen replies that give you detailed and mind-boggling > versions of exactly what you asked for, especially if it's got nothing to > do with the answer you actually need. An exclamation point in a subject line also tends to act as an excellent lighting rod... -- Grant Edwards grante Yow! Gibble, Gobble, we at ACCEPT YOU ... visi.com From ethan at stoneleaf.us Thu Dec 10 12:52:41 2009 From: ethan at stoneleaf.us (Ethan Furman) Date: Thu, 10 Dec 2009 09:52:41 -0800 Subject: switch In-Reply-To: <67b225de-8fc3-415a-819a-61370fecff47@a10g2000pre.googlegroups.com> References: <335204.99872.qm@web57905.mail.re3.yahoo.com> <68e6e315-f3c7-4e52-a56f-802e99d75e6a@y32g2000prd.googlegroups.com> <46ec89b7-6a5c-4710-af30-04fe549f7470@u25g2000prh.googlegroups.com> <40c4aae1-1f90-4d50-9d68-8d15cae0457b@k4g2000yqb.googlegroups.com> <67b225de-8fc3-415a-819a-61370fecff47@a10g2000pre.googlegroups.com> Message-ID: <4B213569.8040300@stoneleaf.us> Asun Friere wrote: > On Dec 10, 2:00 pm, Carl Banks wrote: > >>On Dec 9, 5:02 pm, Asun Friere wrote: >> >> >>>On Dec 9, 7:08 pm, Carl Banks wrote: >> >>>>What if the object is a string you just read from a file? >> >>>>How do you dispatch using polymorphism in that case? >> >>>This would be a pertinent question, were I advocating that _all_ >>>switch statements should, or even can, be replaced with "dispatch >>>using polymorphism." >> >>Then why did you claim that a decent OO should never have a switch >>statement then? >>You argued that a decent language OO should never >>have a switch statement because polymorphic dispatch is the right way >>to handle it in OO languages, which implies that polymorphism can and >>should take the place of any switch statement. > > That is a misreading. I wrote... [snip] You wrote, and I quote, "For which reason python has no 'case' statement and why *no decent OO language should* ." [emphasis added] Just to be clear. ~Ethan~ From vinay_sajip at yahoo.co.uk Thu Dec 10 13:03:32 2009 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Thu, 10 Dec 2009 10:03:32 -0800 (PST) Subject: Moving from Python 2 to Python 3: A 4 page "cheat sheet" References: <291d64cb-cc5c-4109-822c-84d58ed7b18b@k17g2000yqh.googlegroups.com> <19194586-cd6a-4d13-ae1c-798884194672@n35g2000yqm.googlegroups.com> <4d82209c-1a43-405e-8ba7-49b7d7985335@n35g2000yqm.googlegroups.com> Message-ID: On Dec 3, 12:12?am, Terry Reedy wrote: > At the moment (3.1) there are, unfortunately, library packages that > require % for formatting (logging, I believe, for one). There has been > discussion on adding a new option for 3.2, but I do not know what will > happen. Depends on whether you want to be absolutely complete. I > strictly use .format when I can, which so far is always. Logging uses %-style formatting because that was all that was available at the time it was written. A frequent complaint from some quarters is about the overhead of logging, and so I'm not sure it's a good idea to switch over from %-formatting to str.format just for the sake of it, unless a way can be found which avoids the problems of lower performance and backwards compatibility (e.g. a foolproof %- string to {} converter, which I've had a stab at, but which cannot be achieved without changes to the {} code, e.g. to allow old-style octal constants). As far as logging is concerned I'll be periodically looking to see if moving over to the new format without performance/ backwards compatibility compromises is feasible, and when it is I'll adopt the new format. For now, AFAIK, people who are determined to use the {}-format can do so by subclassing logging.Formatter and by passing in message classes which convert format-string and args to final message. It's a one-time cost they'd incur (to write the relevant subclasses) which could be used on multiple projects. Regards, Vinay Sajip From nobody at nowhere.com Thu Dec 10 13:16:44 2009 From: nobody at nowhere.com (Nobody) Date: Thu, 10 Dec 2009 18:16:44 +0000 Subject: switch References: <335204.99872.qm@web57905.mail.re3.yahoo.com> Message-ID: On Thu, 10 Dec 2009 05:47:19 +0000, Steven D'Aprano wrote: >>> I string together a bunch of elif statements to simulate a switch >>> >>> if foo == True: >>> blah >>> elif bar == True: >>> blah blah >>> elif bar == False: >>> blarg >>> elif .... >> >> This isn't what would normally be considered a switch (i.e. what C >> considers a switch). > > Anyone would think that C was the only programming language in > existence... It's the only one I know of which calls such statements "switch" statements. Most other languages call them "case" statements. >> A switch tests the value of an expression against a >> set of constants. > > In C. Things may be different in other languages. > > For example, I recall the so-called "4GL" (remember when that was the > marketing term of choice for interpreted programming languages?) > Hyperscript from Informix. I can't check the exact syntax right now, but > it had a switch statement which allowed you to do either C-like tests > against a single expression, or if-like multiple independent tests. Interpreted languages generally don't care about the labels being constant, so you can do e.g. (BBC BASIC V): CASE TRUE OF WHEN foo: blah WHEN bar: blah blah WHEN NOT(bar): blarg ENDCASE The test expression is compared against each case expression sequentially until one matches; both the test expression and case expressions are evaluated at run-time. This is essentially just an if/elif chain with different syntax, whereas a C-style switch may be signficiantly more efficient (e.g. using a jump table or a balanced tree). >> Compiled languages' switch statements typically require constant labels >> as this enables various optimisations. > > Pascal, for example, can test against either single values, enumerated > values, or a range of values: > > case n of > 0: > writeln('zero'); > 1, 2: > writeln('one or two'); > 3...10: > writeln('something between three and ten'); > else writeln('something different'); > end; IOW, identical semantics to C, but with some extra syntax to avoid the need to write multiple consecutive labels. From python at mrabarnett.plus.com Thu Dec 10 13:24:28 2009 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 10 Dec 2009 18:24:28 +0000 Subject: switch In-Reply-To: References: <335204.99872.qm@web57905.mail.re3.yahoo.com> Message-ID: <4B213CDC.7060008@mrabarnett.plus.com> Steven D'Aprano wrote: > On Wed, 09 Dec 2009 18:50:29 +0000, Nobody wrote: > >> On Tue, 08 Dec 2009 21:02:44 -0800, Kee Nethery wrote: >> >>> I string together a bunch of elif statements to simulate a switch >>> >>> if foo == True: >>> blah >>> elif bar == True: >>> blah blah >>> elif bar == False: >>> blarg >>> elif .... >> This isn't what would normally be considered a switch (i.e. what C >> considers a switch). > > Anyone would think that C was the only programming language in > existence... > > >> A switch tests the value of an expression against a >> set of constants. > > In C. Things may be different in other languages. > > For example, I recall the so-called "4GL" (remember when that was the > marketing term of choice for interpreted programming languages?) > Hyperscript from Informix. I can't check the exact syntax right now, but > it had a switch statement which allowed you to do either C-like tests > against a single expression, or if-like multiple independent tests. > > Moving away from obsolete languages, we have Ruby which does much the > same thing: if you provide a test value, the case expression does a C- > like test against that expression, and if you don't, it does if-like > multiple tests. > > http://www.skorks.com/2009/08/how-a-ruby-case-statement-works-and-what- > you-can-do-with-it/ > > > >> If you were writing the above in C, you would need to >> use a chain of if/else statements; you couldn't use a switch. >> >> Compiled languages' switch statements typically require constant labels >> as this enables various optimisations. > > Pascal, for example, can test against either single values, enumerated > values, or a range of values: > > case n of > 0: > writeln('zero'); > 1, 2: > writeln('one or two'); > 3...10: > writeln('something between three and ten'); > else writeln('something different'); > end; > Originally the 'case' statement in Pascal didn't support ranges or a default; they started as non-standard extensions in some implementations. Originally, if none of the values matched then that was a runtime error. From info at wingware.com Thu Dec 10 13:42:19 2009 From: info at wingware.com (Wingware) Date: Thu, 10 Dec 2009 13:42:19 -0500 Subject: ANN: Wing IDE 3.2.3 released Message-ID: <4B21410B.8030108@wingware.com> Hi, Wingware has released version 3.2.3 of Wing IDE, our integrated development environment for the Python programming language. Wing IDE can be used on Windows, Linux, and OS X to develop Python code for web, GUI, and embedded scripting applications. Wing IDE provides auto-completion, call tips, a powerful debugger, unit testing, version control, search, and many other features. This release introduces the following minor features and improvements: * Show return value types in Source Assistant * Add preference to control folding of trailing white space * Add preference to use ## style comments in comment-out feature * Show number of search and replace matches * Added documentation for using Wing with Autodesk Maya * Correct analysis of Python 3.x builtins * Fix tutorial to work under Python 3.x as well * Turn off mixed indent tab size forcing until time of read or save * Fix issues with debugger API used for embedded debugging * Several other minor features and bug fixes. See the change log for details: http://wingware.com/pub/wingide/3.2.3/CHANGELOG.txt *Wing 3.2 Highlights* Versions 3.2.x of Wing IDE include the following new features not present in Wing IDE 3.1: * Support for Python 3.0 and 3.1 * Rewritten version control integration with support for Subversion, CVS, Bazaar, git, Mercurial, and Perforce (*) * Added 64-bit Debian, RPM, and tar file installers for Linux * File management in Project view (**) * Auto-completion in the editor obtains completion data from live runtime when the debugger is active (**) * Perspectives: Create and save named GUI layouts and optionally automatically transition when debugging is started (*) * Improved support for Cython and Pyrex (*.pyx files) * Added key binding documentation to the manual * Added Restart Debugging item in Debug menu and tool bar (**) * Improved OS Commands and Bookmarks tools (*) * Support for debugging 64-bit Python on OS X (*)'d items are available in Wing IDE Professional only. (**)'d items are available in Wing IDE Personal and Professional only. The release also contains many other minor features and bug fixes; see the change log for details: http://wingware.com/pub/wingide/3.2.3/CHANGELOG.txt *Downloads* Wing IDE Professional and Wing IDE Personal are commercial software and require a license to run. A free trial license can be obtained directly from the product when launched. Wing IDE 101 can be used free of charge. Wing IDE Pro 3.2.3 http://wingware.com/downloads/wingide/3.2 Wing IDE Personal 3.2.3 http://wingware.com/downloads/wingide-personal/3.2 Wing IDE 101 3.2.3 http://wingware.com/downloads/wingide-101/3.2 *About Wing IDE* Wing IDE is an integrated development environment designed specifically for the Python programming language. It provides powerful debugging, editing, code intelligence, testing, version control, and search capabilities. These features reduce development and debugging time, cut down on coding errors, and make it easier to understand and navigate Python code. Wing IDE is available in three product levels: Wing IDE Professional is the full-featured Python IDE, Wing IDE Personal offers a reduced feature set at a low price, and Wing IDE 101 is a free simplified version designed for teaching entry level programming courses with Python. 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). Wing IDE 3.2 supports Python versions 2.0.x through 3.1.x. For more product information see http://wingware.com/products *Purchasing and Upgrading* Wing 3.2 is a free upgrade for all Wing IDE 3.0 and 3.1 users. Any 2.x license sold after May 2nd 2006 is free to upgrade; others cost 1/2 the normal price to upgrade. Upgrade a 2.x license: https://wingware.com/store/upgrade Purchase a 3.x license: https://wingware.com/store/purchase -- The Wingware Team Wingware | Python IDE Advancing Software Development www.wingware.com From dbd at ieee.org Thu Dec 10 13:46:17 2009 From: dbd at ieee.org (dbd) Date: Thu, 10 Dec 2009 10:46:17 -0800 (PST) Subject: Float precision and float equality References: <2f0dee67-6fda-47c0-8266-d2d6b02ed655@e4g2000prn.googlegroups.com> <574bd33c-a38b-4af5-802e-fc081965a230@g23g2000vbr.googlegroups.com> <6624fc07-c6d5-40e1-a899-6eb73603a980@u8g2000prd.googlegroups.com> <335cb11d-e862-4daa-aec6-8f96b56bc28a@u1g2000pre.googlegroups.com> <79c41269-2b84-4fb1-8694-c7212f92be62@d9g2000prh.googlegroups.com> <49d04d6f-551b-46a9-8a11-7abe308a0154@f10g2000vbl.googlegroups.com> <8477d937-f44a-4e78-aa35-d97cb1ab5c06@f20g2000prn.googlegroups.com> <81fcae23-ed2c-4a48-b9d5-dae1002df848@z35g2000prh.googlegroups.com> Message-ID: On Dec 7, 12:58?pm, Carl Banks wrote: > On Dec 7, 10:53?am, dbd wrote: > > ... > > You're talking about machine epsilon? ?I think everyone else here is > talking about a number that is small relative to the expected smallest > scale of the calculation. > > Carl Banks When you implement an algorithm supporting floats (per the OP's post), the expected scale of calculation is the range of floating point numbers. For floating point numbers the intrinsic truncation error is proportional to the value represented over the normalized range of the floating point representation. At absolute values smaller than the normalized range, the truncation has a fixed value. These are not necessarily 'machine' characteristics but the characteristics of the floating point format implemented. A useful description of floating point issues can be found: http://dlc.sun.com/pdf/800-7895/800-7895.pdf Dale B. Dalrymple From invalid.emal at at.address Thu Dec 10 13:48:06 2009 From: invalid.emal at at.address (Joe) Date: Thu, 10 Dec 2009 12:48:06 -0600 Subject: no module named error In-Reply-To: <7ocjc2F3o5t6iU1@mid.uni-berlin.de> References: <7o78kuF3p45l7U1@mid.uni-berlin.de> <7o79huF3l4v9uU1@mid.uni-berlin.de> <7o7h4mF3o100mU1@mid.uni-berlin.de> <7o7jvbF3ojs9uU1@mid.uni-berlin.de> <7ocjc2F3o5t6iU1@mid.uni-berlin.de> Message-ID: > Your installation process is botched (no idea why, you don't show us > setup.py or anything else I asked for). Sorry, but I do know how it's currently installed is exactly the way I need it to be installed. > > > All that is missing is what I've asked you now several times before: > _moda.so is *NOT* alongside moda.py inside your python's site-packages > directory. Copy it in there, and the import will work *without* any > sys.path-hackery. Yeah, that's something I don't want to do. But you've given me enough info to help me understand what's going on and how to fix it. Thanks. From james at agentultra.com Thu Dec 10 14:04:52 2009 From: james at agentultra.com (J Kenneth King) Date: Thu, 10 Dec 2009 14:04:52 -0500 Subject: Perl to Python conversion References: <87zl5rnayz.fsf@crunchbang.Belkin> Message-ID: <85pr6modkb.fsf@agentultra.com> martin.schoon at gmail.com (Martin Sch??n) writes: > First off: I am new here and this is my first post after > lurking for quite some time. Hi. > Second off: I don't know much Python---yet. It's not a very big language. If you have experience programming in other languages, you can probably pick it up in a day or two. > Problem: I have come across a small open source application > that I find quite useful. It does have one major flaw though. > Its output is in imperial units. Converting isn't a big deal > for occasional use but if I start to use this stuff on a > regular basis... > > So I down-loaded the source code and found this thing is written > in Perl. > > Should I learn enough Perl to add the conversion? Probably > but this may be a nice excuse to get my Python education > going and if I do I might as well re-do the user interface. Well you can always call it from Python via subprocess (which basically wraps a shell and has fancy ways putting data in and extracting data out). > If I do re-write this thing in Python I might need to learn both > Perl and Python... You'll need to know one of them rather well and enough of the other to get by. It's probably easier to know more Perl than Python since Perl is a lot more expressive than Python (in the TMTOWTDI sense). Frankly I learned Perl before Python and find it rather easy to go between the two. YMMV. > Hence, are there any Perl to Python converters? So far I > have only found bridgekeeper which really is (was?) consultancy. > Apart from that I only find people recommending a manual re-write. It depends where the two languages vary from one another. If the script your translating uses basic types or even simple classes and typical control structures and operations then translating from one to the other is a simple matter of copy-pasting the code and translating the syntax and small bits of grammar. However, in areas where there are high variations; you'll probably want to stay away from it. Perl has a lot of freedom to manipulate references and the programmer can modify the language to suit their needs. So just be careful of code that uses these features as they are difficult to translate into Python. > Any thoughts/recommendations? Depends: - If you needed it done yesterday to get some work done, wrap the Perl script in a subprocess and buy yourself some time to think it over. - If your purpose is to learn Python, then start from scratch. Use the Perl as a guide if there are any maths or algorithms you are unsure about. - If you're just hacking around to learn stuff, learn a little of both. It will make you smarter if it doesn't confuse the heck out of you and make you quit before you finish. ;) > > TIA, > > /Martin HTH From benjamin at python.org Thu Dec 10 14:26:43 2009 From: benjamin at python.org (Benjamin Peterson) Date: Thu, 10 Dec 2009 19:26:43 +0000 (UTC) Subject: C to Python References: <89c38c820912100301r7c31b434k466b8a6f4d394ae5@mail.gmail.com> Message-ID: Emeka gmail.com> writes: > > > Hello All, > ? > I am finding it difficult getting my head around PyObject_CallObject(x,y). I need a gentle and thorough introduction to it. I also need examples. Could someone come to my need? PyObject_CallFunction is probably easier to use. http://docs.python.org/c-api/object.html#PyObject_CallObject From lie.1296 at gmail.com Thu Dec 10 14:55:25 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Fri, 11 Dec 2009 06:55:25 +1100 Subject: plain text parsing to html (newbie problem) In-Reply-To: <0f2e4a9a-284e-425f-9f02-045f32268d16@n35g2000yqm.googlegroups.com> References: <6664c88b-ec93-4b6c-a536-8a6b5959cd5e@a21g2000yqc.googlegroups.com> <35a19377-d2d4-4fb1-ad58-b999e0b9ff8f@u16g2000pru.googlegroups.com> <0f2e4a9a-284e-425f-9f02-045f32268d16@n35g2000yqm.googlegroups.com> Message-ID: <4b2152b7$1@dnews.tpgi.com.au> On 12/10/2009 11:17 PM, Jo?o wrote: > Thanks for the output. > akean, I've installed ipython and I'm exploring it. Thanks. > > Terry, > from what I've read stringIO allows us to store strings in a 'virtual' > file. > Can you please write just 2 lines exemplifying a write to and a read > from an OS level file? > > MRAB, that 'mail' object should've been the os level 'mail' file. But > as I'm a beginner I was using it wrong.. it's actually easier to use real files than creating a virtual file: f = open('mail.txt', 'w') f.write("foo\n") # or print >> f, "foo" and, is there any reason why you're not using the email and smtplib? http://docs.python.org/library/email-examples.html From martin.schoon at gmail.com Thu Dec 10 15:06:14 2009 From: martin.schoon at gmail.com (Martin =?utf-8?B?U2Now7bDtm4=?=) Date: Thu, 10 Dec 2009 21:06:14 +0100 Subject: Perl to Python conversion References: <87zl5rnayz.fsf@crunchbang.Belkin> <85pr6modkb.fsf@agentultra.com> Message-ID: <873a3imw5l.fsf@crunchbang.Belkin> Thanks all, great response! A little more background: I am not a programmer but I have done some programming in the past. This was all humble number crunching as part of my PhD project using FORTRAN. I also did some Rocky Mountain Basic coding for programs manipulating measurement instruments. And I did a minute amount of Turbo Pascal code, too little and too many years ago to count. Since then I have done some stuff in Matlab and (very basic) UNIX scripts. Does HTML, css and LaTeX count? So why Python? Well, I thought it would be fun to learn a little about GUI programming and a friend who is a real programmer recommended Python + PyQt. I have bought some books and lurked here for about a year but haven't managed to get going yet. I figured I needed some kind of project for that and now I have two. Learning Python and PyQt is spare time killer/brain teaser activity. The thermal contact conductance stuff is something that come in handy at work. So here is what I plan to do based on your kind advice and some thinking of my own. 1) I fix the unit thing by adding a conversion to the results presentation routine. 2) Recreating the functionality of the program in Python and PyQt will be a 'long term' educational project at home. There are various bits and pieces there: data base handling, GUI design, math, logic, error/exception handling... We have long, dark winters where I live :-) All the best, /Martin From lie.1296 at gmail.com Thu Dec 10 16:02:53 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Fri, 11 Dec 2009 08:02:53 +1100 Subject: accessing local variables from the pdb debugger In-Reply-To: References: <7oc9u8F3onimoU1@mid.uni-berlin.de> Message-ID: <4b216287$1@dnews.tpgi.com.au> On 12/11/2009 12:37 AM, Jean-Michel Pichavant wrote: > Diez B. Roggisch wrote: > By just inserting the print foo statement right after changing foo's > value, I've rolled back the value to 'foo' ??? A hell of a wtf pdb > feature ! Apparently it's fixed in 2.7 and 3.1 D:\Lie Ryan\Desktop>python27 d.py > d:\lie ryan\desktop\d.py(6)test() -> print(foo) (Pdb) foo = "bar" (Pdb) pp foo 'bar' (Pdb) c bar D:\Lie Ryan\Desktop>python27 d.py > d:\lie ryan\desktop\d.py(6)test() -> print(foo) (Pdb) foo = "bar" (Pdb) c bar From martin at v.loewis.de Thu Dec 10 16:17:55 2009 From: martin at v.loewis.de (Martin v. Loewis) Date: Thu, 10 Dec 2009 22:17:55 +0100 Subject: freeze in python3 In-Reply-To: References: Message-ID: > For example, initerrno should now be PyInit_errno. Am I missing something? No; freeze hasn't been ported to Python 3 yet. Contributions are welcome. Regards, Martin From pavlovevidence at gmail.com Thu Dec 10 17:23:06 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 10 Dec 2009 14:23:06 -0800 (PST) Subject: Float precision and float equality References: <574bd33c-a38b-4af5-802e-fc081965a230@g23g2000vbr.googlegroups.com> <6624fc07-c6d5-40e1-a899-6eb73603a980@u8g2000prd.googlegroups.com> <335cb11d-e862-4daa-aec6-8f96b56bc28a@u1g2000pre.googlegroups.com> <79c41269-2b84-4fb1-8694-c7212f92be62@d9g2000prh.googlegroups.com> <49d04d6f-551b-46a9-8a11-7abe308a0154@f10g2000vbl.googlegroups.com> <8477d937-f44a-4e78-aa35-d97cb1ab5c06@f20g2000prn.googlegroups.com> <81fcae23-ed2c-4a48-b9d5-dae1002df848@z35g2000prh.googlegroups.com> Message-ID: <1aece245-2ea8-4e9a-91c1-839fca73e720@g4g2000pri.googlegroups.com> On Dec 10, 10:46?am, dbd wrote: > On Dec 7, 12:58?pm, Carl Banks wrote: > > > On Dec 7, 10:53?am, dbd wrote: > > > ... > > > You're talking about machine epsilon? ?I think everyone else here is > > talking about a number that is small relative to the expected smallest > > scale of the calculation. > > > Carl Banks > > When you implement an algorithm supporting floats (per the OP's post), > the expected scale of calculation is the range of floating point > numbers. For floating point numbers the intrinsic truncation error is > proportional to the value represented over the normalized range of the > floating point representation. At absolute values smaller than the > normalized range, the truncation has a fixed value. These are not > necessarily 'machine' characteristics but the characteristics of the > floating point format implemented. I know, and it's irrelevant, because no one, I don't think, is talking about magnitude-specific truncation value either, nor about any other tomfoolery with the floating point's least significant bits. > A useful description of floating point issues can be found: [snip] I'm not reading it because I believe I grasp the situation just fine. But you are welcome to convince me otherwise. Here's how: Say I have two numbers, a and b. They are expected to be in the range (-1000,1000). As far as I'm concerned, if they differ by less than 0.1, they might as well be equal. Therefore my test for "equality" is: abs(a-b) < 0.08 Can you give me a case where this test fails? If a and b are too far out of their expected range, all bets are off, but feel free to consider arbitrary values of a and b for extra credit. Carl Banks From gervaz at gmail.com Thu Dec 10 17:42:35 2009 From: gervaz at gmail.com (mattia) Date: 10 Dec 2009 22:42:35 GMT Subject: KeyboardInterrupt References: <4b203886$0$34595$4fafbaef@reader1.news.tin.it> <0a336844-ac41-4d80-9310-4e1f63701eb6@u7g2000yqm.googlegroups.com> <4b2040f9$0$34595$4fafbaef@reader1.news.tin.it> <5c%Tm.61315$We2.28453@newsfe09.iad> Message-ID: <4b21795b$0$30961$4fafbaef@reader3.news.tin.it> Il Thu, 10 Dec 2009 04:56:33 +0000, Brad Harms ha scritto: > On Thu, 10 Dec 2009 00:29:45 +0000, mattia wrote: > >> Il Wed, 09 Dec 2009 16:19:24 -0800, Jon Clements ha scritto: >> >>> On Dec 9, 11:53?pm, mattia wrote: >>>> Hi all, can you provide me a simple code snippet to interrupt the >>>> execution of my program catching the KeyboardInterrupt signal? >>>> >>>> Thanks, >>>> Mattia >>> >>> Errr, normally you can just catch the KeyboardInterrupt exception -- >>> is that what you mean? >>> >>> Jon. >> >> Ouch, so the simplest solution is just insert in the 'main' function a >> try/catch? I believed there was the necessity to create a signal and >> than attach the KeyboardInterrupt to it... > > > KeyboardInterrupt is just an exception that gets raised when CTLR+C (or > the OS's equivalent keyboard combo) gets pressed. It can occur at any > point in a script since you never know when the user will press it, > which is why you put the try: except KeyboardInterrupt: around as much > of your script as possible. The signal that the OS sends to the Python > interpreter is irrelevant. Ok, so can you tell me why this simple script doesn't work (i.e. I'm not able to catch the keyboard interrupt)? import time import sys from threading import Thread def do_work(): for _ in range(1000): try: time.sleep(1) print(".", end="") sys.stdout.flush() except KeyboardInterrupt: sys.exit() def go(): threads = [Thread(target=do_work, args=()) for _ in range(2)] for t in threads: t.start() for t in threads: t.join() go() From daniel at stutzbachenterprises.com Thu Dec 10 18:08:40 2009 From: daniel at stutzbachenterprises.com (Daniel Stutzbach) Date: Thu, 10 Dec 2009 17:08:40 -0600 Subject: KeyboardInterrupt In-Reply-To: <4b21795b$0$30961$4fafbaef@reader3.news.tin.it> References: <4b203886$0$34595$4fafbaef@reader1.news.tin.it> <0a336844-ac41-4d80-9310-4e1f63701eb6@u7g2000yqm.googlegroups.com> <4b2040f9$0$34595$4fafbaef@reader1.news.tin.it> <5c%Tm.61315$We2.28453@newsfe09.iad> <4b21795b$0$30961$4fafbaef@reader3.news.tin.it> Message-ID: On Thu, Dec 10, 2009 at 4:42 PM, mattia wrote: > def go(): > threads = [Thread(target=do_work, args=()) for _ in range(2)] > for t in threads: > t.start() > for t in threads: > t.join() > The KeyboardInterrupt goes to the main thread, which is sitting there in t.join() with no exception handler around it. -- Daniel Stutzbach, Ph.D. President, Stutzbach Enterprises, LLC -------------- next part -------------- An HTML attachment was scrubbed... URL: From fonnesbeck at gmail.com Thu Dec 10 18:09:06 2009 From: fonnesbeck at gmail.com (hardcoreUFO) Date: Thu, 10 Dec 2009 15:09:06 -0800 (PST) Subject: umath import error for Numpy builds on OSX 10.6 Message-ID: <6b6c00c1-edb8-4469-ab3c-af886aee841f@v15g2000prn.googlegroups.com> For the past several weeks, I have been unable to build numpy from source, at least nothing that works. The issue is that symbols appear to be missing from umath. When numpy is imported, I get the following: In [1]: import numpy ------------------------------------------------------------ Traceback (most recent call last): File "", line 1, in File "/Library/Python/2.6/site-packages/numpy-1.5.0.dev_20091211- py2.6-macosx-10.6-universal.egg/numpy/__init__.py", line 132, in import add_newdocs File "/Library/Python/2.6/site-packages/numpy-1.5.0.dev_20091211- py2.6-macosx-10.6-universal.egg/numpy/add_newdocs.py", line 9, in from numpy.lib import add_newdoc File "/Library/Python/2.6/site-packages/numpy-1.5.0.dev_20091211- py2.6-macosx-10.6-universal.egg/numpy/lib/__init__.py", line 4, in from type_check import * File "/Library/Python/2.6/site-packages/numpy-1.5.0.dev_20091211- py2.6-macosx-10.6-universal.egg/numpy/lib/type_check.py", line 8, in import numpy.core.numeric as _nx File "/Library/Python/2.6/site-packages/numpy-1.5.0.dev_20091211- py2.6-macosx-10.6-universal.egg/numpy/core/__init__.py", line 6, in import umath ImportError: dlopen(/Library/Python/2.6/site-packages/ numpy-1.5.0.dev_20091211-py2.6-macosx-10.6-universal.egg/numpy/core/ umath.so, 2): Symbol not found: _npy_cexp Referenced from: /Library/Python/2.6/site-packages/ numpy-1.5.0.dev_20091211-py2.6-macosx-10.6-universal.egg/numpy/core/ umath.so Expected in: flat namespace in /Library/Python/2.6/site-packages/numpy-1.5.0.dev_20091211-py2.6- macosx-10.6-universal.egg/numpy/core/umath.so I think my build script is good, but here it is just incase: #!/bin/sh export MACOSX_DEPLOYMENT_TARGET=10.6 export CFLAGS="-arch x86_64" #export FFLAGS="-arch i386 -arch x86_64" export FFLAGS="-arch x86_64" export LDFLAGS="-Wall -lgfortran -undefined dynamic_lookup -bundle - arch x86_64" rm -rf build python setup.py config -L/Users/fonnesbeck/Code/freetype -L/Users/ fonnesbeck/Code/libpng build python setupegg.py egg_info --tag-date bdist_egg I'm at my wits end with this one, so any help at all is most appreciated. From mrabarnett at mrabarnett.plus.com Thu Dec 10 18:10:02 2009 From: mrabarnett at mrabarnett.plus.com (Matthew Barnett) Date: Thu, 10 Dec 2009 23:10:02 +0000 Subject: KeyboardInterrupt In-Reply-To: <4b21795b$0$30961$4fafbaef@reader3.news.tin.it> References: <4b203886$0$34595$4fafbaef@reader1.news.tin.it> <0a336844-ac41-4d80-9310-4e1f63701eb6@u7g2000yqm.googlegroups.com> <4b2040f9$0$34595$4fafbaef@reader1.news.tin.it> <5c%Tm.61315$We2.28453@newsfe09.iad> <4b21795b$0$30961$4fafbaef@reader3.news.tin.it> Message-ID: <4B217FCA.3030606@mrabarnett.plus.com> mattia wrote: > Il Thu, 10 Dec 2009 04:56:33 +0000, Brad Harms ha scritto: > >> On Thu, 10 Dec 2009 00:29:45 +0000, mattia wrote: >> >>> Il Wed, 09 Dec 2009 16:19:24 -0800, Jon Clements ha scritto: >>> >>>> On Dec 9, 11:53 pm, mattia wrote: >>>>> Hi all, can you provide me a simple code snippet to interrupt the >>>>> execution of my program catching the KeyboardInterrupt signal? >>>>> >>>>> Thanks, >>>>> Mattia >>>> Errr, normally you can just catch the KeyboardInterrupt exception -- >>>> is that what you mean? >>>> >>>> Jon. >>> Ouch, so the simplest solution is just insert in the 'main' function a >>> try/catch? I believed there was the necessity to create a signal and >>> than attach the KeyboardInterrupt to it... >> >> KeyboardInterrupt is just an exception that gets raised when CTLR+C (or >> the OS's equivalent keyboard combo) gets pressed. It can occur at any >> point in a script since you never know when the user will press it, >> which is why you put the try: except KeyboardInterrupt: around as much >> of your script as possible. The signal that the OS sends to the Python >> interpreter is irrelevant. > > Ok, so can you tell me why this simple script doesn't work (i.e. I'm not > able to catch the keyboard interrupt)? > > import time > import sys > from threading import Thread > > def do_work(): > for _ in range(1000): > try: > time.sleep(1) > print(".", end="") > sys.stdout.flush() > except KeyboardInterrupt: > sys.exit() > > def go(): > threads = [Thread(target=do_work, args=()) for _ in range(2)] > for t in threads: > t.start() > for t in threads: > t.join() > > go() Only the main thread can receive the keyboard interrupt. From robert.kern at gmail.com Thu Dec 10 18:29:06 2009 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 10 Dec 2009 17:29:06 -0600 Subject: umath import error for Numpy builds on OSX 10.6 In-Reply-To: <6b6c00c1-edb8-4469-ab3c-af886aee841f@v15g2000prn.googlegroups.com> References: <6b6c00c1-edb8-4469-ab3c-af886aee841f@v15g2000prn.googlegroups.com> Message-ID: On 2009-12-10 17:09 PM, hardcoreUFO wrote: > For the past several weeks, I have been unable to build numpy from > source, at least nothing that works. The issue is that symbols appear > to be missing from umath. When numpy is imported, I get the following: You will want to ask numpy questions on the numpy mailing list: http://www.scipy.org/Mailing_Lists > In [1]: import numpy > ------------------------------------------------------------ > Traceback (most recent call last): > File "/Library/Python/2.6/site-packages/numpy-1.5.0.dev_20091211- > py2.6-macosx-10.6-universal.egg/numpy/core/__init__.py", line 6, in > > import umath > ImportError: dlopen(/Library/Python/2.6/site-packages/ > numpy-1.5.0.dev_20091211-py2.6-macosx-10.6-universal.egg/numpy/core/ > umath.so, 2): Symbol not found: _npy_cexp > Referenced from: /Library/Python/2.6/site-packages/ > numpy-1.5.0.dev_20091211-py2.6-macosx-10.6-universal.egg/numpy/core/ > umath.so > Expected in: flat namespace > in /Library/Python/2.6/site-packages/numpy-1.5.0.dev_20091211-py2.6- > macosx-10.6-universal.egg/numpy/core/umath.so > I think my build script is good, but here it is just incase: > > #!/bin/sh > export MACOSX_DEPLOYMENT_TARGET=10.6 > export CFLAGS="-arch x86_64" > #export FFLAGS="-arch i386 -arch x86_64" > export FFLAGS="-arch x86_64" > export LDFLAGS="-Wall -lgfortran -undefined dynamic_lookup -bundle - > arch x86_64" > rm -rf build > python setup.py config -L/Users/fonnesbeck/Code/freetype -L/Users/ > fonnesbeck/Code/libpng build > python setupegg.py egg_info --tag-date bdist_egg > > I'm at my wits end with this one, so any help at all is most > appreciated. Don't specify LDFLAGS if you don't have to. It is obliterating the -l flag for the npy_math library that numpy builds internally and tries to link with. -- 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 fonnesbeck at gmail.com Thu Dec 10 18:33:10 2009 From: fonnesbeck at gmail.com (hardcoreUFO) Date: Thu, 10 Dec 2009 15:33:10 -0800 (PST) Subject: umath import error for Numpy builds on OSX 10.6 References: <6b6c00c1-edb8-4469-ab3c-af886aee841f@v15g2000prn.googlegroups.com> Message-ID: <26d13841-fe8b-4801-a18b-09ebd237b08d@h14g2000pri.googlegroups.com> On Dec 11, 12:29?pm, Robert Kern wrote: > On 2009-12-10 17:09 PM, hardcoreUFO wrote: > > > For the past several weeks, I have been unable to build numpy from > > source, at least nothing that works. The issue is that symbols appear > > to be missing from umath. When numpy is imported, I get the following: > > You will want to ask numpy questions on the numpy mailing list: > > ? ?http://www.scipy.org/Mailing_Lists > > > > > > > In [1]: import numpy > > ------------------------------------------------------------ > > Traceback (most recent call last): > > ? ?File "/Library/Python/2.6/site-packages/numpy-1.5.0.dev_20091211- > > py2.6-macosx-10.6-universal.egg/numpy/core/__init__.py", line 6, in > > > > ? ? ?import umath > > ImportError: dlopen(/Library/Python/2.6/site-packages/ > > numpy-1.5.0.dev_20091211-py2.6-macosx-10.6-universal.egg/numpy/core/ > > umath.so, 2): Symbol not found: _npy_cexp > > ? ?Referenced from: /Library/Python/2.6/site-packages/ > > numpy-1.5.0.dev_20091211-py2.6-macosx-10.6-universal.egg/numpy/core/ > > umath.so > > ? ?Expected in: flat namespace > > ? in /Library/Python/2.6/site-packages/numpy-1.5.0.dev_20091211-py2.6- > > macosx-10.6-universal.egg/numpy/core/umath.so > > I think my build script is good, but here it is just incase: > > > #!/bin/sh > > export MACOSX_DEPLOYMENT_TARGET=10.6 > > export CFLAGS="-arch x86_64" > > #export FFLAGS="-arch i386 -arch x86_64" > > export FFLAGS="-arch x86_64" > > export LDFLAGS="-Wall -lgfortran -undefined dynamic_lookup -bundle - > > arch x86_64" > > rm -rf build > > python setup.py config -L/Users/fonnesbeck/Code/freetype -L/Users/ > > fonnesbeck/Code/libpng build > > python setupegg.py egg_info --tag-date bdist_egg > > > I'm at my wits end with this one, so any help at all is most > > appreciated. > > Don't specify LDFLAGS if you don't have to. It is obliterating the -l flag for > the npy_math library that numpy builds internally and tries to link with. > Thanks Robert. I was not able to solve the problem on the Numpy list, so I had to broaden the search.Will try what you suggest, though. From fonnesbeck at gmail.com Thu Dec 10 18:41:46 2009 From: fonnesbeck at gmail.com (hardcoreUFO) Date: Thu, 10 Dec 2009 15:41:46 -0800 (PST) Subject: umath import error for Numpy builds on OSX 10.6 References: <6b6c00c1-edb8-4469-ab3c-af886aee841f@v15g2000prn.googlegroups.com> Message-ID: On Dec 11, 12:29?pm, Robert Kern wrote: > Don't specify LDFLAGS if you don't have to. It is obliterating the -l flag for > the npy_math library that numpy builds internally and tries to link with. Unfortunately, that did not eliminate the error. I thought it was something that was changed in Numpy, because my first go at building was successful on Snow Leopard; it suddenly stopped working a few weeks ago. From gervaz at gmail.com Thu Dec 10 18:43:48 2009 From: gervaz at gmail.com (mattia) Date: 10 Dec 2009 23:43:48 GMT Subject: KeyboardInterrupt References: <4b203886$0$34595$4fafbaef@reader1.news.tin.it> <0a336844-ac41-4d80-9310-4e1f63701eb6@u7g2000yqm.googlegroups.com> <4b2040f9$0$34595$4fafbaef@reader1.news.tin.it> <5c%Tm.61315$We2.28453@newsfe09.iad> <4b21795b$0$30961$4fafbaef@reader3.news.tin.it> Message-ID: <4b2187b3$0$30968$4fafbaef@reader3.news.tin.it> Il Thu, 10 Dec 2009 23:10:02 +0000, Matthew Barnett ha scritto: > mattia wrote: >> Il Thu, 10 Dec 2009 04:56:33 +0000, Brad Harms ha scritto: >> >>> On Thu, 10 Dec 2009 00:29:45 +0000, mattia wrote: >>> >>>> Il Wed, 09 Dec 2009 16:19:24 -0800, Jon Clements ha scritto: >>>> >>>>> On Dec 9, 11:53 pm, mattia wrote: >>>>>> Hi all, can you provide me a simple code snippet to interrupt the >>>>>> execution of my program catching the KeyboardInterrupt signal? >>>>>> >>>>>> Thanks, >>>>>> Mattia >>>>> Errr, normally you can just catch the KeyboardInterrupt exception -- >>>>> is that what you mean? >>>>> >>>>> Jon. >>>> Ouch, so the simplest solution is just insert in the 'main' function >>>> a try/catch? I believed there was the necessity to create a signal >>>> and than attach the KeyboardInterrupt to it... >>> >>> KeyboardInterrupt is just an exception that gets raised when CTLR+C >>> (or the OS's equivalent keyboard combo) gets pressed. It can occur at >>> any point in a script since you never know when the user will press >>> it, which is why you put the try: except KeyboardInterrupt: around as >>> much of your script as possible. The signal that the OS sends to the >>> Python interpreter is irrelevant. >> >> Ok, so can you tell me why this simple script doesn't work (i.e. I'm >> not able to catch the keyboard interrupt)? >> >> import time >> import sys >> from threading import Thread >> >> def do_work(): >> for _ in range(1000): >> try: >> time.sleep(1) >> print(".", end="") >> sys.stdout.flush() >> except KeyboardInterrupt: >> sys.exit() >> >> def go(): >> threads = [Thread(target=do_work, args=()) for _ in range(2)] for t >> in threads: >> t.start() >> for t in threads: >> t.join() >> >> go() > > Only the main thread can receive the keyboard interrupt. Ok, so is there any way to stop all the threads if the keyboard interrupt is received? From patrickstinson.lists at gmail.com Thu Dec 10 19:52:05 2009 From: patrickstinson.lists at gmail.com (Patrick Stinson) Date: Thu, 10 Dec 2009 17:52:05 -0700 Subject: freeze in python3 In-Reply-To: References: Message-ID: <6214d7a20912101652i1fa05f99k9856791aee5895f5@mail.gmail.com> awesome! On Thu, Dec 10, 2009 at 2:17 PM, Martin v. Loewis wrote: >> For example, initerrno should now be PyInit_errno. Am I missing something? > > No; freeze hasn't been ported to Python 3 yet. Contributions are welcome. > > Regards, > Martin > -- > http://mail.python.org/mailman/listinfo/python-list > From n3wcr4zy at gmail.com Thu Dec 10 19:58:40 2009 From: n3wcr4zy at gmail.com (N3wCr4Zy) Date: Thu, 10 Dec 2009 16:58:40 -0800 (PST) Subject: Caps Lock State on Windows Message-ID: how to i get Caps Lock state (on/off) on windows with win32api? From tjreedy at udel.edu Thu Dec 10 19:58:43 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 10 Dec 2009 19:58:43 -0500 Subject: IndentationError In-Reply-To: <506405.21155.qm@web57906.mail.re3.yahoo.com> References: <506405.21155.qm@web57906.mail.re3.yahoo.com> Message-ID: hong zhang wrote: > List, > > I got error says IndentationError in end of line. > I could not figure out why. See following: > > $ ./cont-mcs > File "./cont-mcs", line 264 > mcs1 = ht_val+cck_val+green_val+fat_val+sgi_val > ^ > IndentationError: unindent does not match any outer indentation level Look at previous lines. Make sure you only use tabs or only use spaces and not both. If you still need help, post all code back to last unindented line. From ben+python at benfinney.id.au Thu Dec 10 19:58:57 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 11 Dec 2009 11:58:57 +1100 Subject: IndentationError References: Message-ID: <87fx7i72cu.fsf@benfinney.id.au> hong zhang writes: > I got error says IndentationError in end of line. > I could not figure out why. Nor can we, without seeing the code to compare indentation levels. > Thanks for help. Please construct a minimal example (not a whole huge program), that we can run to show the behaviour you're seeing. -- \ ?Any intelligent fool can make things bigger and more complex? | `\ It takes a touch of genius ? and a lot of courage ? to move in | _o__) the opposite direction.? ?Albert Einstein | Ben Finney From python at rcn.com Thu Dec 10 20:23:10 2009 From: python at rcn.com (Raymond Hettinger) Date: Thu, 10 Dec 2009 17:23:10 -0800 (PST) Subject: Float precision and float equality References: <574bd33c-a38b-4af5-802e-fc081965a230@g23g2000vbr.googlegroups.com> <6624fc07-c6d5-40e1-a899-6eb73603a980@u8g2000prd.googlegroups.com> <335cb11d-e862-4daa-aec6-8f96b56bc28a@u1g2000pre.googlegroups.com> <79c41269-2b84-4fb1-8694-c7212f92be62@d9g2000prh.googlegroups.com> <49d04d6f-551b-46a9-8a11-7abe308a0154@f10g2000vbl.googlegroups.com> <8477d937-f44a-4e78-aa35-d97cb1ab5c06@f20g2000prn.googlegroups.com> <81fcae23-ed2c-4a48-b9d5-dae1002df848@z35g2000prh.googlegroups.com> Message-ID: [Carl Banks] > > You're talking about machine epsilon? ?I think everyone else here is > > talking about a number that is small relative to the expected smallest > > scale of the calculation. That was also my reading of the OP's question. The suggestion to use round() was along the lines of performing a quantize or snap-to-grid operation after each step in the calculation. That approach parallels the recommendation for how to use the decimal module for fixed point calculations: http://docs.python.org/library/decimal.html#decimal-faq Raymond From lodmod.dod at gmail.com Thu Dec 10 20:30:08 2009 From: lodmod.dod at gmail.com (LoD MoD) Date: Thu, 10 Dec 2009 17:30:08 -0800 Subject: urllib post and redirect = fail Message-ID: I'm trying to do a post to log into a simple admin console. All I get is a simple you need to log in error. I already mapped the form id's to make sure they are correct, but it still seems to deny. I know mechanize would probably do a better job of this than urllib, but their docs for python aren't available online right now. Any help is appreciated. import urllib, urllib2 # build opener with HTTPCookieProcessor o = urllib2.build_opener( urllib2.HTTPCookieProcessor() ) urllib2.install_opener( o ) # assuming the site expects 'user' and 'pass' as query params #p = urllib.urlencode( { 'j_character_encoding' : 'UTF-8', 'j_username': 'cooduser', 'j_password': 'password' } ) p = urllib.urlencode(dict(j_username='cooduser', j_password='password')) # perform login with params f = o.open( 'http://myserver:5000/login/LoginForm.jsp', p ) data = f.read() f.close() print data Here is the form source:

Authentication Denied Authentication Denied

The username or password has been refused by Server. Please try again.

The response code is 200. Here is the header info from f.info() : Cache-Control: no-cache Connection: close Date: Fri, 11 Dec 2009 01:29:40 GMT Pragma: no-cache Content-Length: 3534 Content-Type: text/html; charset=UTF-8 Expires: Thu, 01 Jan 1970 00:00:00 GMT Set-Cookie: NCONSOLESESSION=QwcDLhgG5NrxJGBQJfpv1dynvpddjT4LJTHnGhYz9ZDl6R9Pzqvh!2016686010; path=/ X-Powered-By: Servlet/2.5 JSP/2.1 From gagsl-py2 at yahoo.com.ar Thu Dec 10 20:36:10 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 10 Dec 2009 22:36:10 -0300 Subject: IndentationError References: <506405.21155.qm@web57906.mail.re3.yahoo.com> Message-ID: En Wed, 09 Dec 2009 16:32:18 -0300, hong zhang escribi?: > I got error says IndentationError in end of line. > I could not figure out why. See following: > > $ ./cont-mcs > File "./cont-mcs", line 264 > mcs1 = ht_val+cck_val+green_val+fat_val+sgi_val > ^ > IndentationError: unindent does not match any outer indentation level The caret ^ might be misplaced; look at start of line 264, or perhaps the previous line. Remember not to mix tabs and spaces. -- Gabriel Genellina From half.italian at gmail.com Thu Dec 10 20:37:45 2009 From: half.italian at gmail.com (Sean DiZazzo) Date: Thu, 10 Dec 2009 17:37:45 -0800 (PST) Subject: daemon.DaemonContext and logging Message-ID: <105750f9-2ed1-4dc3-b23d-d64d3b433224@z10g2000prh.googlegroups.com> I'm finally getting around to trying out the python-daemon module and have hit a wall. I'm trying to set up logging inside of the "with daemon.DaemonContext" block. But when I try to use a logger inside the block it throws an error: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ from __future__ import with_statement import logging import logging.handlers import daemon import daemon.pidlockfile import sys logger = logging.getLogger("DaemonLog") logger.setLevel(logging.INFO) formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") handler = logging.FileHandler("log.file") logger.addHandler(handler) pid = daemon.pidlockfile.TimeoutPIDLockFile("/var/run/daemontest.pid", 10) with daemon.DaemonContext(pidfile=pid, gid=0, uid=0, stdout=sys.stdout, stderr=sys.stderr): logger.info("POO") ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ I get the following traceback: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ [seans_imac:~/Downloads] halfitalian% Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/logging/__init__.py", line 753, in emit self.flush() File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/logging/__init__.py", line 731, in flush self.stream.flush() IOError: [Errno 9] Bad file descriptor Error in atexit._run_exitfuncs: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/atexit.py", line 24, in _run_exitfuncs func(*targs, **kargs) File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/logging/__init__.py", line 1355, in shutdown h.close() File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/logging/__init__.py", line 784, in close self.stream.close() IOError: [Errno 9] Bad file descriptor Error in sys.exitfunc: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/atexit.py", line 24, in _run_exitfuncs func(*targs, **kargs) File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/logging/__init__.py", line 1355, in shutdown h.close() File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/logging/__init__.py", line 784, in close self.stream.close() IOError: [Errno 9] Bad file descriptor ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Any advice? Also, I left in the call to TimeoutPIDLockfile() as well, because the library's documentation is pretty sparse, and I want to know if I'm using it properly. Thanks in advance. ~Sean From gagsl-py2 at yahoo.com.ar Thu Dec 10 20:48:05 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 10 Dec 2009 22:48:05 -0300 Subject: using freeze.py with python3 References: <6214d7a20912091204h2d176b55m75afdd0dc18851f@mail.gmail.com> Message-ID: En Wed, 09 Dec 2009 17:04:45 -0300, Patrick Stinson escribi?: > Has anyone tried using Python-3.1.1/Tools/freeze/freeze.py with the > encodings package? It appears that encodings is required to intialize > the interpreter, but PyImport_ImportFrozenModule is failing for the > "encodings" module in marshal.c:r_object(), after trying to demarshal > an object of type 0. I'd report this at http://bugs.python.org -- Gabriel Genellina From lie.1296 at gmail.com Thu Dec 10 20:57:15 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Fri, 11 Dec 2009 12:57:15 +1100 Subject: IndentationError In-Reply-To: References: Message-ID: <4b21a785$1@dnews.tpgi.com.au> On 12/10/2009 6:32 AM, hong zhang wrote: > List, > > I got error says IndentationError in end of line. > I could not figure out why. See following: > > $ ./cont-mcs > File "./cont-mcs", line 264 > mcs1 = ht_val+cck_val+green_val+fat_val+sgi_val > ^ > IndentationError: unindent does not match any outer indentation level > Look at the surrounding code. Indentation Errors often lies on the previous few lines. Possibly caused by unmatching parentheses. From kevinar18 at hotmail.com Thu Dec 10 21:05:57 2009 From: kevinar18 at hotmail.com (Kevin Ar18) Date: Thu, 10 Dec 2009 21:05:57 -0500 Subject: Overriding the >> builtin Message-ID: I am aware of the fact that you can somehow replace the __builtins__ in Python. There is a library here that modifies the >> binary builtins: http://github.com/aht/stream.py/blob/master/stream.py Question: Is there anywhere that explains in detail how to modify the builtins in Python like this library did? _________________________________________________________________ Windows 7: Unclutter your desktop. Learn more. http://www.microsoft.com/windows/windows-7/videos-tours.aspx?h=7sec&slideid=1&media=aero-shake-7second&listid=1&stop=1&ocid=PID24727::T:WLMTAGL:ON:WL:en-US:WWL_WIN_7secdemo:122009 -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Thu Dec 10 21:22:06 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 10 Dec 2009 23:22:06 -0300 Subject: Porting pyftpdlib to Python 3.x: question about tarball naming convention References: Message-ID: En Wed, 09 Dec 2009 20:13:17 -0300, Giampaolo Rodola' escribi?: > I've started the (hard) process of porting pyftpdlib [1] to Python 3. > In order to do that I'm working on a separate SVN branch and I plan to > maintain two different releases of my software, one for 2.x and > another one for 3.x. I would not do that. Try to keep a single source (2.x) and use 2to3 to automatically generate the 3.x version. Perhaps including some conditionals checking sys.version_info. Somewhere in the wiki there are porting guidelines. (Try to resist the temptation to alter the 3.x code: it must remain "generated" by the 2to3 conversion) > My doubts are about the naming convention I have to use for the > tarball and how it affects the integration with distutils and > setuptools. > Now that I'm going to have two major releases (pyftpdlib-0.5.2 for > Python 2.x and pyftpdlib-0.5.2 for Python 3.x) how am I supposed to > deal with that? If you manage to write the code in a way that 2to3 can convert it to 3.x without any problems, then you don't have to distribute the 3.x sources at all. Just run 2to3 on the target system as part of the install process. -- Gabriel Genellina From lie.1296 at gmail.com Thu Dec 10 21:33:35 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Fri, 11 Dec 2009 13:33:35 +1100 Subject: KeyboardInterrupt In-Reply-To: <4b2187b3$0$30968$4fafbaef@reader3.news.tin.it> References: <4b203886$0$34595$4fafbaef@reader1.news.tin.it> <0a336844-ac41-4d80-9310-4e1f63701eb6@u7g2000yqm.googlegroups.com> <4b2040f9$0$34595$4fafbaef@reader1.news.tin.it> <5c%Tm.61315$We2.28453@newsfe09.iad> <4b21795b$0$30961$4fafbaef@reader3.news.tin.it> <4b2187b3$0$30968$4fafbaef@reader3.news.tin.it> Message-ID: <4b21b00b$1@dnews.tpgi.com.au> On 12/11/2009 10:43 AM, mattia wrote: > Ok, so is there any way to stop all the threads if the keyboard interrupt > is received? You can't stop a thread from outside. The thread has to end itself (by ending the function). Usually, in the thread, you will check the value of a variable. If it's false, then it's time to stop and head to the end of the function. # global, or better use a Quit sentinel in a Queue import time, sys from threading import Thread running = True def do_work(): while True: time.sleep(1) print(".", end="") sys.stdout.flush() if running == False: break print('thread ended') def go(): global running threads = [Thread(target=do_work, args=()) for _ in range(2)] for t in threads: t.start() try: while running: time.sleep(1) running = any(t.is_alive() for t in threads) except KeyboardInterrupt: running = False From bearophileHUGS at lycos.com Thu Dec 10 21:51:04 2009 From: bearophileHUGS at lycos.com (Bearophile) Date: Thu, 10 Dec 2009 18:51:04 -0800 (PST) Subject: switch References: <335204.99872.qm@web57905.mail.re3.yahoo.com> <4b1f65b9$0$30372$426a74cc@news.free.fr> Message-ID: <38d1e41f-32d0-4907-aa46-d370f6c7be5f@v25g2000yqk.googlegroups.com> Bruno Desthuilliers: > Well, obviously such business rules must by no mean be hardcoded. You > really need a "rule engine", configurable by your domain experts thru a > DSL that we'll design specially for you. The rule engine will generate > an AbstractScoreFactory that will instanciate appropriate IScore > implementation objects that knows what to do. [snip] Thank you very much for bringing back some sanity in this newsgroup, sometimes a good antiexample like yours is better than many explanations. Bye, bearophile From gagsl-py2 at yahoo.com.ar Thu Dec 10 21:56:13 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 10 Dec 2009 23:56:13 -0300 Subject: KeyboardInterrupt References: <4b203886$0$34595$4fafbaef@reader1.news.tin.it> <0a336844-ac41-4d80-9310-4e1f63701eb6@u7g2000yqm.googlegroups.com> <4b2040f9$0$34595$4fafbaef@reader1.news.tin.it> <5c%Tm.61315$We2.28453@newsfe09.iad> <4b21795b$0$30961$4fafbaef@reader3.news.tin.it> <4b2187b3$0$30968$4fafbaef@reader3.news.tin.it> Message-ID: En Thu, 10 Dec 2009 20:43:48 -0300, mattia escribi?: > Il Thu, 10 Dec 2009 23:10:02 +0000, Matthew Barnett ha scritto: > >> Only the main thread can receive the keyboard interrupt. > > Ok, so is there any way to stop all the threads if the keyboard interrupt > is received? If all other threads (except the main one) are "daemon" threads, then the whole process finishes when the main thread exits; all daemon threads are abruptly finished. Note that "try/finally" blocks are not honored, neither are "with" statements... If you want an orderly retreat, the other threads must cooperate (e.g. the main thread sets a flag and they periodically check for it). -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Thu Dec 10 22:09:45 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 11 Dec 2009 00:09:45 -0300 Subject: When will Python 3 be fully deployed References: <4b20ac0a$0$1596$742ec2ed@news.sonic.net> Message-ID: En Thu, 10 Dec 2009 05:18:13 -0300, John Nagle escribi?: > Luis M. Gonz?lez wrote: >> On Dec 6, 3:21 pm, vsoler wrote: > > I'd argue against using Python 2.6 for production work. Either use > Python 2.5, which is stable, or 3.x, which is bleeding-edge. 2.6 has > some of the > features of Python 3.x, but not all of them, and is neither fish nor fowl > as a result. 2.6 is really more of a sideline that was used for trying > out new features, not something suitable for production. > > I think the idea is to run your 2.5 code through '2to3" and see if it > works in 3.x. In addition to Ned Deily's previous comments, I'd like to note that 2to3 assumes the source is valid 2.6 code - you have to ensure the code runs fine with Python 2.6 before using 2to3 to convert to 3.x -- Gabriel Genellina From john at castleamber.com Thu Dec 10 22:22:41 2009 From: john at castleamber.com (John Bokma) Date: Thu, 10 Dec 2009 21:22:41 -0600 Subject: switch References: <335204.99872.qm@web57905.mail.re3.yahoo.com> <68e6e315-f3c7-4e52-a56f-802e99d75e6a@y32g2000prd.googlegroups.com> <9010003a-d129-46b4-9535-88b03f0bc121@w19g2000pre.googlegroups.com> Message-ID: <87638ekxdq.fsf@castleamber.com> Tim Chase writes: Please don't delete attribution line(s), added: Asun Friere writes: >> >> phone.update_from_record(record) >> >> This switch statement belongs to one guy. One guy who wants to know >> how to do everything that needs to be done to Phones no matter who >> asks > > This is where you make a false assumption -- the contents and parsing > of the "switch" are provider-specific in this case, mapping to a > common ontology of the Phone object: In that case, why not give the classes Asun suggested all the same base class: Phone? >> I wonder if you agree that it's bit cleaner now? It's an effective >> solution. I'm making no representation that it's the best. > > It's clean if it were the solution to my problem -- however, the mess > comes from the profusion of provider formats. Yup, and there is no other solution to that than to convert them to something universal. > Yes, having been programming since I was in middle-school (quick > calculation yields a "boy I'm old" estimate of about 20 years...does > anybody miss 360k 5.25" floppy disks? :) I do miss cassette tapes and the wheeeeeee kkkrggrggrgrgrg of a program loading. -- John Bokma Read my blog: http://johnbokma.com/ Hire me (Perl/Python): http://castleamber.com/ From gagsl-py2 at yahoo.com.ar Thu Dec 10 22:23:19 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 11 Dec 2009 00:23:19 -0300 Subject: Parsing html with Beautifulsoup References: <20091210091519.GA14175@sun.ac.za> Message-ID: En Thu, 10 Dec 2009 06:15:19 -0300, Johann Spies escribi?: > How do I get Beautifulsoup to render (taking the above line as > example) > > sunentint for   href=#OBJ_sunetint>sunetint
> > and still provide the text-parts in the 's with plain text? Hard to tell if we don't see what's inside those 's - please provide at least a few rows of the original HTML table. -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Thu Dec 10 22:41:30 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 11 Dec 2009 00:41:30 -0300 Subject: Runtime load python modules from memory References: Message-ID: En Thu, 10 Dec 2009 12:13:15 -0300, scream.ru at gmail.com escribi?: > Is it possible to load python module from memory? > > For example, I can read python .pyc file into memory, > preprocess it ( decrypt :-) ), and then import it. > > Is it possible? Sure. Frozen modules are exactly that; see Tools/freeze in the source tree. If you want to do some preprocessing, read PEP 302 and implement the importer protocol. -- Gabriel Genellina From python at bdurham.com Thu Dec 10 22:42:56 2009 From: python at bdurham.com (python at bdurham.com) Date: Thu, 10 Dec 2009 22:42:56 -0500 Subject: CherryPy work with 64-bit version of Python 2.6? Message-ID: <1260502976.15005.1349548031@webmail.messagingengine.com> Anyone know if CherryPy works with the 64-bit version of Python 2.6? Thank you, Malcolm -------------- next part -------------- An HTML attachment was scrubbed... URL: From ppearson at nowhere.invalid Thu Dec 10 22:59:36 2009 From: ppearson at nowhere.invalid (Peter Pearson) Date: 11 Dec 2009 03:59:36 GMT Subject: IndentationError References: <4b21a785$1@dnews.tpgi.com.au> Message-ID: <7odud8F3pc8maU1@mid.individual.net> On Fri, 11 Dec 2009 12:57:15 +1100, Lie Ryan wrote: > On 12/10/2009 6:32 AM, hong zhang wrote: >> List, >> >> I got error says IndentationError in end of line. >> I could not figure out why. See following: >> >> $ ./cont-mcs >> File "./cont-mcs", line 264 >> mcs1 = ht_val+cck_val+green_val+fat_val+sgi_val >> ^ >> IndentationError: unindent does not match any outer indentation level >> > > Look at the surrounding code. Indentation Errors often lies on the > previous few lines. Possibly caused by unmatching parentheses. Do you see what's wrong here? ... Python 2.5.2 (r252:60911, Jul 22 2009, 15:35:03) [GCC 4.2.4 (Ubuntu 4.2.4-1ubuntu3)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> if None: ... print x ... print y File "", line 3 print y ^ IndentationError: unindent does not match any outer indentation level >>> The problem is that "print y" is indented less than "print x", meaning that the indented code block containing "print x" is over, and yet "print y" is *not* indented the same as the "if". -- To email me, substitute nowhere->spamcop, invalid->net. From half.italian at gmail.com Thu Dec 10 23:21:18 2009 From: half.italian at gmail.com (Sean DiZazzo) Date: Thu, 10 Dec 2009 20:21:18 -0800 (PST) Subject: daemon.DaemonContext and logging References: <105750f9-2ed1-4dc3-b23d-d64d3b433224@z10g2000prh.googlegroups.com> Message-ID: <373ccabe-0a09-4433-a68f-ac1ccba19a69@13g2000prl.googlegroups.com> On Dec 10, 5:37?pm, Sean DiZazzo wrote: > I'm finally getting around to trying out the python-daemon module and > have hit a wall. ?I'm trying to set up logging inside of the "with > daemon.DaemonContext" block. ?But when I try to use a logger inside > the block it throws an error: Got it! The DaemonContext closes all open file descriptors, including the one inside the logging handler. I got it to work by passing the logger's file handle in with the "preserve_files" option. ~Sean From donn.ingle at gmail.com Thu Dec 10 23:41:56 2009 From: donn.ingle at gmail.com (Donn) Date: Fri, 11 Dec 2009 06:41:56 +0200 Subject: pyZui - anyone know about this? Message-ID: <200912110641.56775.donn.ingle@gmail.com> Hi, I happened upon this youtube link: http://www.youtube.com/watch?v=57nWm984wdY It fairly blew my socks off. In it a fellow by the name of David Roberts demos a zui written in Python. Aside from the zooming (which is impressive enough) it show embedding of images, pdf files, web pages and text. He says nothing about what toolkits were used or how it might have been done. It's Linux-based, but no other info. On some googling, I can only find a few bug reports on pypi related to pyQt. I would really like to find out how that ZUI was done, it's simply amazing. Any clues out there? \d -- \/\/ave: donn.ingle at googlewave.com home: http://otherwise.relics.co.za/ 2D vector animation : https://savannah.nongnu.org/projects/things/ Font manager : https://savannah.nongnu.org/projects/fontypython/ From robert.kern at gmail.com Thu Dec 10 23:44:14 2009 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 10 Dec 2009 22:44:14 -0600 Subject: umath import error for Numpy builds on OSX 10.6 In-Reply-To: <26d13841-fe8b-4801-a18b-09ebd237b08d@h14g2000pri.googlegroups.com> References: <6b6c00c1-edb8-4469-ab3c-af886aee841f@v15g2000prn.googlegroups.com> <26d13841-fe8b-4801-a18b-09ebd237b08d@h14g2000pri.googlegroups.com> Message-ID: On 2009-12-10 17:33 PM, hardcoreUFO wrote: > Thanks Robert. I was not able to solve the problem on the Numpy list, > so I had to broaden the search.Will try what you suggest, though. There's no one here who can help you with this who isn't on the numpy list. -- 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 robert.kern at gmail.com Thu Dec 10 23:47:51 2009 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 10 Dec 2009 22:47:51 -0600 Subject: umath import error for Numpy builds on OSX 10.6 In-Reply-To: References: <6b6c00c1-edb8-4469-ab3c-af886aee841f@v15g2000prn.googlegroups.com> Message-ID: On 2009-12-10 17:41 PM, hardcoreUFO wrote: > On Dec 11, 12:29 pm, Robert Kern wrote: >> Don't specify LDFLAGS if you don't have to. It is obliterating the -l flag for >> the npy_math library that numpy builds internally and tries to link with. > > Unfortunately, that did not eliminate the error. I thought it was > something that was changed in Numpy, because my first go at building > was successful on Snow Leopard; it suddenly stopped working a few > weeks ago. Right, when the -lnpymath stuff got checked in. Looking at the build log you posted to numpy-discusson, it does appear that the $LDFLAGS is obliterating the intended flags. Please post a build log without setting those flags to numpy-discussion. A correct link line should look something like this: gcc -arch i386 -arch ppc -isysroot /Developer/SDKs/MacOSX10.4u.sdk -g -bundle -undefined dynamic_lookup build/temp.macosx-10.3-i386-2.5/numpy/core/src/umath/umathmodule_onefile.o -Lbuild/temp.macosx-10.3-i386-2.5 -lnpymath -o build/lib.macosx-10.3-i386-2.5/numpy/core/umath.so -- 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 ben+python at benfinney.id.au Thu Dec 10 23:57:02 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 11 Dec 2009 15:57:02 +1100 Subject: New user documentation for =?utf-8?Q?=E2=80=98python-daemon?= =?utf-8?Q?=E2=80=99?= (was: daemon.DaemonContext and logging) References: <105750f9-2ed1-4dc3-b23d-d64d3b433224@z10g2000prh.googlegroups.com> <373ccabe-0a09-4433-a68f-ac1ccba19a69@13g2000prl.googlegroups.com> Message-ID: <873a3i6rc1.fsf_-_@benfinney.id.au> Sean DiZazzo writes: > On Dec 10, 5:37?pm, Sean DiZazzo wrote: > > I'm finally getting around to trying out the python-daemon module > > and have hit a wall. ?I'm trying to set up logging inside of the > > "with daemon.DaemonContext" block. ?But when I try to use a logger > > inside the block it throws an error: > > Got it! The DaemonContext closes all open file descriptors, including > the one inside the logging handler. I got it to work by passing the > logger's file handle in with the "preserve_files" option. Beautiful. If anyone would like to write a new user's guide for ?python-daemon? (in reStructuredText format), I'd appreciate it. If you want to take advantage of distributed VCS, the Bazaar repository for the project is online; here's how to get a branch: $ bzr version Bazaar (bzr) 2.0.2 [?] $ bzr branch http://bzr.debian.org/bzr/python-daemon/python-daemon.devel/ $ cd python-daemon.devel/ Then you can hack away and commit, and use ?bzr send? to send your changes to me. -- \ ?Think for yourselves and let others enjoy the privilege to do | `\ so too.? ?Voltaire, _Essay On Tolerance_ | _o__) | Ben Finney From ben+python at benfinney.id.au Fri Dec 11 00:07:30 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 11 Dec 2009 16:07:30 +1100 Subject: When will Python 3 be fully deployed References: <4b20ac0a$0$1596$742ec2ed@news.sonic.net> Message-ID: <87y6la5ca5.fsf@benfinney.id.au> "Gabriel Genellina" writes: > In addition to Ned Deily's previous comments, I'd like to note that > 2to3 assumes the source is valid 2.6 code - you have to ensure the > code runs fine with Python 2.6 before using 2to3 to convert to 3.x To achieve that, you're strongly encouraged to follow Step 0 of the transition guidelines . -- \ ?It was half way to Rivendell when the drugs began to take | `\ hold? ?Hunter S. Tolkien, _Fear and Loathing in Barad-D?r_ | _o__) | Ben Finney From frank at chagford.com Fri Dec 11 02:00:23 2009 From: frank at chagford.com (Frank Millman) Date: Fri, 11 Dec 2009 09:00:23 +0200 Subject: How do I Block Events in wxPython References: <6854a0bb-9edc-4392-9761-d2f3cf98f89e@k4g2000yqb.googlegroups.com><7a9c25c20912092357i7fb0e327gf88919a85fdf3482@mail.gmail.com> <7a9c25c20912100816y59e023e3kb35a87aa10c80913@mail.gmail.com> Message-ID: Stephen Hansen wrote: > > Well if you have a legitimate case for pre-empting the event loop with > these > periodic regular short blocking moments (it seems you may), I think what > you > want to do is overwrite FilterEvent on your App object. You can then make > that flag something you set on the app, and while it's true, returning > False > (or True, I really don't know the differenced between telling wx 'Ok, I > processed this event you can ignore it' and 'Ok, I'm not going to process > this event and neither should you'). Otherwise, return -1. > This works beautifully - thanks, Stephen. As you say, the difference between returning True or False is not clear, but in practice I found that I had to return True - then all mouse and keyboard activity is blocked. There is another step required, which I did not find in the docs, but found in help(wx.App.FilterEvent). If you override FilterEvent, you also have to call SetCallFilterEvent(True) on the App object when you want it to be called, and set it back to False when finished. This is handy, as it avoids the overhead of calling it when you don't need it. In fact, as I am writing this, I realise that I don't need a flag at all. I just override FilterEvent, and return True. Then when I want to block, I call SetCallFilterEvent(True), and when I want to stop, I call SetCallFilterEvent(False). This is very useful. Thanks again. Frank From jspies at sun.ac.za Fri Dec 11 02:04:38 2009 From: jspies at sun.ac.za (Johann Spies) Date: Fri, 11 Dec 2009 09:04:38 +0200 Subject: Parsing html with Beautifulsoup In-Reply-To: References: <20091210091519.GA14175@sun.ac.za> Message-ID: <4B21EF06.1040505@sun.ac.za> Gabriel Genellina het geskryf: > En Thu, 10 Dec 2009 06:15:19 -0300, Johann Spies > escribi?: > >> How do I get Beautifulsoup to render (taking the above line as >> example) >> >> sunentint for  > href=#OBJ_sunetint>sunetint
>> >> and still provide the text-parts in the 's with plain text? > > Hard to tell if we don't see what's inside those 's - please > provide at least a few rows of the original HTML table. > Thanks for your reply. Here are a few lines: 2 All Users at Any
 Any
 clientencrypt  3 Any
  4  Rainwall_Group
 RainWall_Stop
&nb$    5  Rainwall_Group
 Rainwall_Group
 Rainwall_Broadcast
 RainWall_Daemon
  Regards Johann -- Johann Spies Telefoon: 021-808 4599 Informasietegnologie, Universiteit van Stellenbosch "Lo, children are an heritage of the LORD: and the fruit of the womb is his reward." Psalms 127:3 From wissme at hotmail.com Fri Dec 11 02:50:15 2009 From: wissme at hotmail.com (Jean Guillaume Pyraksos) Date: Fri, 11 Dec 2009 08:50:15 +0100 Subject: ANN: Wing IDE 3.2.3 released References: Message-ID: In article , Wingware wrote: > http://wingware.com/downloads/wingide-101/3.2 No Cocoa version for MacOS-X ? Shall we have to use X11 in 2009 ? How come ? JG From joanmg at gmail.com Fri Dec 11 03:13:03 2009 From: joanmg at gmail.com (joanmg at gmail.com) Date: Fri, 11 Dec 2009 00:13:03 -0800 (PST) Subject: Python tricks with applescript in OS-X Message-ID: Greetings, I've written a short document with some working examples of how to interface python with other applications in OS-X via applescript (had to spend some time figuring it out, and thought I might as well write it down). The examples include asking Google Earth for the latitude and longitude of the point at the center of its screen, or using the finder to pop-up a dialog window to get input from the user: http://juanreyero.com/article/python/os-x-python.html Cheers, Juan http://juanreyero.com From anh.hai.trinh at gmail.com Fri Dec 11 03:16:12 2009 From: anh.hai.trinh at gmail.com (Anh Hai Trinh) Date: Fri, 11 Dec 2009 00:16:12 -0800 (PST) Subject: which pi formula is given in the decimal module documentation? Message-ID: <4c88dd83-213c-49c0-8c36-d9058be24dc3@m7g2000prd.googlegroups.com> I'm just curious which formula for pi is given here: ? def pi(): """Compute Pi to the current precision. >>> print pi() 3.141592653589793238462643383 """ getcontext().prec += 2 # extra digits for intermediate steps three = Decimal(3) # substitute "three=3.0" for regular floats lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24 while s != lasts: lasts = s n, na = n+na, na+8 d, da = d+da, da+32 t = (t * n) / d s += t getcontext().prec -= 2 return +s # unary plus applies the new precision It looks like an infinite series with term `t`, where`n` = (2k-1)^2 and `d` = d = 4k(4k+2) for k = 1... Does it have a name? From nicola.larosa at gmail.com Fri Dec 11 03:34:11 2009 From: nicola.larosa at gmail.com (Nicola Larosa (tekNico)) Date: Fri, 11 Dec 2009 00:34:11 -0800 (PST) Subject: Question on Python as career References: <614b8dde-324b-4d54-8e73-7a96e4c0b1cf@a21g2000yqc.googlegroups.com> Message-ID: <8017af95-0830-485a-9e47-4a547ea9aa61@d20g2000yqh.googlegroups.com> > Tim Roberts wrote: >> There are very, very few full-time Python jobs anywhere in the world, >> although many people use Python as one tool in their toolbox. Not that few. Anyway, it's not a zero-sum game: you want to work with Python? Find a job where *you* introduce it. :-) Aahz wrote: > All my employment in the last decade, including three different > full-time jobs at three different companies, has had Python as the > primary job skill requirement and is what I spent more time working > with than anything else. Wow, same as me. :-) Except, mine were four full-time jobs at four different companies, and I introduced Python in the first two, in Italy of all places. I am glad that I didno't have to introduced Python myself for three years now, but was instead asked to work with it. Making yourself known to the community is fundamental, so I second Michele's comment: invest some of your time in free/open work, and you'll be much rewarded. -- Nicola Larosa - http://www.tekNico.net/ Do you know how to proof-read your writing before hitting send? If not, please learn. A spell checker may help. If you do know how, if you care so little for what you write that you can't be bothered, why should any- one care enough to read what you write? - Steven D'Aprano, October 2009 From dbd at ieee.org Fri Dec 11 03:37:09 2009 From: dbd at ieee.org (dbd) Date: Fri, 11 Dec 2009 00:37:09 -0800 (PST) Subject: Float precision and float equality References: <6624fc07-c6d5-40e1-a899-6eb73603a980@u8g2000prd.googlegroups.com> <335cb11d-e862-4daa-aec6-8f96b56bc28a@u1g2000pre.googlegroups.com> <79c41269-2b84-4fb1-8694-c7212f92be62@d9g2000prh.googlegroups.com> <49d04d6f-551b-46a9-8a11-7abe308a0154@f10g2000vbl.googlegroups.com> <8477d937-f44a-4e78-aa35-d97cb1ab5c06@f20g2000prn.googlegroups.com> <81fcae23-ed2c-4a48-b9d5-dae1002df848@z35g2000prh.googlegroups.com> <1aece245-2ea8-4e9a-91c1-839fca73e720@g4g2000pri.googlegroups.com> Message-ID: On Dec 10, 2:23?pm, Carl Banks wrote: > ... > > A useful description of floating point issues can be found: > > [snip] > > I'm not reading it because I believe I grasp the situation just fine. > ... > > Say I have two numbers, a and b. ?They are expected to be in the range > (-1000,1000). ?As far as I'm concerned, if they differ by less than > 0.1, they might as well be equal. > ... > Carl Banks I don't expect Carl to read. I posted the reference for the OP whose only range specification was "calculations with floats" and "equality of floats" and who expressed concern about "truncation errors". Those who can't find "floats" in the original post will find nothing of interest in the reference. Dale B. Dalrymple From jan.mach at cesnet.cz Fri Dec 11 04:26:49 2009 From: jan.mach at cesnet.cz (Jan Mach) Date: Fri, 11 Dec 2009 10:26:49 +0100 Subject: Variable class instantiation Message-ID: <1260523609.4490.464.camel@omnius> Hi everybody, I am currently solving the following problem and I am stuck. I am trying to create instance of the class of variable name. I know, that the following works: if (something): classToUse = C1 else: classToUse = C2 o = classToUse() ,but this is not what I want. I need to have the class name in the string and then instantiate it: (this does not work of course) classToUse = "C1" o = classToUse() It is because I don`t know at the moment what the name of the class will be, I will load it from the file or pass it as argument. Does anyone know what is the correct syntax to accomplish this? Thanks for your time in advance Jan Mach -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3129 bytes Desc: not available URL: From joaopcf at gmail.com Fri Dec 11 04:43:16 2009 From: joaopcf at gmail.com (=?ISO-8859-1?Q?Jo=E3o?=) Date: Fri, 11 Dec 2009 01:43:16 -0800 (PST) Subject: plain text parsing to html (newbie problem) References: <6664c88b-ec93-4b6c-a536-8a6b5959cd5e@a21g2000yqc.googlegroups.com> <35a19377-d2d4-4fb1-ad58-b999e0b9ff8f@u16g2000pru.googlegroups.com> <0f2e4a9a-284e-425f-9f02-045f32268d16@n35g2000yqm.googlegroups.com> <4b2152b7$1@dnews.tpgi.com.au> Message-ID: <9efe81d2-4e9a-41d9-acf9-28b89d954189@a21g2000yqc.googlegroups.com> On Dec 10, 7:55?pm, Lie Ryan wrote: > > and, is there any reason why you're not using the email and smtplib?http://docs.python.org/library/email-examples.html Mainly because I was unaware of them :( I just read about them and I found all the Subject, From, To classes, but what about Content-Type? I need Content-Type: text/html and charset="utf-8" so that I can pass a basic CSS formatting. How can I do that? With email.mime.base.MIMEBase? I'll have to update that in my code later, as I already got it to work and my current RHEL5.3 default Python 2.4.3 (#1, Sep 17 2008) install is complaining with "ImportError: No module named mime.multipart" Thank you for your patience and feedback From joaopcf at gmail.com Fri Dec 11 04:43:42 2009 From: joaopcf at gmail.com (=?ISO-8859-1?Q?Jo=E3o?=) Date: Fri, 11 Dec 2009 01:43:42 -0800 (PST) Subject: plain text parsing to html (newbie problem) References: <6664c88b-ec93-4b6c-a536-8a6b5959cd5e@a21g2000yqc.googlegroups.com> <35a19377-d2d4-4fb1-ad58-b999e0b9ff8f@u16g2000pru.googlegroups.com> <0f2e4a9a-284e-425f-9f02-045f32268d16@n35g2000yqm.googlegroups.com> <4b2152b7$1@dnews.tpgi.com.au> Message-ID: <861943af-a905-4254-9ff2-c8b42b56ff34@m25g2000yqc.googlegroups.com> On Dec 10, 7:55?pm, Lie Ryan wrote: > > and, is there any reason why you're not using the email and smtplib?http://docs.python.org/library/email-examples.html Mainly because I was unaware of them :( I just read about them and I found all the Subject, From, To classes, but what about Content-Type? I need Content-Type: text/html and charset="utf-8" so that I can pass a basic CSS formatting. How can I do that? With email.mime.base.MIMEBase? I'll have to update that in my code later, as I already got it to work and my current RHEL5.3 default Python 2.4.3 (#1, Sep 17 2008) install is complaining with "ImportError: No module named mime.multipart" Thank you for your patience and feedback From chardster at gmail.com Fri Dec 11 05:06:35 2009 From: chardster at gmail.com (Richard Thomas) Date: Fri, 11 Dec 2009 02:06:35 -0800 (PST) Subject: Variable class instantiation References: Message-ID: On Dec 11, 9:26?am, Jan Mach wrote: > Hi everybody, > I am currently solving the following problem and I am stuck. I am trying > to create instance of the class of variable name. I know, that the > following works: > > if (something): > ? ? classToUse = C1 > else: > ? ? classToUse = C2 > > o = classToUse() > > ,but this is not what I want. I need to have the class name in the string and then > instantiate it: > > (this does not work of course) > classToUse = "C1" > o = classToUse() > > It is because I don`t know at the moment what the name of the class will be, I will > load it from the file or pass it as argument. Does anyone know what is the correct syntax > to accomplish this? > > Thanks for your time in advance > > Jan Mach > > ?smime.p7s > 4KViewDownload You can always do eval(my_string) to get the class object. Better I think is to make an explicit dictionary of options (much safer). classes = dict((cls.__name__, cls) for cls in (C1, C2)) classes["C1"] # gives you C1 classes["C2"] # gives you C2 Richard. From steve at REMOVE-THIS-cybersource.com.au Fri Dec 11 05:09:17 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 11 Dec 2009 10:09:17 GMT Subject: Variable class instantiation References: Message-ID: <00ab9ee7$0$15654$c3e8da3@news.astraweb.com> On Fri, 11 Dec 2009 10:26:49 +0100, Jan Mach wrote: > I need to have the class name in the > string and then instantiate it: > > (this does not work of course) > classToUse = "C1" > o = classToUse() > > It is because I don`t know at the moment what the name of the class will > be, I will load it from the file or pass it as argument. Does anyone > know what is the correct syntax to accomplish this? Here are three solutions: # 1 classToUse = globals()['C1'] # 2 thisModule = __import__(__name__) classToUse = thisModule.__dict__['C1'] # 3 classToUse = eval('C1') The first solution is probably the best; the third is tempting, but dangerous if you can't absolutely trust the source of the string 'C1'. (Google "code injection" for more details on why eval is risky.) -- Steven From lie.1296 at gmail.com Fri Dec 11 05:10:48 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Fri, 11 Dec 2009 21:10:48 +1100 Subject: Variable class instantiation In-Reply-To: References: Message-ID: <4b221b34$1@dnews.tpgi.com.au> On 12/11/2009 8:26 PM, Jan Mach wrote: > Hi everybody, > I am currently solving the following problem and I am stuck. I am trying > to create instance of the class of variable name. I know, that the > following works: > > if (something): > classToUse = C1 > else: > classToUse = C2 > > o = classToUse() > > ,but this is not what I want. I need to have the class name in the string and then > instantiate it: > > (this does not work of course) > classToUse = "C1" > o = classToUse() > > It is because I don`t know at the moment what the name of the class will be, I will > load it from the file or pass it as argument. Does anyone know what is the correct syntax > to accomplish this? Make a dict of name->class, otherwise it's a security issue. A malicious user may pass a class you never wish to instantiate (with eval, it's even worse, malicious user can execute arbitrary code). From wentland at cl.uni-heidelberg.de Fri Dec 11 05:12:12 2009 From: wentland at cl.uni-heidelberg.de (Wolodja Wentland) Date: Fri, 11 Dec 2009 11:12:12 +0100 Subject: Which graph library is best suited for large graphs? Message-ID: <20091211101212.GC5712@kinakuta.local> Hi all, I am writing a library for accessing Wikipedia data and include a module that generates graphs from the Link structure between articles and other pages (like categories). These graphs could easily contain some million nodes which are frequently linked. The graphs I am building right now have around 300.000 nodes with an average in/out degree of - say - 4 and already need around 1-2GB of memory. I use networkx to model the graphs and serialise them to files on the disk. (using adjacency list format, pickle and/or graphml). The recent thread on including a graph library in the stdlib spurred my interest and introduced me to a number of libraries I have not seen before. I would like to reevaluate my choice of networkx and need some help in doing so. I really like the API of networkx but have no problem in switching to another one (right now) .... I have the impression that graph-tool might be faster and have a smaller memory footprint than networkx, but am unsure about that. Which library would you choose? This decision is quite important for me as the choice will influence my libraries external interface. Or is there something like WSGI for graph libraries? kind regards -- .''`. Wolodja Wentland : :' : `. `'` 4096R/CAF14EFC `- 081C B7CD FF04 2BA9 94EA 36B2 8B7F 7D30 CAF1 4EFC -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 836 bytes Desc: Digital signature URL: From sancar.saran at evodot.com Fri Dec 11 05:26:30 2009 From: sancar.saran at evodot.com (Sancar Saran) Date: Fri, 11 Dec 2009 12:26:30 +0200 Subject: Moving from PHP to Python. Is it Possible Message-ID: <200912111226.30240.sancar.saran@evodot.com> Greetings. I'm 35 yrs old self learner and who do daily PHP coding for food more than a decade. After ten years of PHP coding I'm getting bored and give try for learning new things. After 3 days of crawling google, diving in python and cursing, now I can show something on my linux/apache/mod_wsgi setup. And i'm struck on something. I had CMS design. It works with PHP very well. And I want to transfer my design in Python. My design depends on a Global Array. A huge array which store everything about requested Web page for a final rendering. In PHP accessing globals is easy. You may do direct access or use class something like ZEND Registry. I'm looking for similar facility in python world. Also I have couple of questions. 1-) Can I create Global (read/write access anywhere from my code) Multi dimensional, associative array (or hash) and store any kind of variable type. 2-) Is there any error trigger for mod_wsgi. When something go bad I god Internal Server error. Looking for error log was't nice. Is there any way to shows errors in the web page ? 3-) Any documents books sites about helping moving from php to python 4-) In php we had someting like ob_start(); // start Output buffering require('hede.php'); // include phtml similar to psp. mixed language and html (to avoiding string replacement (or marker based) html templates) $var = ob_get_clean(); // get rendered output and use anywhere can find a similar abilities in Python ? 5-) is there any Python documentation based on examples. When I give up about to finding php's $_REQUEST or $_SERVER equivalents in python some demo code in Twisted docs are much helpful than any other words. Me and my kind already have problem with English language. Example code much more helpful than full academic description. Thanks for support and patience for this old noob. Regards... From dickinsm at gmail.com Fri Dec 11 05:30:44 2009 From: dickinsm at gmail.com (Mark Dickinson) Date: Fri, 11 Dec 2009 02:30:44 -0800 (PST) Subject: which pi formula is given in the decimal module documentation? References: <4c88dd83-213c-49c0-8c36-d9058be24dc3@m7g2000prd.googlegroups.com> Message-ID: On Dec 11, 8:16?am, Anh Hai Trinh wrote: > I'm just curious which formula for pi is given here: docs.python.org/library/decimal.html#recipes>? > > def pi(): > ? ? """Compute Pi to the current precision. > > ? ? >>> print pi() > ? ? 3.141592653589793238462643383 > > ? ? """ > ? ? getcontext().prec += 2 ?# extra digits for intermediate steps > ? ? three = Decimal(3) ? ? ?# substitute "three=3.0" for regular > floats > ? ? lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24 > ? ? while s != lasts: > ? ? ? ? lasts = s > ? ? ? ? n, na = n+na, na+8 > ? ? ? ? d, da = d+da, da+32 > ? ? ? ? t = (t * n) / d > ? ? ? ? s += t > ? ? getcontext().prec -= 2 > ? ? return +s ? ? ? ? ? ? ? # unary plus applies the new precision > > It looks like an infinite series with term `t`, where`n` = (2k-1)^2 > and `d` = d = 4k(4k+2) for k = 1... Does it have a name? Interesting. So the general term here is 3 * (2k choose k) / (16**k * (2*k+1)), k >= 0. Python 3.2a0 (py3k:76334:76335, Nov 18 2009, 11:34:44) [GCC 4.0.1 (Apple Inc. build 5490)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> from math import factorial as f >>> 3*sum(f(2*k)/f(k)/f(k)/(2*k+1)/16**k for k in range(50)) 3.141592653589794 I've no idea what its name is or where it comes from, though. I expect Raymond Hettinger would know. -- Mark From lie.1296 at gmail.com Fri Dec 11 05:33:43 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Fri, 11 Dec 2009 21:33:43 +1100 Subject: plain text parsing to html (newbie problem) In-Reply-To: <861943af-a905-4254-9ff2-c8b42b56ff34@m25g2000yqc.googlegroups.com> References: <6664c88b-ec93-4b6c-a536-8a6b5959cd5e@a21g2000yqc.googlegroups.com> <35a19377-d2d4-4fb1-ad58-b999e0b9ff8f@u16g2000pru.googlegroups.com> <0f2e4a9a-284e-425f-9f02-045f32268d16@n35g2000yqm.googlegroups.com> <4b2152b7$1@dnews.tpgi.com.au> <861943af-a905-4254-9ff2-c8b42b56ff34@m25g2000yqc.googlegroups.com> Message-ID: <4b222093$1@dnews.tpgi.com.au> On 12/11/2009 8:43 PM, Jo?o wrote: > On Dec 10, 7:55 pm, Lie Ryan wrote: >> >> and, is there any reason why you're not using the email and smtplib?http://docs.python.org/library/email-examples.html > > Mainly because I was unaware of them :( > > I just read about them and I found all the Subject, From, To classes, > but what about Content-Type? > I need Content-Type: text/html and charset="utf-8" so that I can pass > a basic CSS formatting. > How can I do that? With email.mime.base.MIMEBase? You can set MIME type and encoding from the MIME constructor email.mime.Text.MIMEText("Bold Text", "html", "utf-8") > I'll have to update that in my code later, as I already got it to work > and my current RHEL5.3 default > Python 2.4.3 (#1, Sep 17 2008) install is complaining with > "ImportError: No module named mime.multipart" are you importing "import mime" or "import email.mime" or "import email.MIMEMultipart"? From fetchinson at googlemail.com Fri Dec 11 05:38:46 2009 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Fri, 11 Dec 2009 11:38:46 +0100 Subject: pyZui - anyone know about this? In-Reply-To: <200912110641.56775.donn.ingle@gmail.com> References: <200912110641.56775.donn.ingle@gmail.com> Message-ID: > Hi, > I happened upon this youtube link: > http://www.youtube.com/watch?v=57nWm984wdY > It fairly blew my socks off. In it a fellow by the name of David Roberts > demos > a zui written in Python. Aside from the zooming (which is impressive enough) > it show embedding of images, pdf files, web pages and text. > > He says nothing about what toolkits were used or how it might have been > done. > It's Linux-based, but no other info. On some googling, I can only find a few > bug reports on pypi related to pyQt. I would really like to find out how > that > ZUI was done, it's simply amazing. > > Any clues out there? Youtube has a link 'Send message' on the profile of users, maybe sending a message to the person who uploaded the video will give you a useful response. Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From dickinsm at gmail.com Fri Dec 11 05:43:47 2009 From: dickinsm at gmail.com (Mark Dickinson) Date: Fri, 11 Dec 2009 02:43:47 -0800 (PST) Subject: which pi formula is given in the decimal module documentation? References: <4c88dd83-213c-49c0-8c36-d9058be24dc3@m7g2000prd.googlegroups.com> Message-ID: On Dec 11, 10:30?am, Mark Dickinson wrote: > > It looks like an infinite series with term `t`, where`n` = (2k-1)^2 > > and `d` = d = 4k(4k+2) for k = 1... Does it have a name? > > Interesting. ?So the general term here is > 3 * (2k choose k) / (16**k * (2*k+1)), ?k >= 0. > > I've no idea what its name is or where it comes from, though. ?I > expect Raymond Hettinger would know. After a cup of coffee, it's much clearer: this just comes from the Taylor series for arcsin(x), applied to x = 1/2 to get asin(1/2) = pi/ 6. -- Mark From bearophileHUGS at lycos.com Fri Dec 11 06:03:03 2009 From: bearophileHUGS at lycos.com (Bearophile) Date: Fri, 11 Dec 2009 03:03:03 -0800 (PST) Subject: Which graph library is best suited for large graphs? References: Message-ID: <7c6c5804-acc1-4fbe-bdf4-238da730728f@d20g2000yqh.googlegroups.com> Wolodja Wentland: > Which library would you choose? This one probably uses low memory, but I don't know if it works still: http://osl.iu.edu/~dgregor/bgl-python/ Bye, bearophile From wentland at cl.uni-heidelberg.de Fri Dec 11 06:17:43 2009 From: wentland at cl.uni-heidelberg.de (Wolodja Wentland) Date: Fri, 11 Dec 2009 12:17:43 +0100 Subject: Which graph library is best suited for large graphs? In-Reply-To: <7c6c5804-acc1-4fbe-bdf4-238da730728f@d20g2000yqh.googlegroups.com> References: <7c6c5804-acc1-4fbe-bdf4-238da730728f@d20g2000yqh.googlegroups.com> Message-ID: <20091211111743.GE5712@kinakuta.local> On Fri, Dec 11, 2009 at 03:03 -0800, Bearophile wrote: > Wolodja Wentland: > > Which library would you choose? > > This one probably uses low memory, but I don't know if it works still: > http://osl.iu.edu/~dgregor/bgl-python/ That project looks not that maintained and graph-tool [1] is based on boost as well, so I don't see the advantage in choosing bgl-python over graph-tool. The point is, that I am not sure if using graph-tool has any advantages over networkx at all. It looks like a great library, supports filtered graphs which I find pretty useful, but have not used it yet. [1] http://projects.forked.de/graph-tool/ -- .''`. Wolodja Wentland : :' : `. `'` 4096R/CAF14EFC `- 081C B7CD FF04 2BA9 94EA 36B2 8B7F 7D30 CAF1 4EFC -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 836 bytes Desc: Digital signature URL: From donn.ingle at gmail.com Fri Dec 11 06:24:11 2009 From: donn.ingle at gmail.com (Donn) Date: Fri, 11 Dec 2009 13:24:11 +0200 Subject: pyZui - anyone know about this? In-Reply-To: References: <200912110641.56775.donn.ingle@gmail.com> Message-ID: <200912111324.11546.donn.ingle@gmail.com> On Friday 11 December 2009 12:38:46 Daniel Fetchinson wrote: > Youtube has a link 'Send message' on the profile of users, maybe > sending a message to the person who uploaded the video will give you a > useful response. > I'm a Tube-tard so that never crossed my mind. Will give it a go. \d From sion at viridian.paintbox Fri Dec 11 06:36:13 2009 From: sion at viridian.paintbox (Sion Arrowsmith) Date: Fri, 11 Dec 2009 11:36:13 GMT Subject: Variable class instantiation References: <00ab9ee7$0$15654$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: >thisModule = __import__(__name__) >classToUse = thisModule.__dict__['C1'] Any reason to prefer this over: classToUse = getattr(thisModule, 'C1') ? (I think, for a module, they should do exactly the same thing. Personally, I prefer keeping explicit references to __special names__ to a minimum.) -- \S under construction From steve at REMOVE-THIS-cybersource.com.au Fri Dec 11 06:40:14 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 11 Dec 2009 11:40:14 GMT Subject: Variable class instantiation References: <00ab9ee7$0$15654$c3e8da3@news.astraweb.com> Message-ID: <00abb437$0$15654$c3e8da3@news.astraweb.com> On Fri, 11 Dec 2009 11:36:13 +0000, Sion Arrowsmith wrote: > Steven D'Aprano wrote: >>thisModule = __import__(__name__) >>classToUse = thisModule.__dict__['C1'] > > Any reason to prefer this over: > > classToUse = getattr(thisModule, 'C1') > > ? (I think, for a module, they should do exactly the same thing. > Personally, I prefer keeping explicit references to __special names__ to > a minimum.) No, no reason at all. I just forgot about getttr. -- Steven From contact at xavierho.com Fri Dec 11 07:07:36 2009 From: contact at xavierho.com (Xavier Ho) Date: Fri, 11 Dec 2009 22:07:36 +1000 Subject: Overriding the >> builtin In-Reply-To: References: Message-ID: <2d56febf0912110407p49dcf5a6qec61be27c6c8ff3e@mail.gmail.com> On Fri, Dec 11, 2009 at 12:05 PM, Kevin Ar18 wrote: > I am aware of the fact that you can somehow replace the __builtins__ in > Python. There is a library here that modifies the >> binary builtins: > http://github.com/aht/stream.py/blob/master/stream.py > > Question: Is there anywhere that explains in detail how to modify the > builtins in Python like this library did? > I did some google and I didn't find anything useful, either. The unofficial doc on effbot.org gives "See __add__", which is fair enough. I believe you're after __rshift__ [that is >>], __lshift__ [which is <<], as starters. There are also __rrshift__ and __rlshift__, but not as useful. What did you need this anyway? Just curious. Cheers, Xav -------------- next part -------------- An HTML attachment was scrubbed... URL: From jeanmichel at sequans.com Fri Dec 11 07:29:42 2009 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Fri, 11 Dec 2009 13:29:42 +0100 Subject: accessing local variables from the pdb debugger In-Reply-To: <4b216287$1@dnews.tpgi.com.au> References: <7oc9u8F3onimoU1@mid.uni-berlin.de> <4b216287$1@dnews.tpgi.com.au> Message-ID: <4B223B36.4090305@sequans.com> Lie Ryan wrote: > On 12/11/2009 12:37 AM, Jean-Michel Pichavant wrote: >> Diez B. Roggisch wrote: >> By just inserting the print foo statement right after changing foo's >> value, I've rolled back the value to 'foo' ??? A hell of a wtf pdb >> feature ! > > Apparently it's fixed in 2.7 and 3.1 > > D:\Lie Ryan\Desktop>python27 d.py > > d:\lie ryan\desktop\d.py(6)test() > -> print(foo) > (Pdb) foo = "bar" > (Pdb) pp foo > 'bar' > (Pdb) c > bar > > D:\Lie Ryan\Desktop>python27 d.py > > d:\lie ryan\desktop\d.py(6)test() > -> print(foo) > (Pdb) foo = "bar" > (Pdb) c > bar > Thanks, that could mean it is a bug from pdb in python 2.5. I tried with ipython & python, same issue. I'll keep that in mind, sadly it concerns a basic feature of the debugger. JM From d.dalton at iinet.net.au Fri Dec 11 07:41:39 2009 From: d.dalton at iinet.net.au (Daniel Dalton) Date: Fri, 11 Dec 2009 23:41:39 +1100 Subject: Best way to conduct a google search Message-ID: <20091211124139.GA28813@debian-hp.lan> Hi, I need to do the following in my program: 1. Conduct a google search, supplying the variable "text" to the search. Is there a google api or something similar I should use? 2. I then need to be able to get the url, of the page, or the html content, so I can dump it to text. Thanks, Dan -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 198 bytes Desc: Digital signature URL: From dickinsm at gmail.com Fri Dec 11 07:49:19 2009 From: dickinsm at gmail.com (Mark Dickinson) Date: Fri, 11 Dec 2009 04:49:19 -0800 (PST) Subject: which pi formula is given in the decimal module documentation? References: <4c88dd83-213c-49c0-8c36-d9058be24dc3@m7g2000prd.googlegroups.com> Message-ID: <3ca936a7-03c3-4451-ae46-f2e31a006dfa@g7g2000yqa.googlegroups.com> On Dec 11, 8:16?am, Anh Hai Trinh wrote: > I'm just curious which formula for pi is given here: docs.python.org/library/decimal.html#recipes>? > > def pi(): > ? ? """Compute Pi to the current precision. > > ? ? >>> print pi() > ? ? 3.141592653589793238462643383 > > ? ? """ > ? ? getcontext().prec += 2 ?# extra digits for intermediate steps > ? ? three = Decimal(3) ? ? ?# substitute "three=3.0" for regular > floats > ? ? lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24 > ? ? while s != lasts: > ? ? ? ? lasts = s > ? ? ? ? n, na = n+na, na+8 > ? ? ? ? d, da = d+da, da+32 > ? ? ? ? t = (t * n) / d > ? ? ? ? s += t > ? ? getcontext().prec -= 2 > ? ? return +s ? ? ? ? ? ? ? # unary plus applies the new precision And just for fun, here's a one-liner (well, okay, two lines including the import) that uses Decimal to print the first 28 digits of pi: Python 2.6.4 (r264:75706, Nov 16 2009, 15:42:08) [GCC 4.0.1 (Apple Inc. build 5490)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> from decimal import Decimal as D >>> print reduce(lambda x,k:2+k/2*x/k,range(999,1,-2),D()) 3.141592653589793238462643383 -- Mark From deets at nospam.web.de Fri Dec 11 07:54:46 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 11 Dec 2009 13:54:46 +0100 Subject: no module named error In-Reply-To: References: <7o78kuF3p45l7U1@mid.uni-berlin.de> <7o79huF3l4v9uU1@mid.uni-berlin.de> <7o7h4mF3o100mU1@mid.uni-berlin.de> <7o7jvbF3ojs9uU1@mid.uni-berlin.de> <7ocjc2F3o5t6iU1@mid.uni-berlin.de> Message-ID: <7oetomF3pkupbU1@mid.uni-berlin.de> Joe schrieb: >> Your installation process is botched (no idea why, you don't show us >> setup.py or anything else I asked for). > > Sorry, but I do know how it's currently installed is exactly the way I > need it to be installed. It is? It wasn't working until you fiddled with sys.path - which you needed help to find out. How's that exactly the way it is needed? > >> >> All that is missing is what I've asked you now several times before: >> _moda.so is *NOT* alongside moda.py inside your python's site-packages >> directory. Copy it in there, and the import will work *without* any >> sys.path-hackery. > > Yeah, that's something I don't want to do. But you've given me enough > info to help me understand what's going on and how to fix it. Thanks. So it's ok that the installation copies moda.py, but not that it copies _moda.so to the same destination? Looks all very strange to me. But then - it's your system. Glad it works for you. Diez From frank at chagford.com Fri Dec 11 08:27:22 2009 From: frank at chagford.com (Frank Millman) Date: Fri, 11 Dec 2009 15:27:22 +0200 Subject: Question about 'remote objects' References: Message-ID: Frank Millman wrote: > > I am writing a multi-user business/accounting application. It is getting > rather complex and I am looking at how to, not exactly simplify it, but > find a way to manage the complexity. > [...] > > Is there any particular benefit in using remote objects as opposed to > writing a SocketServer? > Many thanks for the very useful replies. Irmen - thanks for clearing up my misconception about how Pyro works. This is still definitely an option. Diez - plenty of food for thought. Your cautionary tale about premature optimisation is salutary. J Kenneth King - also plenty of food for thought, but in fact the most important part of your post was the following - - Find the clear boundaries of each component. - Build an API along those boundaries. - Add a network layer in front of the boundaries. I should know this, but I confess I do need reminding. I had a useful brainstorming session with a colleague this morning focussing on this, and this is where I shall concentrate my attention for the next few days. I suspect that, once this has become clearer, it will not matter much whether I use remote objects, write a SocketServer, or keep it all on one machine. I really appreciate the feedback - it helps a lot. Frank From solipsis at pitrou.net Fri Dec 11 08:52:33 2009 From: solipsis at pitrou.net (Antoine Pitrou) Date: Fri, 11 Dec 2009 13:52:33 +0000 (UTC) Subject: Recommendation for small, fast, Python based web server References: <1260387281.5558.1349282363@webmail.messagingengine.com> Message-ID: Hello, > I've looked at the web servers that come bundled with the Python > standard library[1] and they are too slow. Apparently you have debugged your speed issue so I suppose you don't have performance problems anymore. Do note, however, that Python is generally not as fast as C -- especially for low-level stuff -- and a Python Web server will probably serve around 10x less requests per second than a C Web server like Apache (this will still give you hundreds of simple requests per second on a modern machine). In any case, as far as functionality, robustness, portability and community support are concerned, you probably can't go wrong with Twisted. Regards Antoine. From ndbecker2 at gmail.com Fri Dec 11 08:55:19 2009 From: ndbecker2 at gmail.com (Neal Becker) Date: Fri, 11 Dec 2009 08:55:19 -0500 Subject: Which graph library is best suited for large graphs? References: <7c6c5804-acc1-4fbe-bdf4-238da730728f@d20g2000yqh.googlegroups.com> Message-ID: Bearophile wrote: > Wolodja Wentland: >> Which library would you choose? > > This one probably uses low memory, but I don't know if it works still: > http://osl.iu.edu/~dgregor/bgl-python/ > > Bye, > bearophile How about python interface to igraph? From solipsis at pitrou.net Fri Dec 11 09:00:46 2009 From: solipsis at pitrou.net (Antoine Pitrou) Date: Fri, 11 Dec 2009 14:00:46 +0000 (UTC) Subject: a huge shared read-only data in parallel accesses -- How? multithreading? multiprocessing? References: Message-ID: Le Wed, 09 Dec 2009 06:58:11 -0800, Valery a ?crit?: > > I have a huge data structure that takes >50% of RAM. My goal is to have > many computational threads (or processes) that can have an efficient > read-access to the huge and complex data structure. > > "Efficient" in particular means "without serialization" and "without > unneeded lockings on read-only data" I was going to suggest memcached but it probably serializes non-atomic types. It doesn't mean it will be slow, though. Serialization implemented in C may well be faster than any "smart" non-serializing scheme implemented in Python. > 2. multi-threading > => d. CPython is told to have problems here because of GIL -- any > comments? What do you call "problems because of the GIL"? It is quite a vague statement, and an answer would depend on your OS, the number of threads you're willing to run, and whether you want to extract throughput from multiple threads or are just concerned about latency. In any case, you have to do some homework and compare the various approaches on your own data, and decide whether the numbers are satisfying to you. > I am a big fan of parallel map() approach I don't see what map() has to do with accessing data. map() is for *processing* of data. In other words, whether or not you use a map()-like primitive does not say anything about how the underlying data should be accessed. From wentland at cl.uni-heidelberg.de Fri Dec 11 09:07:41 2009 From: wentland at cl.uni-heidelberg.de (Wolodja Wentland) Date: Fri, 11 Dec 2009 15:07:41 +0100 Subject: Which graph library is best suited for large graphs? In-Reply-To: References: <7c6c5804-acc1-4fbe-bdf4-238da730728f@d20g2000yqh.googlegroups.com> Message-ID: <20091211140741.GF5712@kinakuta.local> On Fri, Dec 11, 2009 at 08:55 -0500, Neal Becker wrote: > Bearophile wrote: > > Wolodja Wentland: > >> Which library would you choose? > > This one probably uses low memory, but I don't know if it works still: > > http://osl.iu.edu/~dgregor/bgl-python/ > How about python interface to igraph? Don't know :-) as I have not yet worked with it. Why do you recommend it? -- .''`. Wolodja Wentland : :' : `. `'` 4096R/CAF14EFC `- 081C B7CD FF04 2BA9 94EA 36B2 8B7F 7D30 CAF1 4EFC -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 836 bytes Desc: Digital signature URL: From marc.wyburn at googlemail.com Fri Dec 11 09:12:11 2009 From: marc.wyburn at googlemail.com (marc wyburn) Date: Fri, 11 Dec 2009 06:12:11 -0800 (PST) Subject: Active Directory ADO strange objects returned Message-ID: <0a3d058e-7096-41bd-9dc3-f29f33d1d762@m38g2000yqd.googlegroups.com> Hi, I have a script that returns data from active directory using ADO. Everything works except for any fields that use a time value I get an instance of an object returned called . I know it's a time object because if I do object.HighPart or object.LowPart I get a value back. The bit I don't understand is how I inspect the object to work out what it is programmatically. Do I need to do some sort of makepy trickery so that the object is understood by Python? I have already makepy'd MS ActiveX Data Object 2.8. thanks, Marc. From kw at codebykevin.com Fri Dec 11 09:43:59 2009 From: kw at codebykevin.com (Kevin Walzer) Date: Fri, 11 Dec 2009 09:43:59 -0500 Subject: Python tricks with applescript in OS-X In-Reply-To: References: Message-ID: <445d6$4b225ab5$4275d90a$24371@FUSE.NET> On 12/11/09 3:13 AM, joanmg at gmail.com wrote: > Greetings, > > I've written a short document with some working examples of how to > interface python with other applications in OS-X via applescript (had > to spend some time figuring it out, and thought I might as well write > it down). The examples include asking Google Earth for the latitude > and longitude of the point at the center of its screen, or using the > finder to pop-up a dialog window to get input from the user: > > http://juanreyero.com/article/python/os-x-python.html > > Cheers, > > Juan > http://juanreyero.com Thanks for these examples. There is also a Python package that allows you to interface with an application's AppleScript dictionary via Python itself, without the intermediate step of using the osascript command-line tool: http://appscript.sourceforge.net/ You might find that of interest. --Kevin -- Kevin Walzer Code by Kevin http://www.codebykevin.com From patrol at invisibleroads.com Fri Dec 11 09:47:13 2009 From: patrol at invisibleroads.com (InvisibleRoads Patrol) Date: Fri, 11 Dec 2009 08:47:13 -0600 Subject: extending dictonary In-Reply-To: References: Message-ID: On Sat, 21 Nov 2009 09:25:38 +0100, nospam <"knutjbj(nospam)"@online.no> wrote: > Is there any way to extend the dictonary in such manner that I can > insert muliplay value to each keys and return one of the value as the > default value. I would like to have similar syste that I drawed out below. > > > tree[nucelotide_postionc][nucleotide]=default(value subtree) This should > be returned when doing lookup without any > tree[nucelotide_postionc][nucleotide]=Postive value > tree[nucelotide_postionc][nucleotide]=Negative value You could use the collections.defaultdict method. >>> import collections >>> example1 = collections.defaultdict(int) >>> example1[1] 0 >>> example2 = collections.defaultdict(list) >>> example2[1] [] >>> example3 = collections.defaultdict(dict) >>> example3[1] {} >>> # Make nested default dictionary >>> def getNewOuterDictionary(): ... return collections.defaultdict(getNewInnerDictionary) >>> def getNewInnerDictionary(): ... return collections.defaultdict([]) >>> example4[1][1] [] Hope that helps. -- Roy Hyunjin Han http://invisibleroads.com Training people to become software developers and connecting them to jobs and projects for local businesses From patrol at invisibleroads.com Fri Dec 11 09:58:28 2009 From: patrol at invisibleroads.com (InvisibleRoads Patrol) Date: Fri, 11 Dec 2009 08:58:28 -0600 Subject: extending dictonary In-Reply-To: References: Message-ID: On Sat, 21 Nov 2009 09:25:38 +0100, nospam <"knutjbj(nospam)"@online.no> wrote: > Is there any way to extend the dictonary in such manner that I can > insert muliplay value to each keys and return one of the value as the > default value. I would like to have similar syste that I drawed out below. > > > tree[nucelotide_postionc][nucleotide]=default(value subtree) This should > be returned when doing lookup without any > tree[nucelotide_postionc][nucleotide]=Postive value > tree[nucelotide_postionc][nucleotide]=Negative value You could use the collections.defaultdict method. >>> >>> import collections >>> >>> example1 = collections.defaultdict(int) >>> >>> example1[1] 0 >>> >>> example2 = collections.defaultdict(list) >>> >>> example2[1] [] >>> >>> example3 = collections.defaultdict(dict) >>> >>> example3[1] {} >>> >>> # Make nested default dictionary >>> >>> def getNewOuterDictionary(): ... return collections.defaultdict(getNewInnerDictionary) >>> >>> def getNewInnerDictionary(): ... return collections.defaultdict([]) >>> >>> example4[1][1] [] Hope that helps. -- Roy Hyunjin Han http://invisibleroads.com We train people to become software developers and connect them to jobs and projects for local businesses. From zephjc at gmail.com Fri Dec 11 10:11:12 2009 From: zephjc at gmail.com (zeph) Date: Fri, 11 Dec 2009 07:11:12 -0800 (PST) Subject: Moving from PHP to Python. Is it Possible References: Message-ID: <3c4778e3-e31a-4484-ae9a-f6d5b737fa68@x25g2000prf.googlegroups.com> Hi Sancar, 1) PHP does some really nasty things in how it treats globals, and you will have to break yourself of those sorts of habits -- Python offers much cleaner alternatives, like grouping similar functionality into modules which can be imported; the import functionality in python is pretty flexible. Python won't pack a ton of garbage into a giant, global 'dictionary' (what python calls associative arrays). There are modules (bundled of code) which you can import to handle your needs. 2) Check out the traceback[1] module for retrieving the traceback info for logging to a file, and cgitb[2] modules for printing the traceback as HTML to your browser. 3) http://docs.python.org/ is a great place to start - it has a lot of well written and generally thorough documentation with examples 4) It's better to collect all your eventual output into a string that you print - there are examples at [3]. You can import from other modules as needed (even conditionally), grow your string for output, then finally print it like (this example was adapted from one found on [3]): output = '' output += 'My Page' output += '' output += '

Powers of two

\n
    ' for n in range(1,11): output += '
  1. '+str(2**n)+'
  2. ' output += '
' print output You can copy-paste this right into your Python interactive shell to see the output. Note: += is inline string concatenation. 5) You can get form state from the cgi module[4] and FormStorage object, and you can get server environment data from the os.environ[5] dictionary; Good luck and keep on learning! :-) - zeph References: 1: http://docs.python.org/library/traceback.html 2: http://docs.python.org/library/cgitb.html 3: http://gnosis.cx/publish/programming/feature_5min_python.html 4: http://docs.python.org/library/cgi.html 5: http://docs.python.org/library/os.html#process-parameters From joaopcf at gmail.com Fri Dec 11 10:22:49 2009 From: joaopcf at gmail.com (=?ISO-8859-1?Q?Jo=E3o?=) Date: Fri, 11 Dec 2009 07:22:49 -0800 (PST) Subject: plain text parsing to html (newbie problem) References: <6664c88b-ec93-4b6c-a536-8a6b5959cd5e@a21g2000yqc.googlegroups.com> <35a19377-d2d4-4fb1-ad58-b999e0b9ff8f@u16g2000pru.googlegroups.com> <0f2e4a9a-284e-425f-9f02-045f32268d16@n35g2000yqm.googlegroups.com> <4b2152b7$1@dnews.tpgi.com.au> <861943af-a905-4254-9ff2-c8b42b56ff34@m25g2000yqc.googlegroups.com> <4b222093$1@dnews.tpgi.com.au> Message-ID: <90cfab6c-f91b-453e-9e82-83508f4ff358@c3g2000yqd.googlegroups.com> Lie Ryan wrote: > You can set MIME type and encoding from the MIME constructor > email.mime.Text.MIMEText("Bold Text", "html", "utf-8") > > are you importing "import mime" or "import email.mime" or "import > email.MIMEMultipart"? Hi Lie. I was importing as, 'from email.mime.text import MIMEText' which was returning that error because I don't have a mime subdir in my /usr/lib64/python2.4/email/ as I was expecting. 'import email.MIMEMultipart' worked perfectly (the mime methods are in the /email/ root). I'll try to redo my script right after I get some urgent things done. Thanks :) From ingoogni at gmail.com Fri Dec 11 10:31:18 2009 From: ingoogni at gmail.com (IngoognI) Date: Fri, 11 Dec 2009 07:31:18 -0800 (PST) Subject: Which graph library is best suited for large graphs? References: Message-ID: On Dec 11, 11:12?am, Wolodja Wentland wrote: > > Which library would you choose? looking at the galery at networx, it seems to be all balls 'n sticks, how about writing the data to a file POV-Ray can read and render it there? From stefan_ml at behnel.de Fri Dec 11 10:46:03 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Fri, 11 Dec 2009 16:46:03 +0100 Subject: C to Python In-Reply-To: References: <89c38c820912100301r7c31b434k466b8a6f4d394ae5@mail.gmail.com> Message-ID: <4b22693b$0$7628$9b4e6d93@newsspool1.arcor-online.net> Benjamin Peterson, 10.12.2009 20:26: > Emeka writes: >> I am finding it difficult getting my head around PyObject_CallObject(x,y). I > need a gentle and thorough introduction to it. I also need examples. Could > someone come to my need? > > PyObject_CallFunction is probably easier to use. Hmm, I didn't see the original e-mail, but when it comes to "easier to use", I think the answer is basically Cython. http://cython.org Stefan From wentland at cl.uni-heidelberg.de Fri Dec 11 11:04:31 2009 From: wentland at cl.uni-heidelberg.de (Wolodja Wentland) Date: Fri, 11 Dec 2009 17:04:31 +0100 Subject: Which graph library is best suited for large graphs? In-Reply-To: References: Message-ID: <20091211160431.GG5712@kinakuta.local> On Fri, Dec 11, 2009 at 07:31 -0800, IngoognI wrote: > On Dec 11, 11:12?am, Wolodja Wentland > wrote: > > Which library would you choose? > > looking at the galery at networx, it seems to be all balls 'n sticks, > how about writing the data to a file POV-Ray can read and render it > there? Huh? I am not really concerned about rendering the graphs but after a library with a small memory footprint. Preferably one that contains a number of typical algorithms. -- .''`. Wolodja Wentland : :' : `. `'` 4096R/CAF14EFC `- 081C B7CD FF04 2BA9 94EA 36B2 8B7F 7D30 CAF1 4EFC -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 836 bytes Desc: Digital signature URL: From ndbecker2 at gmail.com Fri Dec 11 11:57:38 2009 From: ndbecker2 at gmail.com (Neal Becker) Date: Fri, 11 Dec 2009 11:57:38 -0500 Subject: Which graph library is best suited for large graphs? References: <7c6c5804-acc1-4fbe-bdf4-238da730728f@d20g2000yqh.googlegroups.com> <20091211140741.GF5712@kinakuta.local> Message-ID: Wolodja Wentland wrote: > On Fri, Dec 11, 2009 at 08:55 -0500, Neal Becker wrote: >> Bearophile wrote: >> > Wolodja Wentland: >> >> Which library would you choose? > >> > This one probably uses low memory, but I don't know if it works still: >> > http://osl.iu.edu/~dgregor/bgl-python/ > >> How about python interface to igraph? > > Don't know :-) as I have not yet worked with it. Why do you recommend it? My understanding is that igraph is a high performance graph library (all implemented in C). It seems to have a very active user community. There is also boost graph library, which IIRC also has a python interface. From python at mrabarnett.plus.com Fri Dec 11 11:58:26 2009 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 11 Dec 2009 16:58:26 +0000 Subject: Moving from PHP to Python. Is it Possible In-Reply-To: <3c4778e3-e31a-4484-ae9a-f6d5b737fa68@x25g2000prf.googlegroups.com> References: <3c4778e3-e31a-4484-ae9a-f6d5b737fa68@x25g2000prf.googlegroups.com> Message-ID: <4B227A32.9060300@mrabarnett.plus.com> zeph wrote: [snip] > 4) It's better to collect all your eventual output into a string that > you print - there are examples at [3]. You can import from other > modules as needed (even conditionally), grow your string for output, > then finally print it like (this example was adapted from one found on > [3]): > > output = '' > output += 'My Page' > output += '' > output += '

Powers of two

\n
    ' > for n in range(1,11): > output += '
  1. '+str(2**n)+'
  2. ' > > output += '
' > print output > > > You can copy-paste this right into your Python interactive shell to > see the output. Note: += is inline string concatenation. > It's better to put the strings into a list and then concatenate them in one go: output = [''] output.append('My Page') output.append('') output.append('

Powers of two

\n
    ') for n in range(1, 11): output.append('
  1. %s
  2. ' % (2 ** n)) output.append('
') print ''.join(output) From sancar.saran at evodot.com Fri Dec 11 12:04:05 2009 From: sancar.saran at evodot.com (Sancar Saran) Date: Fri, 11 Dec 2009 19:04:05 +0200 Subject: Moving from PHP to Python. Is it Possible In-Reply-To: <3c4778e3-e31a-4484-ae9a-f6d5b737fa68@x25g2000prf.googlegroups.com> References: <3c4778e3-e31a-4484-ae9a-f6d5b737fa68@x25g2000prf.googlegroups.com> Message-ID: <200912111904.05515.sancar.saran@evodot.com> On Friday 11 December 2009 05:11:12 pm zeph wrote: > Hi Sancar, Hi zeph, Thanks for reply. And here my needs about those 2 two programming technique. > 1) PHP does some really nasty things in how it treats globals, and you > will have to break yourself of those sorts of habits -- Python offers > much cleaner alternatives, like grouping similar functionality into > modules which can be imported; the import functionality in python is > pretty flexible. > Python won't pack a ton of garbage into a giant, global > 'dictionary' (what python calls associative arrays). There are > modules (bundled of code) which you can import to handle your needs. PHP was doing tons of nasty things. 10 years after I'm starting to understand some those and still not understand most programmers point of view to GLOBALS are evil. Anyhow I'm self learner plus I got heavy English limitation or probably I'm too narrow minded to see right thing. In my usage GLOBALS are too much useful to discard it. Anyway, I need to save my lots and lots of config variables in dictionary style global accessible location. Because. In my design We got lots of plugins, and those plugins may show in multiple times and multiple locations in a page. Each plugin may have setup values to affect entire page output. Because of this. I have to put those values in global location for future use. Is it possible If so ? how ? Is there any way to access directly or I have to wrote some kind of class like acting Windows registry in global scope ? > 2) Check out the traceback[1] module for retrieving the traceback info > for logging to a file, and cgitb[2] modules for printing the traceback > as HTML to your browser. > > 3) http://docs.python.org/ is a great place to start - it has a lot of > well written and generally thorough documentation with examples > > 4) It's better to collect all your eventual output into a string that > you print - there are examples at [3]. You can import from other > modules as needed (even conditionally), grow your string for output, > then finally print it like (this example was adapted from one found on > [3]): > > output = '' > output += 'My Page' > output += '' > output += '

Powers of two

\n
    ' > for n in range(1,11): > output += '
  1. '+str(2**n)+'
  2. ' > > output += '
' > print output > > > You can copy-paste this right into your Python interactive shell to > see the output. Note: += is inline string concatenation. Yes, I'm aware about this usage. We got similar syntax in php. Problem is we cannot give this kind of structure to our html designers. In php world our fine solution was using phtml mixed files for templates. It has two benefits. 1-) You dont need to string replace in templates (like in marker based templates) 2-) with php opcode caches your template will stored in ram. I believe second benefit was not available in python and my point of view escaping string replacement was good for performance. So My question is. For example I had this kind of python file and we want to use this as plugin template
<% for n in range(3): # This indent will persist %>

This paragraph will be repeated 3 times.

<% # This line will cause the block to end %> This line will only be shown once.
on execution time, I want to import this template file, execute as python script and store output in a GLOBAL dictionary for later usage. Is it possible ? > > 5) You can get form state from the cgi module[4] and FormStorage > object, and you can get server environment data from the os.environ[5] > dictionary; > > Good luck and keep on learning! :-) > > - zeph > > > References: > 1: http://docs.python.org/library/traceback.html > 2: http://docs.python.org/library/cgitb.html > 3: http://gnosis.cx/publish/programming/feature_5min_python.html > 4: http://docs.python.org/library/cgi.html > 5: http://docs.python.org/library/os.html#process-parameters > And thanks for those links. Regards... From mr.porteiro.head at gmail.com Fri Dec 11 12:07:27 2009 From: mr.porteiro.head at gmail.com (bobnotbob) Date: Fri, 11 Dec 2009 09:07:27 -0800 (PST) Subject: Virtual file for subprocess Message-ID: I am calling external executable from my python program (using subprocess). This external program's output is a text file which I then read and parse. Is there any way to "sandbox" the calling of this external program so that it writes to a virtual file instead of the hardcoded text? From robin at reportlab.com Fri Dec 11 12:45:24 2009 From: robin at reportlab.com (Robin Becker) Date: Fri, 11 Dec 2009 17:45:24 +0000 Subject: eiger replacement? Message-ID: <4B228534.90508@chamonix.reportlab.co.uk> The current hardware CPU: Intel(R) Pentium(R) 4 CPU 2.40GHz (2394.01-MHz 686-class CPU) Device Model: Hitachi HDT725025VLAT80 Serial Number: VF1100R107LS4K Firmware Version: V5DOA42A User Capacity: 250,059,350,016 bytes available here http://www.kikatek.com/product_info.php?products_id=18618&source=froogle. real memory = 1073168384 (1023 MB) The machine is Dell PowerEdge 400SC. Memory will cost about ?78 for a 2Gb upgrade kit. -- Robin Becker From sraji.me at gmail.com Fri Dec 11 12:56:23 2009 From: sraji.me at gmail.com (Raji Seetharaman) Date: Fri, 11 Dec 2009 23:26:23 +0530 Subject: When to use mechanize and Windmill library during WebScraping ? Message-ID: <23e3fbb60912110956q2716f7dbk35b7da7fea14dcaa@mail.gmail.com> Hi For 'Webscraping with Python' mechanize or urllib2 and windmill or selenium libraries are used to download the webpages. http://www.packtpub.com/article/web-scraping-with-python The above link makes use of mechanize library to download the web pages. The below link uses windmill library to download the web pages. http://www.packtpub.com/article/web-scraping-with-python-part-2 I dont know when to use mechanize or windmill library It has been said that Windmill library is used when the HTML file is auto generated by the JavaScript code. Also i dont know how to identify whether the HTML file is auto generated by the JavaScript code or not ? Suggest me Thanks Raji. S http://sraji.wordpress.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From bryanvick at gmail.com Fri Dec 11 13:03:06 2009 From: bryanvick at gmail.com (Bryan) Date: Fri, 11 Dec 2009 10:03:06 -0800 (PST) Subject: Using hash to see if object's attributes have changed Message-ID: <9e670042-394f-43bb-8b97-2a14346a64ab@o9g2000prg.googlegroups.com> When a user submits a request to update an object in my web app, I make the changes in the DB, along w/ who last updated it and when. I only want to update the updated/updatedBy columns in the DB if the data has actually changed however. I'm thinking of having the object in question be able to return a list of its values that constitute its state. Then I can take a hash of that list as the object exists in the database before the request, and then on the object that the user has made changes to. If they are not equal, the user has changed the object. I imagine it working something like this: def getValues(obj): return [obj.a, obj.b, obj.c] foo = Obj() foo.a = foo.b = foo.c = 1 stateBefore = hashlib.sha1(str(getValues(foo))) foo.b = 'changed' stateNow = hashlib.sha1(str(getValues(foo))) assert stateBefore != stateNow I originally thought about running the hash on the __dict__ attribute, but there may be things in there that don't actually constitute the object's state as far as the database is concerned, so I thought it better to have each object be responsible for returning a list of values that constitute its state as far as the DB is concerned. I would appreciate any insight into why this is a good/bad idea given your past experiences. From tjreedy at udel.edu Fri Dec 11 13:06:01 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 11 Dec 2009 13:06:01 -0500 Subject: ANN: WHIFF.0.7 += GAE + jQueryUI + internationalization + testdrive = (last beta?) In-Reply-To: <34fef074-beaf-4bc0-9251-08dbfbd43d98@u7g2000yqm.googlegroups.com> References: <954766b0-3b3e-47d6-943e-364d34a619af@v30g2000yqm.googlegroups.com> <34fef074-beaf-4bc0-9251-08dbfbd43d98@u7g2000yqm.googlegroups.com> Message-ID: Aaron Watters wrote: >> That was a joke in the tree view. You clicked on the "science link" >> in the tree hierarchy. I will fix it due to your complaint. > > Fixed. Now clicking on the same link goes to "Scientific American". Perhaps I was not clear enough. I am using FireFox 3.5 with Flashblock which blocks Flash content until one clicks twice on the space to explicitly open the Flash content. When I clicked on the space for your OpenFlashChart example, that is when the new window opended up, without warning, before I even saw the chart. I cannot reproduce this now because the chart seems to be in the local cache. If I had clcked on the link that is formatted as a link, that would have been a different matter, and I would have merely suggested a change such as the one you made, which I do approve of. Terry Jan Reedy From victorsubervi at gmail.com Fri Dec 11 13:08:29 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Fri, 11 Dec 2009 14:08:29 -0400 Subject: MySQL set and enum, calling values Message-ID: <4dc0cfea0912111008x5fb47e8dv5a9091cbe67ec4c8@mail.gmail.com> Hi; I have the following code: cursor.execute('describe %s;' % store) colFields, colFieldValues = [itm[0] for itm in cursor], [itm[1] for itm in cursor] ... for col in colFields: ... print '%s: %s
\n' % (col, colValue[0]) Don't worry about the colValue[0]. In fact, the code throws no errors. However, when colValue[0] (which is called from the MySQL table) is a set as opposed to, say, a string, it prints out: Set([]) which is natural, because there isn't anything in the set. What I'm trying to accomplish, however, is to offer a select of the possible values of that set as are available from the describe and caught in the tuple colFieldValues. For example, if I go to print, say, colFieldValues[20], which is a set, it prints out the whole set: set('Extra-small','Small','Medium','Large','XLarge','XXLarge','XXXLarge') But if I print out colFieldValues[20][0], it prints out "s". Now, I suppose I could do something like lop off the ends of colFieldValues[20] thus: tmp = string.split(colFieldValues[20][4:-2], "','") but boy that's inelegant! Any better suggestions? Also, how can I test for it? It's an instance of string. How do I know if it's a set? TIA, Victor -------------- next part -------------- An HTML attachment was scrubbed... URL: From robert.kern at gmail.com Fri Dec 11 13:17:00 2009 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 11 Dec 2009 12:17:00 -0600 Subject: Using hash to see if object's attributes have changed In-Reply-To: <9e670042-394f-43bb-8b97-2a14346a64ab@o9g2000prg.googlegroups.com> References: <9e670042-394f-43bb-8b97-2a14346a64ab@o9g2000prg.googlegroups.com> Message-ID: On 2009-12-11 12:03 PM, Bryan wrote: > When a user submits a request to update an object in my web app, I > make the changes in the DB, along w/ who last updated it and when. I > only want to update the updated/updatedBy columns in the DB if the > data has actually changed however. > > I'm thinking of having the object in question be able to return a list > of its values that constitute its state. Then I can take a hash of > that list as the object exists in the database before the request, and > then on the object that the user has made changes to. If they are not > equal, the user has changed the object. It *might* work, but probably won't be robust especially as you are relying on the string representation. You would be much better off using an ORM, which will do all of this for you. This is exactly what they are for. They usually determine whether attributes have change by instrumentation rather than inspection. If you still don't want to use a full ORM, you should at least emulate that strategy. Add descriptors to your classes for each attribute you want to map to a column. On __set__, they should compare the new value to the old, and set a "dirty" flag if the the attribute changes value. Or just implement __setattr__ on your classes to do a similar check. -- 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 Dec 11 13:21:49 2009 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 11 Dec 2009 12:21:49 -0600 Subject: switch In-Reply-To: <87638ekxdq.fsf@castleamber.com> References: <335204.99872.qm@web57905.mail.re3.yahoo.com> <68e6e315-f3c7-4e52-a56f-802e99d75e6a@y32g2000prd.googlegroups.com> <9010003a-d129-46b4-9535-88b03f0bc121@w19g2000pre.googlegroups.com> <87638ekxdq.fsf@castleamber.com> Message-ID: <4B228DBD.7040304@tim.thechases.com> On 12/10/2009 09:22 PM, John Bokma wrote: > Tim Chase writes: > > Please don't delete attribution line(s), added: > > Asun Friere writes: I tend to prune them because a good newsreader will thread messages and put my reply in the context of the message to which I'm replying. Both Thunderbird and Claws Mail seem to have correctly placed my message under Asun's message. However your reply to mine failed to show up under my message in either program (it showed up under the top-level post by Hong Zhang in both apps). Looks like you're sending from Gnus...a threading/reply bug in Gnus perhaps? Anyways...I'll leave them in for this reply. >>> phone.update_from_record(record) >>> >>> This switch statement belongs to one guy. One guy who wants to know >>> how to do everything that needs to be done to Phones no matter who >>> asks >> >> This is where you make a false assumption -- the contents and parsing >> of the "switch" are provider-specific in this case, mapping to a >> common ontology of the Phone object: > > In that case, why not give the classes Asun suggested all the same base > class: Phone? Whether the logic gets put in a subclass of Phone, or whether it gets put in a provider Phone-factory (as it currently does...the Provider superclass also knows how to auto-detect the format of a filename/path passed to it and know whether it can handle it), there's still a rat's-nest of if/else/switch type logic, each branch of which usually involves a single assignment, or further sub-branch checking. So I often have things that would pseudo-code like switch rectype: case '01': phone.textmessaging += row['txtmsgcost'] count = row['count'] switch subtype: case 'a': phone.textmessagessent += count case 'b': phone.textmessagesreceived += count case 'c': phone.pagessent += count case 'd': phone.pagesreceived += count case '02': ... which is fairly readable. However, with a method-dispatch dictionary, this flattens the hierarchy to "def"s at the same level (class definition scope), leaving the hierarchy visible only in the call-graph. Turning each of these a function would - obfuscate the flow and processing hierarchy - create a profusion of 1-3 line functions (about 50 Phone attributes, times currently about 15 provider formats, plus a duplication factor of about 10% where certain fields aggregate from various sources in the data, accumulating in a single Phone field) - have the overhead of several million function-calls >> Yes, having been programming since I was in middle-school (quick >> calculation yields a "boy I'm old" estimate of about 20 years...does >> anybody miss 360k 5.25" floppy disks? :) > > I do miss cassette tapes and the wheeeeeee kkkrggrggrgrgrg of a program > loading. Heh, one of the other things I miss: booting my Apple ][+ and hitting the button, resulting in a prompt where I could code in under 2 seconds from power-on. Can't say I miss tape at all though :) -tkc From sraji.me at gmail.com Fri Dec 11 13:24:06 2009 From: sraji.me at gmail.com (Raji Seetharaman) Date: Fri, 11 Dec 2009 23:54:06 +0530 Subject: A try with WebScraping using Python Message-ID: <23e3fbb60912111024q4a9471c8w9ab0dda115ba11@mail.gmail.com> Hi >From the tutorial found on the net i came to know about WebScraping using Python. I thought to give a try with it. My wish is to extract the contact mail id's from all the posts published till now in the below link http://fossjobs.wordpress.com/ With Firebug add-on its easy to find the location of mail id's inside HTML DOM tree. I dont know how to download all the web pages i.e., the coding part Which library i can use to download ? ( mechanize or windmill ) Help me Thanks Raji. S http://sraji.wordpress.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From imageguy1206 at gmail.com Fri Dec 11 13:36:39 2009 From: imageguy1206 at gmail.com (imageguy) Date: Fri, 11 Dec 2009 10:36:39 -0800 (PST) Subject: Moving from PHP to Python. Is it Possible References: <3c4778e3-e31a-4484-ae9a-f6d5b737fa68@x25g2000prf.googlegroups.com> Message-ID: <42459ec7-35a5-4879-b6c1-169b1519e861@k19g2000yqc.googlegroups.com> > So My question is. > For example I had this kind of python file and we want to use this as plugin > template > > ?
> ? <% > ? for n in range(3): > ? ? ? # This indent will persist > ? %> > ?

This paragraph will be > ? repeated 3 times.

> ? <% > ? # This line will cause the block to end > ? %> > ? This line will only be shown once.
> ?
> > on execution time, I want to import this template file, execute as python > script and store output in a GLOBAL dictionary for later usage. > > Is it possible ? > Have you checked out one of the templating systems modules ? I have used Cheetah quite successfully, but there a numerous other options. http://www.cheetahtemplate.org/ I think you will find that a template system (like Cheetah) will give you the best results with the most maintainable structure. g. From irmen-NOSPAM- at xs4all.nl Fri Dec 11 13:40:21 2009 From: irmen-NOSPAM- at xs4all.nl (Irmen de Jong) Date: Fri, 11 Dec 2009 19:40:21 +0100 Subject: Recommendation for small, fast, Python based web server In-Reply-To: References: <1260387281.5558.1349282363@webmail.messagingengine.com> Message-ID: <4b2291cf$0$22918$e4fe514c@news.xs4all.nl> On 11-12-2009 14:52, Antoine Pitrou wrote: > > Hello, > >> I've looked at the web servers that come bundled with the Python >> standard library[1] and they are too slow. > > Apparently you have debugged your speed issue so I suppose you don't have > performance problems anymore. Do note, however, that Python is generally > not as fast as C -- especially for low-level stuff -- and a Python Web > server will probably serve around 10x less requests per second than a C > Web server like Apache (this will still give you hundreds of simple > requests per second on a modern machine). I don't think that number is fair for Python. I think a well written Python web server can perform in the same ballpark as most mainstream web servers written in C. Especially Apache, which really isn't a top performer. And I'm pretty sure a well written Python server can outperform a badly written C based server easily. -irmen From bryanvick at gmail.com Fri Dec 11 13:44:54 2009 From: bryanvick at gmail.com (Bryan) Date: Fri, 11 Dec 2009 10:44:54 -0800 (PST) Subject: Using hash to see if object's attributes have changed References: <9e670042-394f-43bb-8b97-2a14346a64ab@o9g2000prg.googlegroups.com> Message-ID: On Dec 11, 10:17?am, Robert Kern wrote: > On 2009-12-11 12:03 PM, Bryan wrote: > > > When a user submits a request to update an object in my web app, I > > make the changes in the DB, along w/ who last updated it and when. ?I > > only want to update the updated/updatedBy columns in the DB if the > > data has actually changed however. > > > I'm thinking of having the object in question be able to return a list > > of its values that constitute its state. ?Then I can take a hash of > > that list as the object exists in the database before the request, and > > then on the object that the user has made changes to. ?If they are not > > equal, the user has changed the object. > > It *might* work, but probably won't be robust especially as you are relying on > the string representation. You would be much better off using an ORM, which will > do all of this for you. This is exactly what they are for. > > They usually determine whether attributes have change by instrumentation rather > than inspection. If you still don't want to use a full ORM, you should at least > emulate that strategy. Add descriptors to your classes for each attribute you > want to map to a column. On __set__, they should compare the new value to the > old, and set a "dirty" flag if the the attribute changes value. Or just > implement __setattr__ on your classes to do a similar check. > > -- > Robert Kern I am using sqlalchemy, and it does a pretty good job of this. The problem is that it considers an object changed whenever an attribute gets set after the object is loaded, even if the attribute is being set to the same value. Another thing I could do is when applying the user's changes to the object that was loaded from the db, only apply the change if the value is actually different. In that case I could use the ORM's isDirty() test that keeps track of what was set since being loaded. Then the object doesn't know anything about its state or isDirty() tests, only the controller would, which I like as it is less intrusive, but it also is dependent on a ORM. Instrumentation would require a bit more work. I would have to watch for changes using set/get and __dict__ access. Also, I would have to be able to say, "Has this object changed since time x". Imagine loading an object from the db. Depending on the ORM implementation, it may instantiate an object, then set all its attributes from the DB row, which would trigger my isDirty instrumentation. So it would look dirty even fresh out of the DB w/ no changes. So I would have to be able to manually clear the isDirty flag. Not that any of this is impossible, just more complex. From dmitrey.kroshko at scipy.org Fri Dec 11 13:48:38 2009 From: dmitrey.kroshko at scipy.org (dmitrey) Date: Fri, 11 Dec 2009 10:48:38 -0800 (PST) Subject: __mul__ vs __rmul__ (and others) priority for different classes Message-ID: <8cb0df8f-e0e0-4a11-8bc3-8d382a25727c@g12g2000yqa.googlegroups.com> hi all, I have created a class MyClass and defined methods like __add__, __mul__, __pow__, __radd__, __rmul__ etc. Also, they are defined to work with numbers, Python lists and numpy.arrays. Both Python lists and numpy arrays have their own methods __add__, __mul__, __pow__, __radd__, __rmul__ etc. If I involve myPythonList * myClassInstance it returns just result of my __rmul__; but when I invoke nuumpy_arr*myClassInstance it returns another numpy array with elements [nuumpy_arr[0]*myClassInstance, nuumpy_arr[1]*myClassInstance, ...]. Can I somehow prevent numpy array of using it __mul__ etc methods? (and use only my __rmul__, __radd__, etc instead)? Thank you in advance, D. From lie.1296 at gmail.com Fri Dec 11 13:56:38 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Sat, 12 Dec 2009 05:56:38 +1100 Subject: Virtual file for subprocess In-Reply-To: References: Message-ID: <4b229672$1@dnews.tpgi.com.au> On 12/12/2009 4:07 AM, bobnotbob wrote: > I am calling external executable from my python program (using > subprocess). This external program's output is a text file which I > then read and parse. Is there any way to "sandbox" the calling of > this external program so that it writes to a virtual file instead of > the hardcoded text? If the program writes its outputs to the stdout, you can redirect the program's stdout using subprocess, try to find a switch that will tell it to write to stdout. Otherwise, you're pretty much stuck to using a real file AFAIK. From max at theslimmers.net Fri Dec 11 13:59:40 2009 From: max at theslimmers.net (Max Slimmer) Date: Fri, 11 Dec 2009 10:59:40 -0800 Subject: HTTPS - HTTPPasswordMgrWithDefaultRealm Message-ID: 1) I have an application that accesses a web site via HTTPS using a certificate. The primary url returns a 302 redirect, urllib2 then goes to this address and gets a 401, which if the passwordMgr has be setup properly then connects. I have been able to determine a set of uri's that if fed to the passwordMgr.add_password() make things work. The problem is that depending on where the application is run from the redirect may be to different url's. I would like to dynamically catch the redirect and then format add_password() properly to add this uri and the user/password information rather than having to determine all possible uri's and load passwordMgr at init time. If I overload the redirect handler when it gets there I don't have access to the passwordMgr. Following is a snipit of the code: passwordMgr = urllib2.HTTPPasswordMgrWithDefaultRealm() #### Here I am setting passwordMgr up with all known uri's, but if I get redirected to some other address It no longer works #### for uri in ('payex.adp.com','agateway.adp.com','bgateway.adp.com','.adp.com '): passwordMgr.add_password(None, uri, usr, pwd) basicAuthHndlr = urllib2.HTTPBasicAuthHandler(passwordMgr) cookies = cookielib.CookieJar() cookieHndlr = urllib2.HTTPCookieProcessor(cookies) self.opener = urllib2.build_opener(MultipartPostHandler, HTTPSClientAuthHandler(httpDebug),basicAuthHndlr,cookieHndlr,urllib2.HTTPRedirectHandler()) I then call: self.opener(request) 2) I have a second problem, for which I have created an ugly workaround, Namely I need a way to give the HTTPSConnection.__ini__() a reference to the cert file. The HTTPSClientAuthHandler do_open method takes a ref to the HTTPSClientAuthConnection not an instance, so I overloaded this class and get the cert_file via a previously set global ref. I would like a better way to feed the cert file. Here is the code I am using: class HTTPSClientAuthConnection(httplib.HTTPSConnection): def __init__(self, host, timeout=socket._GLOBAL_DEFAULT_TIMEOUT): # nb cert_file is global and set in UrllibPX httplib.HTTPSConnection.__init__(self, host, cert_file=cert_file) doseq = 1 class HTTPSClientAuthHandler(urllib2.HTTPSHandler): def https_open(self, req): for tries in range(3): try: ret = self.do_open(HTTPSClientAuthConnection, req) return ret except URLError: log = logging.getLogger() log.warn("problem connecting") raise thanks, -- Max Slimmer -------------- next part -------------- An HTML attachment was scrubbed... URL: From stef.mientki at gmail.com Fri Dec 11 14:03:34 2009 From: stef.mientki at gmail.com (Stef Mientki) Date: Fri, 11 Dec 2009 20:03:34 +0100 Subject: pyZui - anyone know about this? In-Reply-To: <200912111324.11546.donn.ingle@gmail.com> References: <200912110641.56775.donn.ingle@gmail.com> <200912111324.11546.donn.ingle@gmail.com> Message-ID: <4B229786.9010801@gmail.com> Donn wrote: > On Friday 11 December 2009 12:38:46 Daniel Fetchinson wrote: > >> Youtube has a link 'Send message' on the profile of users, maybe >> sending a message to the person who uploaded the video will give you a >> useful response. >> >> > I'm a Tube-tard so that never crossed my mind. Will give it a go. > > \d > please let us know when you find more information about the project. thanks, Stef Mientki From carsten.haese at gmail.com Fri Dec 11 14:12:35 2009 From: carsten.haese at gmail.com (Carsten Haese) Date: Fri, 11 Dec 2009 14:12:35 -0500 Subject: MySQL set and enum, calling values In-Reply-To: <4dc0cfea0912111008x5fb47e8dv5a9091cbe67ec4c8@mail.gmail.com> References: <4dc0cfea0912111008x5fb47e8dv5a9091cbe67ec4c8@mail.gmail.com> Message-ID: Victor Subervi wrote: > [...] if I go to print, say, > colFieldValues[20], which is a set, it prints out the whole set: > set('Extra-small','Small','Medium','Large','XLarge','XXLarge','XXXLarge') > But if I print out colFieldValues[20][0], it prints out "s". The only reasonable explanation of this behavior is that despite all your wishing for it to be a set, colFieldValues[20] is in fact not a set, but rather a string. It is a string containing the letter s, followed by the letter e, followed by the letter t, followed by an openening parenthesis, and so on. > Also, how can I test > for it? It's an instance of string. How do I know if it's a set? That's a fantastic question. Python thinks it's a string. What makes you think it's a set? -- Carsten Haese http://informixdb.sourceforge.net From invalid at invalid.invalid Fri Dec 11 14:21:29 2009 From: invalid at invalid.invalid (Grant Edwards) Date: Fri, 11 Dec 2009 19:21:29 +0000 (UTC) Subject: Virtual file for subprocess References: <4b229672$1@dnews.tpgi.com.au> Message-ID: On 2009-12-11, Lie Ryan wrote: > On 12/12/2009 4:07 AM, bobnotbob wrote: >> I am calling external executable from my python program (using >> subprocess). This external program's output is a text file which I >> then read and parse. Is there any way to "sandbox" the calling of >> this external program so that it writes to a virtual file instead of >> the hardcoded text? > > If the program writes its outputs to the stdout, you can > redirect the program's stdout using subprocess, try to find a > switch that will tell it to write to stdout. Otherwise, you're > pretty much stuck to using a real file AFAIK. Most Unix systems have paths that you can pass to programs which think they need to write to "files". Accessing those files actually access already open file descriptors such as stdin, stdout, and stderr. On Linux, for example, you can tell the program to write to /proc/self/fd/1 and that's actually stdout which can then be a pipe connected to the Python program that invoked the program. This can be very useful when executing a program which can be told what file to write to, but who's author was too narrow-minded to provide the option to send output to stdout. If you need to get fancy you can create multiple input/output pipes that are inherited by the child program and then references as /proc/self/fd/. -- Grant Edwards grante Yow! These PRESERVES should at be FORCE-FED to PENTAGON visi.com OFFICIALS!! From victorsubervi at gmail.com Fri Dec 11 14:28:23 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Fri, 11 Dec 2009 15:28:23 -0400 Subject: MySQL set and enum, calling values In-Reply-To: References: <4dc0cfea0912111008x5fb47e8dv5a9091cbe67ec4c8@mail.gmail.com> Message-ID: <4dc0cfea0912111128w48b072bfsd7d8c29445c5f81d@mail.gmail.com> On Fri, Dec 11, 2009 at 3:12 PM, Carsten Haese wrote: > Victor Subervi wrote: > > [...] if I go to print, say, > > colFieldValues[20], which is a set, it prints out the whole set: > > set('Extra-small','Small','Medium','Large','XLarge','XXLarge','XXXLarge') > > But if I print out colFieldValues[20][0], it prints out "s". > > The only reasonable explanation of this behavior is that despite all > your wishing for it to be a set, colFieldValues[20] is in fact not a > set, but rather a string. It is a string containing the letter s, > followed by the letter e, followed by the letter t, followed by an > openening parenthesis, and so on. > > > Also, how can I test > > for it? It's an instance of string. How do I know if it's a set? > > That's a fantastic question. Python thinks it's a string. What makes you > think it's a set? > Right. I'm doing it the ugly way with the truncating tuple and string replace. V -------------- next part -------------- An HTML attachment was scrubbed... URL: From johnkduffy at gmail.com Fri Dec 11 14:29:05 2009 From: johnkduffy at gmail.com (ObservantP) Date: Fri, 11 Dec 2009 11:29:05 -0800 (PST) Subject: pyserial - escape codes transportation Message-ID: <1cdd3691-2855-4406-8953-9be1b1f86a71@v30g2000yqm.googlegroups.com> need help. newbie. pyserial and dot matrix printer. issue- escape codes arrive at printer ( verified from hex dump) but do not get applied. printer make/model STAR POS printer SP500. oddly, printer commands not initiated with the escape code .i.e. a symbol, work fine. import serial ser=serial.Serial(0) ser.bytesize=7 ser.timeout=1 ser.dsrdtr=1 ser.write('PySerial'+'\n') ser.write('Star SP500'+'\n') #Double Width On 14 SO =  Or ESC W 1 / 0 # Off 20 DC4=  ser.write('' +'Double Width-Symbol\n') #Good ser.write('' +'Reset\n') #Good ser.write('\n') #Good ser.write('Xw1\n'+'Double Width-ESC\n') #Nope ( Nor CHR(027) '\x1b' ser.write('Xw0\n'+'Reset\n') #X is symbol not showing up here. ser.write('\n') ser.write('\n') ser.write('\n') ser.close() From istvan.szirtes at gmail.com Fri Dec 11 14:39:37 2009 From: istvan.szirtes at gmail.com (Isti) Date: Fri, 11 Dec 2009 11:39:37 -0800 (PST) Subject: How can I get the target platform info of a dll with Python 3.1.1? Message-ID: <01772f90-856c-4723-9f72-366a5d088ed5@k4g2000yqb.googlegroups.com> I have many dll files and I would like to select them into two different folders (PC and PPC). For this I need to know the target platform of the dll file or any other details about its platform. I use Python 3.1.1. I have tried the win32api which does not compatible with this Python version. So, I try to use the ctypes.windll with try-except method where the try is true the loaded- in dll is "PC" and if not, unable to load the dll that is "PPC". But, I have a problem with this idea. There are some dll files which I know that "PC" dll but unable to load in memory. The try-except does not work with them. So, I need to request info from the dll file about the target platform of itself. Do you have any idea about this problem? Many thanks. From istvan.szirtes at gmail.com Fri Dec 11 14:42:19 2009 From: istvan.szirtes at gmail.com (=?ISO-8859-1?Q?Istv=E1n_Szirtes?=) Date: Fri, 11 Dec 2009 20:42:19 +0100 Subject: How can I get the target platform info of a dll with Python 3.1.1? Message-ID: I have many dll files and I would like to select them into two different folders (PC and PPC). For this I need to know the target platform of the dll file or any other details about its platform. I use Python 3.1.1. I have tried the win32api which does not compatible with this Python version. So, I try to use the ctypes.windll with try-except method where the try is true the loaded- in dll is "PC" and if not, unable to load the dll that is "PPC". But, I have a problem with this idea. There are some dll files which I know that "PC" dll but unable to load in memory. The try-except does not work with them. So, I need to request info from the dll file about the target platform of itself. Do you have any idea about this problem? Many thanks for your help. -------------- next part -------------- An HTML attachment was scrubbed... URL: From invalid at invalid.invalid Fri Dec 11 14:56:23 2009 From: invalid at invalid.invalid (Grant Edwards) Date: Fri, 11 Dec 2009 19:56:23 +0000 (UTC) Subject: pyserial - escape codes transportation References: <1cdd3691-2855-4406-8953-9be1b1f86a71@v30g2000yqm.googlegroups.com> Message-ID: On 2009-12-11, ObservantP wrote: > need help. newbie. pyserial and dot matrix printer. > issue- escape codes arrive at printer ( verified from hex dump) but do > not get applied. What you're saying is your printer isn't working correctly. > printer make/model STAR POS printer SP500. oddly, printer > commands not initiated with the escape code .i.e. a symbol, > work fine. > > > import serial > ser=serial.Serial(0) > > ser.bytesize=7 > ser.timeout=1 > ser.dsrdtr=1 > ser.write('PySerial'+'\n') > ser.write('Star SP500'+'\n') > > > > #Double Width On 14 SO =  Or ESC W 1 / 0 > # Off 20 DC4=  > > ser.write('' +'Double Width-Symbol\n') #Good > ser.write('' +'Reset\n') #Good > ser.write('\n') #Good > > ser.write('Xw1\n'+'Double Width-ESC\n') #Nope ( Nor CHR(027) FWIW, that's _not_ sending an ASCII escape character. It's sending a string starting with a caret and a square bracket. I don't know what you're actually trying to send, but my guess is that you want is '\033w1' or '\x1Bw1' -- Grant Edwards grante Yow! I'm also against at BODY-SURFING!! visi.com From invalid at invalid.invalid Fri Dec 11 14:58:26 2009 From: invalid at invalid.invalid (Grant Edwards) Date: Fri, 11 Dec 2009 19:58:26 +0000 (UTC) Subject: pyserial - escape codes transportation References: <1cdd3691-2855-4406-8953-9be1b1f86a71@v30g2000yqm.googlegroups.com> Message-ID: On 2009-12-11, Grant Edwards wrote: > On 2009-12-11, ObservantP wrote: >> need help. newbie. pyserial and dot matrix printer. issue- >> escape codes arrive at printer ( verified from hex dump) but >> do not get applied. > > What you're saying is your printer isn't working correctly. BTW, I (among others) filter out all posts made from google groups. I only stumbled across your posting by accident while playing with my newsreader configuration. I won't see any follow-up postings you make if they're from google groups. -- Grant Edwards grante Yow! ! Everybody out of at the GENETIC POOL! visi.com From zephjc at gmail.com Fri Dec 11 15:20:51 2009 From: zephjc at gmail.com (zeph) Date: Fri, 11 Dec 2009 12:20:51 -0800 (PST) Subject: Moving from PHP to Python. Is it Possible References: <3c4778e3-e31a-4484-ae9a-f6d5b737fa68@x25g2000prf.googlegroups.com> Message-ID: <5dcc533f-ef47-4999-a820-bc921e492189@z10g2000prh.googlegroups.com> On Dec 11, 8:58?am, MRAB wrote: > output = [''] > output.append('My Page') > output.append('') > output.append('

Powers of two

\n
    ') > for n in range(1, 11): > ? ? ?output.append('
  1. %s
  2. ' % (2 ** n)) > > output.append('
') > print ''.join(output) Agreed (I might join on '\n' though), I was just trying to introduce as few new concepts as possible :) From tjreedy at udel.edu Fri Dec 11 15:24:02 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 11 Dec 2009 15:24:02 -0500 Subject: __mul__ vs __rmul__ (and others) priority for different classes In-Reply-To: <8cb0df8f-e0e0-4a11-8bc3-8d382a25727c@g12g2000yqa.googlegroups.com> References: <8cb0df8f-e0e0-4a11-8bc3-8d382a25727c@g12g2000yqa.googlegroups.com> Message-ID: dmitrey wrote: > hi all, > I have created a class MyClass and defined methods like __add__, > __mul__, __pow__, __radd__, __rmul__ etc. > Also, they are defined to work with numbers, Python lists and > numpy.arrays. > > Both Python lists and numpy arrays have their own methods __add__, > __mul__, __pow__, __radd__, __rmul__ etc. > If I involve myPythonList * myClassInstance it returns just result of > my __rmul__; but when I invoke nuumpy_arr*myClassInstance it returns > another numpy array with elements [nuumpy_arr[0]*myClassInstance, > nuumpy_arr[1]*myClassInstance, ...]. > > Can I somehow prevent numpy array of using it __mul__ etc methods? > (and use only my __rmul__, __radd__, etc instead)? No. you have to put your class instance first to get priority. Given a op b, python first calls a.__op__(b) and only if that fails, which it will for most builtin objects when b is MyClass, b.__rop__(a). Numpy arrays, however, are more broadminded about what they will work with. If your operations are not commutative, you will either have to wrap numpy arrays in a class that disables the special methods or use explicit function calls. Terry Jan Reedy From brfredericks at gmail.com Fri Dec 11 15:33:55 2009 From: brfredericks at gmail.com (bfrederi) Date: Fri, 11 Dec 2009 12:33:55 -0800 (PST) Subject: datetime 'NoneType' sporadic error Message-ID: <2aa669fb-d0ee-4fdc-b5aa-97d727103729@p35g2000yqh.googlegroups.com> When using the datetime module, I sporadically get " 'NoneType' object has no attribute 'datetime' " on line 40: http://dpaste.com/hold/132156/ Sorry, I don't have the traceback, this is an error that was sent to me by one of the users. It only happens occasionally. Any ideas? From e_d_k at yahoo.com Fri Dec 11 15:49:42 2009 From: e_d_k at yahoo.com (Ed Keith) Date: Fri, 11 Dec 2009 12:49:42 -0800 (PST) Subject: a list/re problem Message-ID: <851956.36891.qm@web58908.mail.re1.yahoo.com> I have a problem and I am trying to find a solution to it that is both efficient and elegant. I have a list call it 'l': l = ['asc', '*nbh*', 'jlsdjfdk', 'ikjh', '*jkjsdfjasd*', 'rewr'] Notice that some of the items in the list start and end with an '*'. I wish to construct a new list, call it 'n' which is all the members of l that start and end with '*', with the '*'s removed. So in the case above n would be ['nbh', 'jkjsdfjasd'] the following works: r = re.compile('\*(.+)\*') def f(s): m = r.match(s) if m: return m.group(1) else: return '' n = [f(x) for x in l if r.match(x)] But it is inefficient, because it is matching the regex twice for each item, and it is a bit ugly. I could use: n = [] for x in keys: m = r.match(x) if m: n.append(m.group(1)) It is more efficient, but much uglier. Does anyone have a better solution? Thank, -EdK Ed Keith e_d_k at yahoo.com Blog: edkeith.blogspot.com From anand.ibmgsi at gmail.com Fri Dec 11 15:59:30 2009 From: anand.ibmgsi at gmail.com (anand jeyahar) Date: Sat, 12 Dec 2009 02:29:30 +0530 Subject: Which graph library is best suited for large graphs? In-Reply-To: References: <7c6c5804-acc1-4fbe-bdf4-238da730728f@d20g2000yqh.googlegroups.com> <20091211140741.GF5712@kinakuta.local> Message-ID: <4B22B2B2.9080209@gmail.com> On 12/11/2009 10:27 PM, Neal Becker wrote: > Which library would you choose? > Hmm.... i have tried python-graph and was happy with it....but the most use i did was for complete graphs of 60-65 nodes.. Also there is an experimental branch for faster implementations, which is under development. -- ============================================== Anand J http://sites.google.com/a/cbcs.ac.in/students/anand ============================================== The man who is really serious, with the urge to find out what truth is, has no style at all. He lives only in what is. ~Bruce Lee Love is a trade with lousy accounting policies. ~Aang Jie From andreengels at gmail.com Fri Dec 11 16:01:06 2009 From: andreengels at gmail.com (Andre Engels) Date: Fri, 11 Dec 2009 22:01:06 +0100 Subject: a list/re problem In-Reply-To: <851956.36891.qm@web58908.mail.re1.yahoo.com> References: <851956.36891.qm@web58908.mail.re1.yahoo.com> Message-ID: <6faf39c90912111301s3fff7865y4650a57bd4fdebab@mail.gmail.com> On Fri, Dec 11, 2009 at 9:49 PM, Ed Keith wrote: > I have a problem and I am trying to find a solution to it that is both > efficient and elegant. > > I have a list call it 'l': > > l = ['asc', '*nbh*', 'jlsdjfdk', 'ikjh', '*jkjsdfjasd*', 'rewr'] > > Notice that some of the items in the list start and end with an '*'. I wish to construct a new list, call it 'n' which is all the members of l that start and end with '*', with the '*'s removed. > > So in the case above n would be ['nbh', 'jkjsdfjasd'] > > the following works: > > r = re.compile('\*(.+)\*') > > def f(s): > ? ?m = r.match(s) > ? ?if m: > ? ? ? ?return m.group(1) > ? ?else: > ? ? ? ?return '' > > n = ?[f(x) for x in l if r.match(x)] > > > > But it is inefficient, because it is matching the regex twice for each item, and it is a bit ugly. > > I could use: > > > n = [] > for x in keys: > ? ?m = r.match(x) > ? ? ? ?if m: > ? ? ? ? ? ?n.append(m.group(1)) > > > It is more efficient, but much uglier. > > Does anyone have a better solution? Regexes seem like the proverbial sledgehammer to crack a nut here. Note that '*' if it is present, is always 1 character, so we can write: n = [x[1:-1] for x in l if x.startswith("*") and x.endswith("*")] -- Andr? Engels, andreengels at gmail.com From vlastimil.brom at gmail.com Fri Dec 11 16:02:23 2009 From: vlastimil.brom at gmail.com (Vlastimil Brom) Date: Fri, 11 Dec 2009 22:02:23 +0100 Subject: a list/re problem In-Reply-To: <851956.36891.qm@web58908.mail.re1.yahoo.com> References: <851956.36891.qm@web58908.mail.re1.yahoo.com> Message-ID: <9fdb569a0912111302r501f0a8xa0bd7c760a254796@mail.gmail.com> 2009/12/11 Ed Keith : > I have a problem and I am trying to find a solution to it that is both > efficient and elegant. > > I have a list call it 'l': > > l = ['asc', '*nbh*', 'jlsdjfdk', 'ikjh', '*jkjsdfjasd*', 'rewr'] > > Notice that some of the items in the list start and end with an '*'. I wish to construct a new list, call it 'n' which is all the members of l that start and end with '*', with the '*'s removed. > > So in the case above n would be ['nbh', 'jkjsdfjasd'] > > the following works: > > r = re.compile('\*(.+)\*') > > def f(s): > ? ?m = r.match(s) > ? ?if m: > ? ? ? ?return m.group(1) > ? ?else: > ? ? ? ?return '' > > n = ?[f(x) for x in l if r.match(x)] > > > > But it is inefficient, because it is matching the regex twice for each item, and it is a bit ugly. > > I could use: > > > n = [] > for x in keys: > ? ?m = r.match(x) > ? ? ? ?if m: > ? ? ? ? ? ?n.append(m.group(1)) > > > It is more efficient, but much uglier. > > Does anyone have a better solution? > > Thank, > > ? ?-EdK > > > Ed Keith > e_d_k at yahoo.com > > Blog: edkeith.blogspot.com > > > > -- > http://mail.python.org/mailman/listinfo/python-list > Hi, maybe you could use a list comprehension or the equivalent loop just using the string methods and slicing? >>> lst = ['asc', '*nbh*', 'jlsdjfdk', 'ikjh', '*jkjsdfjasd*', 'rewr'] >>> [item[1:-1] for item in lst if (item.startswith("*") and item.endswith("*"))] ['nbh', 'jkjsdfjasd'] >>> hth, vbr From invalid at invalid.invalid Fri Dec 11 16:02:45 2009 From: invalid at invalid.invalid (Grant Edwards) Date: Fri, 11 Dec 2009 21:02:45 +0000 (UTC) Subject: a list/re problem References: Message-ID: On 2009-12-11, Ed Keith wrote: > I have a problem and I am trying to find a solution to it that is both > efficient and elegant. > > I have a list call it 'l': > > l = ['asc', '*nbh*', 'jlsdjfdk', 'ikjh', '*jkjsdfjasd*', 'rewr'] > Notice that some of the items in the list start and end with > an '*'. I wish to construct a new list, call it 'n' which is > all the members of l that start and end with '*', with the > '*'s removed. > > So in the case above n would be ['nbh', 'jkjsdfjasd'] [s[1:-1] for s in l if (s[0] == s[-1] == '*')] -- Grant Edwards grante Yow! Used staples are good at with SOY SAUCE! visi.com From python.list at tim.thechases.com Fri Dec 11 16:05:36 2009 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 11 Dec 2009 15:05:36 -0600 Subject: a list/re problem In-Reply-To: <851956.36891.qm@web58908.mail.re1.yahoo.com> References: <851956.36891.qm@web58908.mail.re1.yahoo.com> Message-ID: <4B22B420.7030005@tim.thechases.com> > l = ['asc', '*nbh*', 'jlsdjfdk', 'ikjh', '*jkjsdfjasd*', 'rewr'] > > Notice that some of the items in the list start and end with an '*'. I wish to construct a new list, call it 'n' which is all the members of l that start and end with '*', with the '*'s removed. > > So in the case above n would be ['nbh', 'jkjsdfjasd'] > > the following works: > > r = re.compile('\*(.+)\*') > > def f(s): > m = r.match(s) > if m: > return m.group(1) > else: > return '' > > n = [f(x) for x in l if r.match(x)] > > But it is inefficient, because it is matching the regex twice for each item, and it is a bit ugly. You can skip the function by writing that as n = [r.match(s).group(1) for s in l if r.match(s)] but it doesn't solve your match-twice problem. I'd skip regexps completely and do something like n = [s[1:-1] for s in l if s.startswith('*') and s.endswith('*') ] And this is coming from a guy that tends to overuse regexps :) -tkc From neilc at norwich.edu Fri Dec 11 16:16:25 2009 From: neilc at norwich.edu (Neil Cerutti) Date: 11 Dec 2009 21:16:25 GMT Subject: a list/re problem References: Message-ID: <7ofr58F3q174qU2@mid.individual.net> On 2009-12-11, Grant Edwards wrote: > [s[1:-1] for s in l if (s[0] == s[-1] == '*')] That last bit doesn't work right, does it, since an == expression evaluates to True or False, no the true or false value itself? -- Neil Cerutti From nguyenn at gmail.com Fri Dec 11 16:23:21 2009 From: nguyenn at gmail.com (nnguyen) Date: Fri, 11 Dec 2009 13:23:21 -0800 (PST) Subject: expat having problems with entities (&) Message-ID: <93d669cd-8e17-4fff-ac58-f329be5c6393@b2g2000yqi.googlegroups.com> I need expat to parse this block of xml: c-P&P LOT 3677 (F) I need to parse the xml and return a dictionary that follows roughly the same layout as the xml. Currently the code for the class handling this is: class XML2Map(): def __init__(self): """ """ self.parser = expat.ParserCreate() self.parser.StartElementHandler = self.start_element self.parser.EndElementHandler = self.end_element self.parser.CharacterDataHandler = self.char_data self.map = [] #not a dictionary self.current_tag = '' self.current_subfields = [] self.current_sub = '' self.current_data = '' def parse_xml(self, xml_text): self.parser.Parse(xml_text, 1) def start_element(self, name, attrs): if name == 'datafield': self.current_tag = attrs['tag'] elif name == 'subfield': self.current_sub = attrs['code'] def char_data(self, data): self.current_data = data def end_element(self, name): if name == 'subfield': self.current_subfields.append([self.current_sub, self.current_data]) elif name == 'datafield': self.map.append({'tag': self.current_tag, 'subfields': self.current_subfields}) self.current_subfields = [] #resetting the values for next subfields Right now my problem is that when it's parsing the subfield element with the data "c-P&P", it's not taking the whole data, but instead it's breaking it into "c-P", "&", "P". i'm not an expert with expat, and I couldn't find a lot of information on how it handles specific entities. In the resulting map, instead of: {'tag': u'991', 'subfields': [[u'b', u'c-P&P'], [u'h', u'LOT 3677'], [u'm', u'(F)']], 'inds': [u' ', u' ']} I get this: {'tag': u'991', 'subfields': [[u'b', u'P'], [u'h', u'LOT 3677'], [u'm', u'(F)']], 'inds': [u' ', u' ']} In the debugger, I can see that current_data gets assigned "c-P", then "&", and then "P". Any ideas on any expat tricks I'm missing out on? I'm also inclined to try another parser that can keep the string together when there are entities, or at least ampersands. From __peter__ at web.de Fri Dec 11 16:24:07 2009 From: __peter__ at web.de (Peter Otten) Date: Fri, 11 Dec 2009 22:24:07 +0100 Subject: a list/re problem References: Message-ID: Ed Keith wrote: > I have a problem and I am trying to find a solution to it that is both > efficient and elegant. > > I have a list call it 'l': > > l = ['asc', '*nbh*', 'jlsdjfdk', 'ikjh', '*jkjsdfjasd*', 'rewr'] > > Notice that some of the items in the list start and end with an '*'. I > wish to construct a new list, call it 'n' which is all the members of l > that start and end with '*', with the '*'s removed. > > So in the case above n would be ['nbh', 'jkjsdfjasd'] > > the following works: > > r = re.compile('\*(.+)\*') > > def f(s): > m = r.match(s) > if m: > return m.group(1) > else: > return '' > > n = [f(x) for x in l if r.match(x)] > > > > But it is inefficient, because it is matching the regex twice for each > item, and it is a bit ugly. > > I could use: > > > n = [] > for x in keys: > m = r.match(x) > if m: > n.append(m.group(1)) > > > It is more efficient, but much uglier. It's efficient and easy to understand; maybe you have to readjust your taste. > Does anyone have a better solution? In this case an approach based on string slicing is probably best. When the regular expression gets more complex you can use a nested a generator expression: >>> items = ['asc', '*nbh*', 'jlsdjfdk', 'ikjh', '*jkjsdfjasd*', 'rewr'] >>> match = re.compile(r"\*(.+)\*").match >>> [m.group(1) for m in (match(s) for s in items) if m is not None] ['nbh', 'jkjsdfjasd'] Peter From invalid at invalid.invalid Fri Dec 11 16:30:57 2009 From: invalid at invalid.invalid (Grant Edwards) Date: Fri, 11 Dec 2009 21:30:57 +0000 (UTC) Subject: a list/re problem References: <7ofr58F3q174qU2@mid.individual.net> Message-ID: On 2009-12-11, Neil Cerutti wrote: > On 2009-12-11, Grant Edwards wrote: >> [s[1:-1] for s in l if (s[0] == s[-1] == '*')] > > That last bit doesn't work right, does it, since an == expression > evaluates to True or False, no the true or false value itself? It works for me. Doesn't it work for you? >From the fine manual (section 5.9. Comparisons): Comparisons can be chained arbitrarily, e.g., x < y <= z is equivalent to x < y and y <= z, except that y is evaluated only once (but in both cases z is not evaluated at all when x < y is found to be false). -- Grant Edwards grante Yow! Hand me a pair of at leather pants and a CASIO visi.com keyboard -- I'm living for today! From nguyenn at gmail.com Fri Dec 11 16:37:35 2009 From: nguyenn at gmail.com (nnguyen) Date: Fri, 11 Dec 2009 13:37:35 -0800 (PST) Subject: expat having problems with entities (&) References: <93d669cd-8e17-4fff-ac58-f329be5c6393@b2g2000yqi.googlegroups.com> Message-ID: <2a5f530d-de3c-405c-bf7b-a108b45a953a@j24g2000yqa.googlegroups.com> On Dec 11, 4:23 pm, nnguyen wrote: > I need expat to parse this block of xml: > > > c-P&P > LOT 3677 > (F) > > > I need to parse the xml and return a dictionary that follows roughly > the same layout as the xml. Currently the code for the class handling > this is: > > class XML2Map(): > > def __init__(self): > """ """ > self.parser = expat.ParserCreate() > > self.parser.StartElementHandler = self.start_element > self.parser.EndElementHandler = self.end_element > self.parser.CharacterDataHandler = self.char_data > > self.map = [] #not a dictionary > > self.current_tag = '' > self.current_subfields = [] > self.current_sub = '' > self.current_data = '' > > def parse_xml(self, xml_text): > self.parser.Parse(xml_text, 1) > > def start_element(self, name, attrs): > if name == 'datafield': > self.current_tag = attrs['tag'] > > elif name == 'subfield': > self.current_sub = attrs['code'] > > def char_data(self, data): > self.current_data = data > > def end_element(self, name): > if name == 'subfield': > self.current_subfields.append([self.current_sub, > self.current_data]) > > elif name == 'datafield': > self.map.append({'tag': self.current_tag, 'subfields': > self.current_subfields}) > self.current_subfields = [] #resetting the values for next > subfields > > Right now my problem is that when it's parsing the subfield element > with the data "c-P&P", it's not taking the whole data, but instead > it's breaking it into "c-P", "&", "P". i'm not an expert with expat, > and I couldn't find a lot of information on how it handles specific > entities. > > In the resulting map, instead of: > > {'tag': u'991', 'subfields': [[u'b', u'c-P&P'], [u'h', u'LOT 3677'], > [u'm', u'(F)']], 'inds': [u' ', u' ']} > > I get this: > > {'tag': u'991', 'subfields': [[u'b', u'P'], [u'h', u'LOT 3677'], > [u'm', u'(F)']], 'inds': [u' ', u' ']} > > In the debugger, I can see that current_data gets assigned "c-P", then > "&", and then "P". > > Any ideas on any expat tricks I'm missing out on? I'm also inclined to > try another parser that can keep the string together when there are > entities, or at least ampersands. I forgot, ignore the "'inds':..." in the output above, it's just another part of the xml I had to parse that isn't important to this discussion. From rami.chowdhury at gmail.com Fri Dec 11 16:39:58 2009 From: rami.chowdhury at gmail.com (Rami Chowdhury) Date: Fri, 11 Dec 2009 13:39:58 -0800 Subject: expat having problems with entities (&) In-Reply-To: <93d669cd-8e17-4fff-ac58-f329be5c6393@b2g2000yqi.googlegroups.com> References: <93d669cd-8e17-4fff-ac58-f329be5c6393@b2g2000yqi.googlegroups.com> Message-ID: <2f79f590912111339l2f1b9cf4j848b50882c873b13@mail.gmail.com> On Fri, Dec 11, 2009 at 13:23, nnguyen wrote: > > Any ideas on any expat tricks I'm missing out on? I'm also inclined to > try another parser that can keep the string together when there are > entities, or at least ampersands. IIRC expat explicitly does not guarantee that character data will be handed to the CharacterDataHandler in complete blocks. If you're certain you want to stay at such a low level, I would just modify your char_data method to append character data to self.current_data rather than replacing it. Personally, if I had the option (e.g. Python 2.5+) I'd use ElementTree... -- -------- Rami Chowdhury "Never assume malice when stupidity will suffice." -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) From aahz at pythoncraft.com Fri Dec 11 16:48:52 2009 From: aahz at pythoncraft.com (Aahz) Date: 11 Dec 2009 13:48:52 -0800 Subject: How to implement Varient/Tagged Unions/Pattern Matching in Python? References: <358b227c-d836-4243-b79a-57258590a7a7@a10g2000pre.googlegroups.com> Message-ID: In article <358b227c-d836-4243-b79a-57258590a7a7 at a10g2000pre.googlegroups.com>, metal wrote: > >I want to get pattern matching like OCaml in python(ref:http:// >en.wikipedia.org/wiki/Tagged_union) > >I consider the syntax: > >def decl(): > def Plus(expr, expr): pass > def Minus(expr, expr): pass > def Times(expr, expr): pass > def Divide(expr, expr): pass > def Value(str): pass > @enum > def expr(Plus, Minus, Times, Divide, Value): pass > declare_types(locals()) > >def f(e): > def _Plus(l, r): > return '(%s+%s)' % (l, r) > def _Minus(l, r): > return '(%s-%s)' % (l, r) > def _Times(l, r): > return '(%s*%s)' % (l, r) > def _Divide(l, r): > return '(%s/%s)' % (l, r) > def _Value(x): > return x > try: > match(e, locals()) # visitor pattern > except NoMatchedError: > pass Perhaps you want to define what match() does? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ The best way to get information on Usenet is not to ask a question, but to post the wrong information. From nguyenn at gmail.com Fri Dec 11 17:01:14 2009 From: nguyenn at gmail.com (nnguyen) Date: Fri, 11 Dec 2009 14:01:14 -0800 (PST) Subject: expat having problems with entities (&) References: <93d669cd-8e17-4fff-ac58-f329be5c6393@b2g2000yqi.googlegroups.com> Message-ID: <63ef21d6-f71c-4942-8d50-a24b32a5f3ef@d21g2000yqn.googlegroups.com> On Dec 11, 4:39 pm, Rami Chowdhury wrote: > On Fri, Dec 11, 2009 at 13:23, nnguyen wrote: > > > Any ideas on any expat tricks I'm missing out on? I'm also inclined to > > try another parser that can keep the string together when there are > > entities, or at least ampersands. > > IIRC expat explicitly does not guarantee that character data will be > handed to the CharacterDataHandler in complete blocks. If you're > certain you want to stay at such a low level, I would just modify your > char_data method to append character data to self.current_data rather > than replacing it. Personally, if I had the option (e.g. Python 2.5+) > I'd use ElementTree... > Well the appending trick worked. From some logging I figured out that it was reading through those bits of current_data before getting to the subfield ending element (which is kinda obvious when you think about it). So I just used a += and made sure to clear out current_data when it hits a subfield ending element. Thanks! From sancar.saran at evodot.com Fri Dec 11 17:11:38 2009 From: sancar.saran at evodot.com (Sancar Saran) Date: Sat, 12 Dec 2009 00:11:38 +0200 Subject: Problems with debugging Lists Message-ID: <200912120011.38311.sancar.saran@evodot.com> Hello again. I wrote small class for generating and accessing globalized Dictionary. And of course I want to add some kind of debug ability to check what is inside... In php we had print_r function to see entire array structure. After some search I found some equal module named pprint. And some how this module wont work with mod_wsgi it was something about mod_wsgi portability standards. After some research there where some thing about putting some variables in apache config to disable this. And now I can see some dictionary structure in my apache log and I got some errors like r += pprint.pprint(self.data) TypeError: cannot concatenate 'str' and 'NoneType' objects So is there any way to get dictionary structure in string format ? Another question is. When I import a module from top is it available for later imported modules # -*- coding: utf-8 -*- import os, sys, cgi, pprint import cgitb cgitb.enable() def application(environ, start_response): sys.path.append(environ['DOCUMENT_ROOT']+"core") #sys.path.append(environ['DOCUMENT_ROOT']+"util") import registry, k5 #from print_r import print_r # new registry r = registry.Registry(environ) r.set_entry('hede','hodo') #response_headers = [('Content-type',k5.headers['content-type']+'; charset='+k5.headers['charset'])] #start_response(kk5.headers['status'], response_headers) # build the response body possibly using the environ dictionary response_body = 'The request method was %s' % environ['REQUEST_METHOD'] response_body += '
' response_body += str(r.debug()) # HTTP response code and message status = '200 OK' # These are HTTP headers expected by the client. # They must be wrapped as a list of tupled pairs: # [(Header name, Header value)]. response_headers = [('Content-Type', 'text/plain'), ('Content-Length', str(len(response_body)))] # Send them to the server using the supplied function start_response(status, response_headers) # Return the response body. # Notice it is wrapped in a list although it could be any iterable. return [response_body] Following script was not working. I have to re import pprint from registry. Is it normal or what is my problem :) Regards From e_d_k at yahoo.com Fri Dec 11 17:31:46 2009 From: e_d_k at yahoo.com (Ed Keith) Date: Fri, 11 Dec 2009 14:31:46 -0800 (PST) Subject: a list/re problem In-Reply-To: Message-ID: <209904.86219.qm@web58907.mail.re1.yahoo.com> --- On Fri, 12/11/09, Peter Otten <__peter__ at web.de> wrote: > From: Peter Otten <__peter__ at web.de> > Subject: Re: a list/re problem > To: python-list at python.org > Date: Friday, December 11, 2009, 4:24 PM > Ed Keith wrote: > > > I have a problem and I am trying to find a solution to > it that is both > > efficient and elegant. > > > > I have a list call it 'l': > > > > l = ['asc', '*nbh*', 'jlsdjfdk', 'ikjh', > '*jkjsdfjasd*', 'rewr'] > > > > Notice that some of the items in the list start and > end with an '*'. I > > wish to construct a new list, call it 'n' which is all > the members of l > > that start and end with '*', with the '*'s removed. > > > > So in the case above n would be ['nbh', 'jkjsdfjasd'] > > > > the following works: > > > > r = re.compile('\*(.+)\*') > > > > def f(s): > >? ???m = r.match(s) > >? ???if m: > >? ? ? ???return > m.group(1) > >? ???else: > >? ? ? ???return '' > > > > n =? [f(x) for x in l if r.match(x)] > > > > > > > > But it is inefficient, because it is matching the > regex twice for each > > item, and it is a bit ugly. > > > > I could use: > > > > > > n = [] > > for x in keys: > >? ???m = r.match(x) > >? ? ? ???if m: > >? ? ? ? ? > ???n.append(m.group(1)) > > > > > > It is more efficient, but much uglier. > > It's efficient and easy to understand; maybe you have to > readjust your > taste. > > > Does anyone have a better solution? > > In this case an approach based on string slicing is > probably best. When the > regular expression gets more complex you can use a nested a > generator > expression: > > >>> items = ['asc', '*nbh*', 'jlsdjfdk', 'ikjh', > '*jkjsdfjasd*', 'rewr'] > >>> match = re.compile(r"\*(.+)\*").match > >>> [m.group(1) for m in (match(s) for s in items) > if m is not None] > ['nbh', 'jkjsdfjasd'] > I am going to use string slicing, re is the wrong tool for the job. But this is what I was looking for when I posted. Simple, elegant and efficient. Thanks all, -EdK Ed Keith e_d_k at yahoo.com Blog: edkeith.blogspot.com From census at no-email.de Fri Dec 11 17:39:48 2009 From: census at no-email.de (census) Date: Fri, 11 Dec 2009 23:39:48 +0100 Subject: Caps Lock State on Windows References: Message-ID: N3wCr4Zy wrote: > how to i get Caps Lock state (on/off) on windows with win32api? public static extern short GetKeyState(int keyCode) in user32.dll From steve at REMOVE-THIS-cybersource.com.au Fri Dec 11 18:03:51 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 11 Dec 2009 23:03:51 GMT Subject: eiger replacement? References: Message-ID: <00ac5472$0$15654$c3e8da3@news.astraweb.com> On Fri, 11 Dec 2009 17:45:24 +0000, Robin Becker wrote: > The current hardware > > CPU: Intel(R) Pentium(R) 4 CPU 2.40GHz (2394.01-MHz 686-class CPU) [...] What does this have to do with Python? -- Steven From pavlovevidence at gmail.com Fri Dec 11 18:16:58 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 11 Dec 2009 15:16:58 -0800 (PST) Subject: datetime 'NoneType' sporadic error References: <2aa669fb-d0ee-4fdc-b5aa-97d727103729@p35g2000yqh.googlegroups.com> Message-ID: On Dec 11, 12:33?pm, bfrederi wrote: > When using the datetime module, I sporadically get " 'NoneType' object > has no attribute 'datetime' " on line 40:http://dpaste.com/hold/132156/ > > Sorry, I don't have the traceback, this is an error that was sent to > me by one of the users. It only happens occasionally. My guess is somewhere in your code the symbol datetime is being used as a variable. That is, you're doing something like datetime = x. This shadows the module. Carl Banks From Brian.Mingus at Colorado.EDU Fri Dec 11 18:35:00 2009 From: Brian.Mingus at Colorado.EDU (Brian J Mingus) Date: Fri, 11 Dec 2009 16:35:00 -0700 Subject: Which graph library is best suited for large graphs? In-Reply-To: <20091211101212.GC5712@kinakuta.local> References: <20091211101212.GC5712@kinakuta.local> Message-ID: <9839a05c0912111535u6ee11310h76830b2dac1663b@mail.gmail.com> On Fri, Dec 11, 2009 at 3:12 AM, Wolodja Wentland < wentland at cl.uni-heidelberg.de> wrote: > Hi all, > > I am writing a library for accessing Wikipedia data and include a module > that generates graphs from the Link structure between articles and other > pages (like categories). > > These graphs could easily contain some million nodes which are frequently > linked. The graphs I am building right now have around 300.000 nodes > with an average in/out degree of - say - 4 and already need around 1-2GB of > memory. I use networkx to model the graphs and serialise them to files on > the disk. (using adjacency list format, pickle and/or graphml). > > The recent thread on including a graph library in the stdlib spurred my > interest and introduced me to a number of libraries I have not seen > before. I would like to reevaluate my choice of networkx and need some > help in doing so. > > I really like the API of networkx but have no problem in switching to > another one (right now) .... I have the impression that graph-tool might > be faster and have a smaller memory footprint than networkx, but am > unsure about that. > > Which library would you choose? This decision is quite important for me > as the choice will influence my libraries external interface. Or is > there something like WSGI for graph libraries? > > kind regards > I once computed the PageRank of the English Wikipedia. I ended up using the Boost graph library, of which there is a parallel implementation that runs on clusters. I tried to do it using Python but failed as the memory requirements were so large. Boost and the parallel version both have python interfaces. -------------- next part -------------- An HTML attachment was scrubbed... URL: From johnkduffy at gmail.com Fri Dec 11 18:56:04 2009 From: johnkduffy at gmail.com (ObservantP) Date: Fri, 11 Dec 2009 15:56:04 -0800 (PST) Subject: pyserial - escape codes transportation References: <1cdd3691-2855-4406-8953-9be1b1f86a71@v30g2000yqm.googlegroups.com> Message-ID: <52f59358-96c1-4798-9abb-68b4ffcf1b71@s20g2000yqd.googlegroups.com> On Dec 11, 7:58?pm, Grant Edwards wrote: > On 2009-12-11, Grant Edwards wrote: > > > On 2009-12-11, ObservantP wrote: > >> need help. newbie. pyserial and dot matrix printer. issue- > >> escape codes arrive at printer ( verified from hex dump) but > >> do not get applied. > > > What you're saying is your printer isn't working correctly. > > BTW, I (among others) filter out all posts made from google > groups. I only stumbled across your posting by accident while > playing with my newsreader configuration. ?I won't see any > follow-up postings you make if they're from google groups. > > -- > Grant Edwards ? ? ? ? ? ? ? ? ? grante ? ? ? ? ? ? Yow! ! ?Everybody out of > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? at ? ? ? ? ? ? ? the GENETIC POOL! > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?visi.com ? ? ? ? ? ? Hi Grant Thanks for the tip. Had used the hex version alright. Looking again at the code, one realizes the difference between 'W' and 'w'... Sorted. All is well. Delighted to get this resolved. John From steve at holdenweb.com Fri Dec 11 19:12:39 2009 From: steve at holdenweb.com (Steve Holden) Date: Fri, 11 Dec 2009 19:12:39 -0500 Subject: Object Relational Mappers are evil (a meditation) In-Reply-To: <7xzl7s7306.fsf@ruckus.brouhaha.com> References: <06532563-3f2b-4cca-802f-34cb326e6d9f@v20g2000vbs.googlegroups.com> <7iv0r2F32cbsaU1@mid.uni-berlin.de> <7xhbu0qri8.fsf@ruckus.brouhaha.com> <7xzl7s7306.fsf@ruckus.brouhaha.com> Message-ID: <4B22DFF7.5090607@holdenweb.com> Paul Rubin wrote: > Mick Krippendorf writes: >>>> If I knew what First Anormal Form was I (hope!) >> I read it somewhere once, I just can't find or even remember the source. >> I definitely didn't make it up, though I wish I had. > > I found exactly one google hit for it, which is this clpy thread. It's a pun on First Normal Form. To transform a schema into First Normal Form you remove repeating groups from the entity and place them in a newly-created entity, leaving a copy of the identifier column behind to express a relationship between the two. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ UPCOMING EVENTS: http://holdenweb.eventbrite.com/ From steve at holdenweb.com Fri Dec 11 19:12:39 2009 From: steve at holdenweb.com (Steve Holden) Date: Fri, 11 Dec 2009 19:12:39 -0500 Subject: Object Relational Mappers are evil (a meditation) In-Reply-To: <7xzl7s7306.fsf@ruckus.brouhaha.com> References: <06532563-3f2b-4cca-802f-34cb326e6d9f@v20g2000vbs.googlegroups.com> <7iv0r2F32cbsaU1@mid.uni-berlin.de> <7xhbu0qri8.fsf@ruckus.brouhaha.com> <7xzl7s7306.fsf@ruckus.brouhaha.com> Message-ID: <4B22DFF7.5090607@holdenweb.com> Paul Rubin wrote: > Mick Krippendorf writes: >>>> If I knew what First Anormal Form was I (hope!) >> I read it somewhere once, I just can't find or even remember the source. >> I definitely didn't make it up, though I wish I had. > > I found exactly one google hit for it, which is this clpy thread. It's a pun on First Normal Form. To transform a schema into First Normal Form you remove repeating groups from the entity and place them in a newly-created entity, leaving a copy of the identifier column behind to express a relationship between the two. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ UPCOMING EVENTS: http://holdenweb.eventbrite.com/ From steve at holdenweb.com Fri Dec 11 19:20:21 2009 From: steve at holdenweb.com (Steve Holden) Date: Fri, 11 Dec 2009 19:20:21 -0500 Subject: Object Relational Mappers are evil (a meditation) In-Reply-To: <50f98a4c0910060810k3a4fa910vabc5bf51381d00f9@mail.gmail.com> References: <06532563-3f2b-4cca-802f-34cb326e6d9f@v20g2000vbs.googlegroups.com> <16a44521-1f07-454a-ace7-9ba5d5db4b9c@y28g2000prd.googlegroups.com> <50f98a4c0910060810k3a4fa910vabc5bf51381d00f9@mail.gmail.com> Message-ID: <4B22E1C5.50201@holdenweb.com> Simon Forman wrote: [...] > As far as the OP rant goes, my $0.02: bad programmers will write bad > code in any language, with any tool or system or environment they're > given. If you want to avoid bad code there's (apparently) no > substitute for smrt programmers who are familiar with the tools > they're using, not just the syntax but the underlying conceptual > models as well. > Hear, hear! regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ UPCOMING EVENTS: http://holdenweb.eventbrite.com/ From steve at holdenweb.com Fri Dec 11 19:20:21 2009 From: steve at holdenweb.com (Steve Holden) Date: Fri, 11 Dec 2009 19:20:21 -0500 Subject: Object Relational Mappers are evil (a meditation) In-Reply-To: <50f98a4c0910060810k3a4fa910vabc5bf51381d00f9@mail.gmail.com> References: <06532563-3f2b-4cca-802f-34cb326e6d9f@v20g2000vbs.googlegroups.com> <16a44521-1f07-454a-ace7-9ba5d5db4b9c@y28g2000prd.googlegroups.com> <50f98a4c0910060810k3a4fa910vabc5bf51381d00f9@mail.gmail.com> Message-ID: <4B22E1C5.50201@holdenweb.com> Simon Forman wrote: [...] > As far as the OP rant goes, my $0.02: bad programmers will write bad > code in any language, with any tool or system or environment they're > given. If you want to avoid bad code there's (apparently) no > substitute for smrt programmers who are familiar with the tools > they're using, not just the syntax but the underlying conceptual > models as well. > Hear, hear! regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ UPCOMING EVENTS: http://holdenweb.eventbrite.com/ From mnordhoff at mattnordhoff.com Fri Dec 11 19:21:10 2009 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Sat, 12 Dec 2009 00:21:10 +0000 Subject: a list/re problem In-Reply-To: References: Message-ID: <4B22E1F6.10101@mattnordhoff.com> Grant Edwards wrote: > On 2009-12-11, Ed Keith wrote: >> I have a problem and I am trying to find a solution to it that is both >> efficient and elegant. >> >> I have a list call it 'l': >> >> l = ['asc', '*nbh*', 'jlsdjfdk', 'ikjh', '*jkjsdfjasd*', 'rewr'] > >> Notice that some of the items in the list start and end with >> an '*'. I wish to construct a new list, call it 'n' which is >> all the members of l that start and end with '*', with the >> '*'s removed. >> >> So in the case above n would be ['nbh', 'jkjsdfjasd'] > > [s[1:-1] for s in l if (s[0] == s[-1] == '*')] s[0] and s[-1] raise an IndexError if l contains an empty string. Better something like: >>> [s[1:-1] for s in l if (s[:1] == s[-1:] == '*')] Or just the slightly more verbose startswith/endswith version. -- Matt Nordhoff From gagsl-py2 at yahoo.com.ar Fri Dec 11 20:13:50 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 11 Dec 2009 22:13:50 -0300 Subject: MySQL set and enum, calling values References: <4dc0cfea0912111008x5fb47e8dv5a9091cbe67ec4c8@mail.gmail.com> <4dc0cfea0912111128w48b072bfsd7d8c29445c5f81d@mail.gmail.com> Message-ID: En Fri, 11 Dec 2009 16:28:23 -0300, Victor Subervi escribi?: > On Fri, Dec 11, 2009 at 3:12 PM, Carsten Haese > wrote: > >> Victor Subervi wrote: >> > [...] if I go to print, say, >> > colFieldValues[20], which is a set, it prints out the whole set: >> > >> set('Extra-small','Small','Medium','Large','XLarge','XXLarge','XXXLarge') >> > But if I print out colFieldValues[20][0], it prints out "s". >> >> > Also, how can I test >> > for it? It's an instance of string. How do I know if it's a set? >> >> That's a fantastic question. Python thinks it's a string. What makes you >> think it's a set? > > Right. I'm doing it the ugly way with the truncating tuple and string > replace. Are you sure the column is declared as SET and not, say, VARCHAR? Anyway, I don't think MySQLdb is able to handle the SET data type correctly. -- Gabriel Genellina From tyler at monkeypox.org Fri Dec 11 20:23:19 2009 From: tyler at monkeypox.org (tyler at monkeypox.org) Date: Fri, 11 Dec 2009 17:23:19 -0800 Subject: When to use mechanize and Windmill library during WebScraping ? In-Reply-To: <23e3fbb60912110956q2716f7dbk35b7da7fea14dcaa@mail.gmail.com> References: <23e3fbb60912110956q2716f7dbk35b7da7fea14dcaa@mail.gmail.com> Message-ID: <20091212012319.GD18229@banana.sharlinx.com> On Fri, 11 Dec 2009, Raji Seetharaman wrote: > Hi > > For 'Webscraping with Python' mechanize or urllib2 and windmill or selenium > libraries are used to download the webpages. > > http://www.packtpub.com/article/web-scraping-with-python Be sure to look at Scrapy too: http://scrapy.org Cheers, -R. Tyler Ballance -------------------------------------- Jabber: rtyler at jabber.org GitHub: http://github.com/rtyler Twitter: http://twitter.com/agentdero Blog: http://unethicalblogger.com -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 198 bytes Desc: not available URL: From steve at REMOVE-THIS-cybersource.com.au Fri Dec 11 20:49:58 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 12 Dec 2009 01:49:58 GMT Subject: Using hash to see if object's attributes have changed References: <9e670042-394f-43bb-8b97-2a14346a64ab@o9g2000prg.googlegroups.com> Message-ID: <00ac7b60$0$15654$c3e8da3@news.astraweb.com> On Fri, 11 Dec 2009 10:03:06 -0800, Bryan wrote: > When a user submits a request to update an object in my web app, I make > the changes in the DB, along w/ who last updated it and when. I only > want to update the updated/updatedBy columns in the DB if the data has > actually changed however. > > I'm thinking of having the object in question be able to return a list > of its values that constitute its state. Then I can take a hash of that > list as the object exists in the database before the request, Storing the entire object instead of the hash is not likely to be *that* much more expensive. We're probably talking about [handwaves] a few dozen bytes versus a few more dozen bytes -- trivial in the large scheme of things. So give the object a __ne__ method, store a copy of the object, and do this: if current_object != existing_object: update(...) > and then > on the object that the user has made changes to. If they are not equal, > the user has changed the object. If all you care about is a flag that says whether the state has changed or not, why don't you add a flag "changed" to the object and update it as needed? if current_object.changed: update(...) current_object.changed = False That would require all attributes be turned into properties, but that shouldn't be hard. Or use a datestamp instead of a flag: if current_object.last_changed > database_last_changed: update(...) > I imagine it working something like this: > > def getValues(obj): > return [obj.a, obj.b, obj.c] > > foo = Obj() > foo.a = foo.b = foo.c = 1 > stateBefore = hashlib.sha1(str(getValues(foo))) > foo.b = 'changed' > stateNow = hashlib.sha1(str(getValues(foo))) > assert stateBefore != stateNow You probably don't need a cryptographically strong hash. Just add a __hash__(self) method to your class: def MyObject(object): # or whatever it is called def __hash__(self): t = (self.a, self.b, self.c) return hash(t) stateNow = hash(foo) In fact, why bother with hashing it? Just store the tuple itself, or a serialized version of it, and compare that. > I originally thought about running the hash on the __dict__ attribute, > but there may be things in there that don't actually constitute the > object's state as far as the database is concerned, so I thought it > better to have each object be responsible for returning a list of values > that constitute its state as far as the DB is concerned. > > I would appreciate any insight into why this is a good/bad idea given > your past experiences. Call me paranoid if you like, but I fear collisions. Even cryptographically strong hashes aren't collision-free (mathematically, they can't be). Even though the chances of a collision might only be one in a trillion-trillion-trillion, some user might be unlucky and stumble across such a collision, leading to a bug that might cause loss of data. As negligible as the risk is, why take that chance if there are ways of detecting changes that are just as good and probably faster? Hash functions have their uses, but I don't think that this is one of them. -- Steven From steve at REMOVE-THIS-cybersource.com.au Fri Dec 11 20:55:51 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 12 Dec 2009 01:55:51 GMT Subject: a list/re problem References: Message-ID: <00ac7cc2$0$15654$c3e8da3@news.astraweb.com> On Fri, 11 Dec 2009 12:49:42 -0800, Ed Keith wrote: > I have a problem and I am trying to find a solution to it that is both > efficient and elegant. > > I have a list call it 'l': > > l = ['asc', '*nbh*', 'jlsdjfdk', 'ikjh', '*jkjsdfjasd*', 'rewr'] > > Notice that some of the items in the list start and end with an '*'. I > wish to construct a new list, call it 'n' which is all the members of l > that start and end with '*', with the '*'s removed. > > So in the case above n would be ['nbh', 'jkjsdfjasd'] > > the following works: > > r = re.compile('\*(.+)\*') [snip] Others have suggested using a list comp. Just to be different, here's a version using filter and map. l = ['asc', '*nbh*', 'jlsdjfdk', 'ikjh', '*jkjsdfjasd*', 'rewr'] l = map( lambda s: s[1:-1] if s.startswith('*') and s.endswith('*') else '', l) l = filter(None, l) -- Steven From steve at REMOVE-THIS-cybersource.com.au Fri Dec 11 20:56:40 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 12 Dec 2009 01:56:40 GMT Subject: Object Relational Mappers are evil (a meditation) References: <06532563-3f2b-4cca-802f-34cb326e6d9f@v20g2000vbs.googlegroups.com> <16a44521-1f07-454a-ace7-9ba5d5db4b9c@y28g2000prd.googlegroups.com> <50f98a4c0910060810k3a4fa910vabc5bf51381d00f9@mail.gmail.com> Message-ID: <00ac7cf3$0$15654$c3e8da3@news.astraweb.com> On Fri, 11 Dec 2009 19:20:21 -0500, Steve Holden wrote: > Simon Forman wrote: > [...] >> As far as the OP rant goes, my $0.02: bad programmers will write bad >> code in any language, with any tool or system or environment they're >> given. If you want to avoid bad code there's (apparently) no >> substitute for smrt programmers who are familiar with the tools they're >> using, not just the syntax but the underlying conceptual models as >> well. >> > Hear, hear! That's all very well, but some languages and techniques encourage the programmer to write bad code. -- Steven From solipsis at pitrou.net Fri Dec 11 21:14:40 2009 From: solipsis at pitrou.net (Antoine Pitrou) Date: Sat, 12 Dec 2009 02:14:40 +0000 (UTC) Subject: Recommendation for small, fast, Python based web server References: <1260387281.5558.1349282363@webmail.messagingengine.com> <4b2291cf$0$22918$e4fe514c@news.xs4all.nl> Message-ID: Le Fri, 11 Dec 2009 19:40:21 +0100, Irmen de Jong a ?crit?: > > I don't think that number is fair for Python. I think a well written > Python web server can perform in the same ballpark as most mainstream > web servers written in C. Especially Apache, which really isn't a top > performer. And I'm pretty sure a well written Python server can > outperform a badly written C based server easily. The order of magnitude I gave is based on real-world testing. You are under-estimating how much of an impact Python's interpretation speed has on low-level code. Even Apache *is* a top performer compared to Python web servers. From gagsl-py2 at yahoo.com.ar Fri Dec 11 21:18:53 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 11 Dec 2009 23:18:53 -0300 Subject: How can I get the target platform info of a dll with Python 3.1.1? References: <01772f90-856c-4723-9f72-366a5d088ed5@k4g2000yqb.googlegroups.com> Message-ID: En Fri, 11 Dec 2009 16:39:37 -0300, Isti escribi?: > I have many dll files and I would like to select them into two > different folders (PC and PPC). For this I need to know the target > platform of the dll file or any other details about its platform. Look at sys.platform and the platform module. -- Gabriel Genellina From debatem1 at gmail.com Fri Dec 11 21:48:34 2009 From: debatem1 at gmail.com (geremy condra) Date: Fri, 11 Dec 2009 21:48:34 -0500 Subject: Which graph library is best suited for large graphs? In-Reply-To: <20091211101212.GC5712@kinakuta.local> References: <20091211101212.GC5712@kinakuta.local> Message-ID: On Fri, Dec 11, 2009 at 5:12 AM, Wolodja Wentland wrote: > Hi all, > > I am writing a library for accessing Wikipedia data and include a module > that generates graphs from the Link structure between articles and other > pages (like categories). > > These graphs could easily contain some million nodes which are frequently > linked. The graphs I am building right now have around 300.000 nodes > with an average in/out degree of - say - 4 and already need around 1-2GB of > memory. I use networkx to model the graphs and serialise them to files on > the disk. (using adjacency list format, pickle and/or graphml). Huh. Using graphine- which should be somewhat more memory hungry than networkx- I generated a naive million node 4-cycle graph and wound up using something under 600 meg of ram. Can you post some code? Geremy Condra From fordhaivat at gmail.com Fri Dec 11 21:50:52 2009 From: fordhaivat at gmail.com (Someone Something) Date: Fri, 11 Dec 2009 21:50:52 -0500 Subject: Open source projects Message-ID: I'm a pretty okay python programmer and I really want to start developing for an open source project. I'm looking for one that preferably deals with networking and isn't as huge as twisted (that's just a preference, not extremely important). Could anyone suggest any projects? I also know C, Perl, Ruby and Java (java least preferred). -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Fri Dec 11 21:52:26 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 11 Dec 2009 23:52:26 -0300 Subject: Problems with debugging Lists References: <200912120011.38311.sancar.saran@evodot.com> Message-ID: En Fri, 11 Dec 2009 19:11:38 -0300, Sancar Saran escribi?: > In php we had print_r function to see entire array structure. After some > search I found some equal module named pprint. > > And some how this module wont work with mod_wsgi it was something about > mod_wsgi portability standards. > > After some research there where some thing about putting some variables > in > apache config to disable this. > > And now I can see some dictionary structure in my apache log and I got > some > errors like > r += pprint.pprint(self.data) > TypeError: cannot concatenate 'str' and 'NoneType' objects The pprint function in the pprint module (that is, pprint.pprint) *prints* its argument, and returns nothing -- or, better said, it returns None (same as print_r in PHP, without the return parameter set to true) > So is there any way to get dictionary structure in string format ? You don't need anything special for that. There are two built-in functions that convert any object to string: str and repr. str(x) provides a simple representation of x (whatever it is), and repr(x) provides a more technical view; when possible, eval(repr(x)) should return x. For debugging purposes, repr() is your friend. pprint.pformat is like the built-in repr(), but provides a better formatted representation, with indenting, a maximum width, etc. > Another question is. When I import a module from top is it available for > later > imported modules Each module contains its own, separate namespace. If you `import foo` in some module, the name `foo` becomes available to be used in that module -- if you want to use `foo` in another module, you have to `import foo` in that other module too. Don't worry; after the very first import (which involves locating the module, loading and compiling it if necesary, and writing the .pyc file) any subsequent imports of the same module just return a new reference to the existing, in-memory module object. -- Gabriel Genellina From fonnesbeck at gmail.com Fri Dec 11 21:55:00 2009 From: fonnesbeck at gmail.com (hardcoreUFO) Date: Fri, 11 Dec 2009 18:55:00 -0800 (PST) Subject: umath import error for Numpy builds on OSX 10.6 References: <6b6c00c1-edb8-4469-ab3c-af886aee841f@v15g2000prn.googlegroups.com> Message-ID: <762e37ef-b06a-400c-a61a-125775cb3940@k13g2000prh.googlegroups.com> On Dec 11, 5:47?pm, Robert Kern wrote: > Right, when the -lnpymath stuff got checked in. Looking at the build log you > posted to numpy-discusson, it does appear that the $LDFLAGS is obliterating the > intended flags. Please post a build log without setting those flags to > numpy-discussion. A correct link line should look something like this: > > gcc -arch i386 -arch ppc -isysroot /Developer/SDKs/MacOSX10.4u.sdk -g -bundle > -undefined dynamic_lookup > build/temp.macosx-10.3-i386-2.5/numpy/core/src/umath/umathmodule_onefile.o > -Lbuild/temp.macosx-10.3-i386-2.5 -lnpymath -o > build/lib.macosx-10.3-i386-2.5/numpy/core/umath.so Thanks Robert, Here is the log from a build without the LDFLAGS set. Having a quick look, all I can see are a few warnings and a CAPI version mismatch message. Any insight most appreciated. The build still gives the same umath error. cf From fonnesbeck at gmail.com Fri Dec 11 22:00:03 2009 From: fonnesbeck at gmail.com (hardcoreUFO) Date: Fri, 11 Dec 2009 19:00:03 -0800 (PST) Subject: umath import error for Numpy builds on OSX 10.6 References: <6b6c00c1-edb8-4469-ab3c-af886aee841f@v15g2000prn.googlegroups.com> <762e37ef-b06a-400c-a61a-125775cb3940@k13g2000prh.googlegroups.com> Message-ID: <6f9c7c8e-bc4c-4a5a-b502-977d37cdd412@d9g2000prh.googlegroups.com> On Dec 12, 3:55?pm, hardcoreUFO wrote: > Here is the log from a build without the LDFLAGS set. ?Having a quick > look, all I can see are a few warnings and a CAPI version mismatch > message. Any insight most appreciated. The build still gives the same > umath error. Sorry, forgot to post the log: http://files.me.com/fonnesbeck/giaoql From tjreedy at udel.edu Fri Dec 11 22:59:45 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 11 Dec 2009 22:59:45 -0500 Subject: Open source projects In-Reply-To: References: Message-ID: Someone Something wrote: > I'm a pretty okay python programmer and I really want to start > developing for an open source project. I'm looking for one that > preferably deals with networking and isn't as huge as twisted (that's > just a preference, not extremely important). Could anyone suggest any > projects? I also know C, Perl, Ruby and Java (java least preferred). Helping port some 3rd party package to Python 3, twisted or otherwise, would be a great contribution to the community. The barrier for some groups is that they have just enough energy to maintain the package and forward port to 2.6 and the upcoming 2.7, but not enough extra to also make changes for 3.1. I am sure you can find some project of interest who people would welcome the extra help. tjr From me at firecrow.com Fri Dec 11 23:04:42 2009 From: me at firecrow.com (Fire Crow) Date: Fri, 11 Dec 2009 20:04:42 -0800 (PST) Subject: power of explicit self? Message-ID: <73d81fbc-95c5-4897-bca1-852471eb7938@q16g2000vbc.googlegroups.com> I'm looking for an explanation of how explicit self is implimented and what features are only possible because of, or are greatly improved, because of it. I've always liked explicit self and am looking for the computer science behind it, so that I can explain the benefits that I see. I'm also interested in the files/lines of the python source that shows how explicit self is implemented if anyone can point out where that takes place. all help welcome From afriere at yahoo.co.uk Fri Dec 11 23:13:46 2009 From: afriere at yahoo.co.uk (Asun Friere) Date: Fri, 11 Dec 2009 20:13:46 -0800 (PST) Subject: switch References: <335204.99872.qm@web57905.mail.re3.yahoo.com> <68e6e315-f3c7-4e52-a56f-802e99d75e6a@y32g2000prd.googlegroups.com> <9010003a-d129-46b4-9535-88b03f0bc121@w19g2000pre.googlegroups.com> Message-ID: On Dec 11, 1:38 am, Tim Chase wrote: > It's clean if it were the solution to my problem Picking out that line first, just to be clear about this. You missed the disclaimer. This was never meant to be a solution to your problem. It was solution to the problem contained in the code you posted. Carl, asked a question, in response you provided an example, and I wrote a solution. I did so to in order to illustrate how something resembling a dispatch mechansism can save a programmer from ending up with a "rat's-nest" of elif chainage. I hope you did not misunderstand me as advocating your pulling apart working production code. Heck, I wouldn't, err ...don't, do this. Which is _not_ to say that it isn't actually a solution your problem as well! :) >>[One guy analogy] > > This is where you make a false assumption Again "I don't really know your problem only the code you've posted." If I misunderstood the record types as originating from different providers, I'm sure you will find that my code, which faithfully reimplements yours, does not. > -- the contents and > parsing of the "switch" are provider-specific in this case, > mapping to a common ontology of the Phone object: > > class MonopolyProvider1Parser: > ... > switch row['recordtype']: > case '01': > phone.international += Decimal(row['internationalcost']) > // optionally a "break" here depending on > // C/C++/Java/PHP syntax vs. Pascal syntax which > // doesn't have fall-through > case '02': > phone.text_messaging += ( > int(row['textmessages sent']) + > int(row['pages received']) + > int(row['textmessages sent']) + > int(row['pages received']) > ... > default: > raise WhatTheHeckIsThis() > > class MonopolyProvider2Parser: > ... > switch row['recordtype']: > case 'abc': > phone.international += ( > Decimal(row['canada cost']) + > Decimal(row['eu cost']) + > Decimal(row['mexico cost']) + > Decimal(row['other intl cost']) > ) > case 'xyz': > phone.text_messaging += int(row['textmessages']) > ... > default: > raise WhatTheHeckIsThis() > Fair enough. What you posted was a subset of your overall problem. Obviously! Inasmuch as the code that you posted accurately represents a subset of your problem, the solution given is still applicable, at least to that subset of your problem. It's just that each inidividual MonopolyProvider will require its own set of data sources. In any case, I'm sure you could work out it could be applied, if you put your mind to it. I agree this involves more code than the example required, possibly for less gain and I believe it is still advantageous to organise the code in a way which separates knowledge from logic. At least when that knowledge is non-trivial. > > # The one thing I'm sure I don't understand from the code is where the > > original rectypes comes into the process. > Sorry, my worrying there about whether we need to look the appropriate RecType up in that dict was just a distraction. The problem isn't in the dict, but with that the try should only be trapping unknown types, not problems of instantiation. I should have written: try : AppropriateRecType = rectypes[rectype] except KeyError : raise WhatTheHeckIsThisError('unknown rectype: %s' % rectype) record = ApproriateRecType(row) > From the provider data -- sometimes CSV files, sometimes > tab-delimited text files, sometimes MS Access MDB files, > sometimes a web service... > varies per-provider (and some providers > have multiple formats, like Verizon has MyBIZ and IBAS; ATT has > their WinCD and Premier; etc). No two formats are the same, so > the logic needed to parse the data into our internal homogenized > Phone data structure varies per each one. And the logic (or lack > thereof) used by many providers in creating their formats require > reverse-engineering most of them through trial-and-error, and > huge ugly if/elif/else chains. I feel your pain, I really do ... and a dispatch mechanism could relieve some of it. ;) Now I'm not saying you should implement it on extant production code. As I wrote above, I still use, and unfortunately maintain, older code which is a hideous mess of elif chains. The task of challenging these elif chains is daunting, and rewriting such working code won't rank in my work priorities for the foreseeable future. This is why, elif chains, when they first arise, or better perhaps, when they first begin to grow, should be examined to see whether they are a bud that ought to be nipped, whether they sensibly can be nipped, and if so how. They are, in Carl's words, "red flags," at least they are if your're "not a very good progammer," like me. I invite all my fellow NVGPs to treat them as such as well. :) I can compare extending and maintaining code I wrote using old school elifs and flags to that written using the State and dispatch patterns, (code which python makes practicable). OO makes life easier for an older NVGP such as myself, a young gun like you might not need to rely on clear code. ;) From tkjthingone at gmail.com Fri Dec 11 23:41:58 2009 From: tkjthingone at gmail.com (Horace Blegg) Date: Fri, 11 Dec 2009 20:41:58 -0800 Subject: Spawning an interactive interpreter in a running python process? Message-ID: Hello List, I'm curious, in an academic sense, if it's possible to spawn the interactive interpreter (>>>) in a running python application. Ideally, I would like to be able to access the modules, functions and variables the application can. Is something like this possible? If not, would I be able to implement something like this on my own? Thank you. -------------- next part -------------- An HTML attachment was scrubbed... URL: From robert.kern at gmail.com Fri Dec 11 23:44:43 2009 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 11 Dec 2009 22:44:43 -0600 Subject: umath import error for Numpy builds on OSX 10.6 In-Reply-To: <762e37ef-b06a-400c-a61a-125775cb3940@k13g2000prh.googlegroups.com> References: <6b6c00c1-edb8-4469-ab3c-af886aee841f@v15g2000prn.googlegroups.com> <762e37ef-b06a-400c-a61a-125775cb3940@k13g2000prh.googlegroups.com> Message-ID: On 2009-12-11 20:55 PM, hardcoreUFO wrote: > On Dec 11, 5:47 pm, Robert Kern wrote: > >> Right, when the -lnpymath stuff got checked in. Looking at the build log you >> posted to numpy-discusson, it does appear that the $LDFLAGS is obliterating the >> intended flags. Please post a build log without setting those flags to >> numpy-discussion. A correct link line should look something like this: >> >> gcc -arch i386 -arch ppc -isysroot /Developer/SDKs/MacOSX10.4u.sdk -g -bundle >> -undefined dynamic_lookup >> build/temp.macosx-10.3-i386-2.5/numpy/core/src/umath/umathmodule_onefile.o >> -Lbuild/temp.macosx-10.3-i386-2.5 -lnpymath -o >> build/lib.macosx-10.3-i386-2.5/numpy/core/umath.so > > Thanks Robert, > > Here is the log from a build without the LDFLAGS set. Having a quick > look, all I can see are a few warnings and a CAPI version mismatch > message. Any insight most appreciated. The build still gives the same > umath error. On numpy-discussion, please. But first, start with a clean checkout. I think you have stale files. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From gagsl-py2 at yahoo.com.ar Fri Dec 11 23:47:53 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 12 Dec 2009 01:47:53 -0300 Subject: Caps Lock State on Windows References: Message-ID: En Thu, 10 Dec 2009 21:58:40 -0300, N3wCr4Zy escribi?: > how to i get Caps Lock state (on/off) on windows with win32api? py> from win32api import GetKeyState py> from win32con import VK_CAPITAL py> GetKeyState(VK_CAPITAL) # normal 0 py> GetKeyState(VK_CAPITAL) # CAPS LOCK set 1 See http://msdn.microsoft.com/en-us/library/ms645530(VS.85).aspx -- Gabriel Genellina From python.list at tim.thechases.com Fri Dec 11 23:49:33 2009 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 11 Dec 2009 22:49:33 -0600 Subject: Spawning an interactive interpreter in a running python process? In-Reply-To: References: Message-ID: <4B2320DD.6000100@tim.thechases.com> > I'm curious, in an academic sense, if it's possible to spawn the > interactive interpreter (>>>) in a running python application. Ideally, I > would like to be able to access the modules, functions and variables the > application can. > > Is something like this possible? While not exactly "the interactive interpreter", you can use pdb to drop to a debugging prompt where you can "access the modules, functions and variables the application can". The common idiom is to insert a line like import pdb; pdb.set_trace() in your code to have a break-point stop execution at the designated point and leave you at a prompt where you can explore. -tkc From tkjthingone at gmail.com Sat Dec 12 00:11:27 2009 From: tkjthingone at gmail.com (Horace Blegg) Date: Fri, 11 Dec 2009 21:11:27 -0800 Subject: Spawning an interactive interpreter in a running python process? In-Reply-To: <4B2320DD.6000100@tim.thechases.com> References: <4B2320DD.6000100@tim.thechases.com> Message-ID: *I really must get in the habit of replying to all, and not just replying*. Ahh, I didn't know it could do that. I will go experiment. But from what you said, it doesn't seem like one could do that on the fly. It actually requires altering the app, and then running it again. I wonder if I could cook something up with PyRun_SimpleString("import pdb; pdb.set_trace()"). This bears investigation! Cheers! -------------- next part -------------- An HTML attachment was scrubbed... URL: From timr at probo.com Sat Dec 12 00:38:47 2009 From: timr at probo.com (Tim Roberts) Date: Fri, 11 Dec 2009 21:38:47 -0800 Subject: eiger replacement? References: <00ac5472$0$15654$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: >On Fri, 11 Dec 2009 17:45:24 +0000, Robin Becker wrote: > >> The current hardware >> >> CPU: Intel(R) Pentium(R) 4 CPU 2.40GHz (2394.01-MHz 686-class CPU) >[...] > >What does this have to do with Python? I'm guessing Robin had a slight address book malfunction when he sent this. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From gagsl-py2 at yahoo.com.ar Sat Dec 12 00:46:20 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 12 Dec 2009 02:46:20 -0300 Subject: Spawning an interactive interpreter in a running python process? References: <4B2320DD.6000100@tim.thechases.com> Message-ID: En Sat, 12 Dec 2009 02:11:27 -0300, Horace Blegg escribi?: > I wonder if I could cook something up with PyRun_SimpleString("import > pdb; > pdb.set_trace()"). This bears investigation! pdb is a debugger, and provides a lot more than you're looking for, I presume. You may want to look at the code [1] and cmd [2] modules too. [1] http://docs.python.org/library/code.html [2] http://docs.python.org/library/cmd.html -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Sat Dec 12 00:53:13 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 12 Dec 2009 02:53:13 -0300 Subject: power of explicit self? References: <73d81fbc-95c5-4897-bca1-852471eb7938@q16g2000vbc.googlegroups.com> Message-ID: En Sat, 12 Dec 2009 01:04:42 -0300, Fire Crow escribi?: > I'm looking for an explanation of how explicit self is implimented and > what features are only possible because of, or are greatly improved, > because of it. I've always liked explicit self and am looking for the > computer science behind it, so that I can explain the benefits that I > see. See the FAQ [1] > I'm also interested in the files/lines of the python source that shows > how explicit self is implemented if anyone can point out where that > takes place. Nowhere, I'd say. An *implicit* self would have to be implemented somewhere in the compiler -- but an explicit self doesn't. It's homogeneous, always name-dot-attribute; the name 'self' is not special at all. [1] http://www.python.org/doc/faq/general/#why-must-self-be-used-explicitly-in-method-definitions-and-calls -- Gabriel Genellina From daved170 at gmail.com Sat Dec 12 02:16:42 2009 From: daved170 at gmail.com (daved170) Date: Fri, 11 Dec 2009 23:16:42 -0800 (PST) Subject: read text file byte by byte Message-ID: Hello everybody, I need to read a text file byte after byte. Eache byte is sent to a function that scramble it and I need to write the result to binary file. I've got some questions - 1) How do I read the file byte by byte 2) Should I use streams? If so and I get my entire scrambled text in stream can I just write it to the binary file? Thanks Dave From victorsubervi at gmail.com Sat Dec 12 03:04:46 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Sat, 12 Dec 2009 03:04:46 -0500 Subject: MySQL set and enum, calling values In-Reply-To: References: <4dc0cfea0912111008x5fb47e8dv5a9091cbe67ec4c8@mail.gmail.com> <4dc0cfea0912111128w48b072bfsd7d8c29445c5f81d@mail.gmail.com> Message-ID: <4dc0cfea0912120004v7dc565f0j7dda52c32000a93a@mail.gmail.com> On Fri, Dec 11, 2009 at 8:13 PM, Gabriel Genellina wrote: > En Fri, 11 Dec 2009 16:28:23 -0300, Victor Subervi < > victorsubervi at gmail.com> escribi?: > > On Fri, Dec 11, 2009 at 3:12 PM, Carsten Haese > >wrote: >> >> Victor Subervi wrote: >>> > [...] if I go to print, say, >>> > colFieldValues[20], which is a set, it prints out the whole set: >>> > >>> set('Extra-small','Small','Medium','Large','XLarge','XXLarge','XXXLarge') >>> > But if I print out colFieldValues[20][0], it prints out "s". >>> >>> > Also, how can I test >>> > for it? It's an instance of string. How do I know if it's a set? >>> >>> That's a fantastic question. Python thinks it's a string. What makes you >>> think it's a set? >>> >> >> Right. I'm doing it the ugly way with the truncating tuple and string >> replace. >> > > Are you sure the column is declared as SET and not, say, VARCHAR? > yes > Anyway, I don't think MySQLdb is able to handle the SET data type > correctly. > Oh, lovely! What do? V -------------- next part -------------- An HTML attachment was scrubbed... URL: From rcdotsharma at gmail.com Sat Dec 12 03:19:20 2009 From: rcdotsharma at gmail.com (Sharma, R.C.) Date: Sat, 12 Dec 2009 17:19:20 +0900 Subject: Python for simulating BRDF Message-ID: <5a0900430912120019o3a8cf3c0jf71464f9dcf566ce@mail.gmail.com> Dear python users, Greetings. I would like to write a simulation program using Python language for simulating bidirectional reflectance distribution function (BRDF) obtained from multi-angular remote sensing. I have a program written in C language. Can I convert it into Python language? In Python, being a higher level programming language, do we encounter more problems in debugging while developing such simulating program? Thank you very much for your kind help in the advance. Sincerely, Sharma, R.C -------------- next part -------------- An HTML attachment was scrubbed... URL: From fetchinson at googlemail.com Sat Dec 12 04:28:14 2009 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Sat, 12 Dec 2009 10:28:14 +0100 Subject: Open source projects In-Reply-To: References: Message-ID: >> I'm a pretty okay python programmer and I really want to start >> developing for an open source project. I'm looking for one that >> preferably deals with networking and isn't as huge as twisted (that's >> just a preference, not extremely important). Could anyone suggest any >> projects? I also know C, Perl, Ruby and Java (java least preferred). Turbogears is a web application server framework which could definitely use help. It comes in two flavors, tg1 and tg2, they have their own trees and you would be more than welcome to help in either of them. See http://www.turbogears.org Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From sancar.saran at evodot.com Sat Dec 12 04:28:15 2009 From: sancar.saran at evodot.com (Sancar Saran) Date: Sat, 12 Dec 2009 11:28:15 +0200 Subject: Problems with debugging Lists In-Reply-To: References: <200912120011.38311.sancar.saran@evodot.com> Message-ID: <200912121128.15135.sancar.saran@evodot.com> On Saturday 12 December 2009 04:52:26 am Gabriel Genellina wrote: > En Fri, 11 Dec 2009 19:11:38 -0300, Sancar Saran > > escribi?: > > In php we had print_r function to see entire array structure. After some > > search I found some equal module named pprint. > > > > And some how this module wont work with mod_wsgi it was something about > > mod_wsgi portability standards. > > > > After some research there where some thing about putting some variables > > in > > apache config to disable this. > > > > And now I can see some dictionary structure in my apache log and I got > > some > > errors like > > r += pprint.pprint(self.data) > > TypeError: cannot concatenate 'str' and 'NoneType' objects > > The pprint function in the pprint module (that is, pprint.pprint) *prints* > its argument, and returns nothing -- or, better said, it returns None > (same as print_r in PHP, without the return parameter set to true) > > > So is there any way to get dictionary structure in string format ? > > You don't need anything special for that. There are two built-in functions > that convert any object to string: str and repr. str(x) provides a simple > representation of x (whatever it is), and repr(x) provides a more > technical view; when possible, eval(repr(x)) should return x. > For debugging purposes, repr() is your friend. > pprint.pformat is like the built-in repr(), but provides a better > formatted representation, with indenting, a maximum width, etc. > > > Another question is. When I import a module from top is it available for > > later > > imported modules > > Each module contains its own, separate namespace. If you `import foo` in > some module, the name `foo` becomes available to be used in that module -- > if you want to use `foo` in another module, you have to `import foo` in > that other module too. > > Don't worry; after the very first import (which involves locating the > module, loading and compiling it if necesary, and writing the .pyc file) > any subsequent imports of the same module just return a new reference to > the existing, in-memory module object. > Hello Gabriel, Thanks for support. repr works as you say and I had some complaints, it wont format the output. Finding some string in 100 key dictionary in formatted in single line bit problematic. Is it any way to format it ? Also, very interesting things are happen. def debug(self): r = '
'
	r += repr(self.data)
	r += '
' return r following code works and does not work ever reload ? One time work another reload wont work. What I missing ? And is possible to get this ? (I store the environ here) r += repr(self.data['environ']['mod_wsgi.listener_port']) or similar multi sub level elements ? Regards... From census at no-email.de Sat Dec 12 04:35:55 2009 From: census at no-email.de (census) Date: Sat, 12 Dec 2009 10:35:55 +0100 Subject: read text file byte by byte References: Message-ID: daved170 wrote: > Hello everybody, > I need to read a text file byte after byte. > Eache byte is sent to a function that scramble it > and I need to write the result to binary file. > > I've got some questions - > 1) How do I read the file byte by byte > 2) Should I use streams? If so and I get my entire scrambled text in > stream can I just write it to the binary file? > > Thanks > Dave f = open ("binaryfile", "r") bytearray = map (ord, f.read () ) Stores the content of binaryfile in the list bytearray. From census at no-email.de Sat Dec 12 04:46:01 2009 From: census at no-email.de (census) Date: Sat, 12 Dec 2009 10:46:01 +0100 Subject: read text file byte by byte References: Message-ID: daved170 wrote: > Hello everybody, > I need to read a text file byte after byte. > Eache byte is sent to a function that scramble it > and I need to write the result to binary file. > > I've got some questions - > 1) How do I read the file byte by byte > 2) Should I use streams? If so and I get my entire scrambled text in > stream can I just write it to the binary file? > > Thanks > Dave OK, now here a complete code to read a file byte by byte, scramble each byte (with a really complex algorithm in my example) and write the output to another file. def scramble (a): return (a + 13) % 256 infile = open ("binaryfile1", "r") outfile = open ("binaryfile2", "w") bytearray = map (ord, infile.read () ) scrambled = map (scramble, bytearray) map (lambda x : outfile.write (chr (x) ), scrambled) infile.close () outfile.flush () outfile.close () From steve at REMOVE-THIS-cybersource.com.au Sat Dec 12 05:31:49 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 12 Dec 2009 10:31:49 GMT Subject: read text file byte by byte References: Message-ID: <00acf5b1$0$15654$c3e8da3@news.astraweb.com> On Sat, 12 Dec 2009 10:35:55 +0100, census wrote: >> I've got some questions - >> 1) How do I read the file byte by byte 2) Should I use streams? If so >> and I get my entire scrambled text in stream can I just write it to the >> binary file? >> >> Thanks >> Dave > > f = open ("binaryfile", "r") > bytearray = map (ord, f.read () ) > > Stores the content of binaryfile in the list bytearray. If it's a binary file, you should open it in binary mode: f = open ("binaryfile", "rb") -- Steven From steve at REMOVE-THIS-cybersource.com.au Sat Dec 12 05:33:09 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 12 Dec 2009 10:33:09 GMT Subject: read text file byte by byte References: Message-ID: <00acf601$0$15654$c3e8da3@news.astraweb.com> On Fri, 11 Dec 2009 23:16:42 -0800, daved170 wrote: > Hello everybody, > I need to read a text file byte after byte. Eache byte is sent to a > function that scramble it and I need to write the result to binary file. > > I've got some questions - > 1) How do I read the file byte by byte f = open(filename, 'rb') f.read(1) will read a single byte. 2) Should I use streams? What do you mean by "streams"? -- Steven -- Steven From tkjthingone at gmail.com Sat Dec 12 06:12:52 2009 From: tkjthingone at gmail.com (Horace Blegg) Date: Sat, 12 Dec 2009 03:12:52 -0800 Subject: Spawning an interactive interpreter in a running python process? In-Reply-To: References: <4B2320DD.6000100@tim.thechases.com> Message-ID: Better and better! You know, I think I knew about those two, I just never connected the dots. With a little fiddling, I think I can cobble together what I want. My sincere thanks, sir/ma'am. On Fri, Dec 11, 2009 at 9:46 PM, Gabriel Genellina wrote: > En Sat, 12 Dec 2009 02:11:27 -0300, Horace Blegg > escribi?: > > > I wonder if I could cook something up with PyRun_SimpleString("import pdb; >> pdb.set_trace()"). This bears investigation! >> > > pdb is a debugger, and provides a lot more than you're looking for, I > presume. > You may want to look at the code [1] and cmd [2] modules too. > > [1] http://docs.python.org/library/code.html > [2] http://docs.python.org/library/cmd.html > > > -- > Gabriel Genellina > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From census at no-email.de Sat Dec 12 06:14:13 2009 From: census at no-email.de (census) Date: Sat, 12 Dec 2009 12:14:13 +0100 Subject: read text file byte by byte References: <00acf5b1$0$15654$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > On Sat, 12 Dec 2009 10:35:55 +0100, census wrote: > >>> I've got some questions - >>> 1) How do I read the file byte by byte 2) Should I use streams? If so >>> and I get my entire scrambled text in stream can I just write it to the >>> binary file? >>> >>> Thanks >>> Dave >> >> f = open ("binaryfile", "r") >> bytearray = map (ord, f.read () ) >> >> Stores the content of binaryfile in the list bytearray. > > If it's a binary file, you should open it in binary mode: > > f = open ("binaryfile", "rb") > > > Add the "b" flag to both in and out file if you prefer it: def scramble (a): return (a + 13) % 256 infile = open ("binin", "rb") outfile = open ("binout", "wb") bytearray = map (ord, infile.read () ) scrambled = map (scramble, bytearray) map (lambda x : outfile.write (chr (x) ), scrambled) infile.close () outfile.flush () outfile.close () From javier.collado at gmail.com Sat Dec 12 06:52:27 2009 From: javier.collado at gmail.com (Javier Collado) Date: Sat, 12 Dec 2009 12:52:27 +0100 Subject: When to use mechanize and Windmill library during WebScraping ? In-Reply-To: <23e3fbb60912110956q2716f7dbk35b7da7fea14dcaa@mail.gmail.com> References: <23e3fbb60912110956q2716f7dbk35b7da7fea14dcaa@mail.gmail.com> Message-ID: Hello, If a script that uses mechanize fails to find an html node that has been identified with Firebug, this is probably because that node has been autogenerated (provided that the expression to get the node is correct). As an alternative to verify this, you can try to download the html page and open it in your favourite editor. If some of the nodes that you can see in your browser are missing or empty, then one of the JavaScript scripts in the page should have created/populated it. If you're in doubt, you can try to use mechanize and, if you have problems such as the described above, then you can move to windmill or some other tool that executes JavaScript code before trying to get the desired data. Best regards, Javier 2009/12/11 Raji Seetharaman : > Hi > > For 'Webscraping with Python' mechanize or urllib2 and windmill or selenium > libraries are used? to download the webpages. > > http://www.packtpub.com/article/web-scraping-with-python > > The above link makes use of mechanize library to download the web pages. > > The below link uses windmill library to download the web pages. > > http://www.packtpub.com/article/web-scraping-with-python-part-2 > > I dont know when to use mechanize or windmill library > > It has been said that Windmill library is used when the HTML file is auto > generated by the JavaScript code. > > Also i dont know how to identify whether the HTML file is auto generated by > the JavaScript code or not ? > > Suggest me > > Thanks > > Raji. S > http://sraji.wordpress.com/ > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > > From tiago at forked.de Sat Dec 12 07:01:36 2009 From: tiago at forked.de (Tiago de Paula Peixoto) Date: Sat, 12 Dec 2009 10:01:36 -0200 Subject: Which graph library is best suited for large graphs? In-Reply-To: <20091211101212.GC5712@kinakuta.local> References: <20091211101212.GC5712@kinakuta.local> Message-ID: Hi there, On 12/11/2009 08:12 AM, Wolodja Wentland wrote: > I really like the API of networkx but have no problem in switching to > another one (right now) .... I have the impression that graph-tool might > be faster and have a smaller memory footprint than networkx, but am > unsure about that. I'm the author of graph-tool, so my opinion may be biased. :-) Nevertheless, I do think that graph-tool will be faster and have a smaller memory footprint than networkx, since the graph data structures and most algorithms are written in C++, using the Boost Graph Library, whereas networkx is mostly pure python. I have made this library due to my own requirements of being able to work with large graphs. The only other library I can think of which may be comparable in performance is igraph, which is implemented in C. But I think graph-tool's interface is a bit more polished (my opinion only). Moreover, since graph-tool uses template metaprograming to obtain specialized versions of algorithms, it may be that it is even faster than igraph, but I have at the moment no benchmarks to back this up. Cheers, Tiago -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 262 bytes Desc: OpenPGP digital signature URL: From tiago at forked.de Sat Dec 12 07:21:00 2009 From: tiago at forked.de (Tiago de Paula Peixoto) Date: Sat, 12 Dec 2009 10:21:00 -0200 Subject: Graph library for Python In-Reply-To: References: <4B1D35BC.5000002@egenix.com> <4B1D5CB3.8030805@egenix.com> <00a70ac5$0$15659$c3e8da3@news.astraweb.com> <4B1E464B.6090408@chamonix.reportlab.co.uk> Message-ID: On 12/10/2009 01:57 PM, Bearophile wrote: > Geremy Condra: >> Well, we all seem to have reinvented the wheel differently ;) > > Maybe also because they are designed for different purposes. This is true. For instance, the data structures and most algorithms in graph-tool are implemented in C++ to achieve good performance, which is necessary if you are working with very large graphs. I think this differs from most python graph libraries, which don't have this as a high priority. >> Bearophile, Tiago- any interest in trying to combine the >> best parts of our libraries, with an eye towards eventual >> integration into the standard library? > > The first thing to do is to ask Guido and Hettinger if they are > willing to put a "good" graph module into the std lib. If their answer > is positive for some definition of "good", then we can think about > doing something. A crucial element in this hypothetical module would be the main graph data structure. The simplest approach would be to implement it in pure python, with lists, dicts and such, as many libraries do. However, this would rule out its use by high-performance code, which would need a simpler C-based data structure for direct interaction. On the other hand, I'm not sure if there is a need for a high performance graph module in python's standard library... Cheers, Tiago -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 262 bytes Desc: OpenPGP digital signature URL: From makobu.mwambiriro at gmail.com Sat Dec 12 08:10:56 2009 From: makobu.mwambiriro at gmail.com (makobu) Date: Sat, 12 Dec 2009 05:10:56 -0800 (PST) Subject: parallelpython 1.5.7 crash Message-ID: Hi all, Hi all, with the above version of parallelpython, what causes this? Traceback (most recent call last): File "C:\Users\tim\code_base\svn\octopus\parallel_python\pp.py", line 762, in __run sresult = worker.t.receive() File "C:\Users\tim\code_base\svn\octopus\parallel_python \pptransport.py", line 133, in receive msg = self.r.read(msg_len) OverflowError: long int too large to convert to int Unhandled exception in thread started by > Traceback (most recent call last): File "C:\Users\tim\code_base\svn\octopus\parallel_python\pp.py", line 771, in __run job.finalize(sresult) UnboundLocalError: local variable 'sresult' referenced before assignment From kay at fiber-space.de Sat Dec 12 08:56:14 2009 From: kay at fiber-space.de (Kay Schluehr) Date: Sat, 12 Dec 2009 05:56:14 -0800 (PST) Subject: How to implement Varient/Tagged Unions/Pattern Matching in Python? References: <358b227c-d836-4243-b79a-57258590a7a7@a10g2000pre.googlegroups.com> Message-ID: <0656bf3c-b30f-4eea-a734-f0856cb4cdcf@k17g2000yqh.googlegroups.com> > BTW, Please don't ask "Why do you want to do like this" No, I don't ask although it would be the interesting aspect for me ;) From johnroth1 at gmail.com Sat Dec 12 09:35:32 2009 From: johnroth1 at gmail.com (John Roth) Date: Sat, 12 Dec 2009 06:35:32 -0800 (PST) Subject: power of explicit self? References: <73d81fbc-95c5-4897-bca1-852471eb7938@q16g2000vbc.googlegroups.com> Message-ID: <0e1c9da1-a8e7-486e-aa28-341ef2c8d1bf@2g2000prl.googlegroups.com> On Dec 11, 9:04?pm, Fire Crow wrote: > I'm looking for an explanation of how explicit self is implimented and > what features are only possible because of, or are greatly improved, > because of it. I've always liked explicit self and am looking for the > computer science behind it, so that I can explain the benefits that I > see. > > I'm also interested in the files/lines of the python source that shows > how explicit self is implemented if anyone can point out where that > takes place. > > all help welcome It's not implemented in the compiler. There's a place in the runtime for invoking a method where the object is inserted at the beginning of the parameter list. IIRC, that's done by wrapping the function object. John Roth From carsten.haese at gmail.com Sat Dec 12 09:59:30 2009 From: carsten.haese at gmail.com (Carsten Haese) Date: Sat, 12 Dec 2009 09:59:30 -0500 Subject: MySQL set and enum, calling values In-Reply-To: <4dc0cfea0912120004v7dc565f0j7dda52c32000a93a@mail.gmail.com> References: <4dc0cfea0912111008x5fb47e8dv5a9091cbe67ec4c8@mail.gmail.com> <4dc0cfea0912111128w48b072bfsd7d8c29445c5f81d@mail.gmail.com> <4dc0cfea0912120004v7dc565f0j7dda52c32000a93a@mail.gmail.com> Message-ID: Victor Subervi wrote: > On Fri, Dec 11, 2009 at 8:13 PM, Gabriel Genellina > > wrote: > Are you sure the column is declared as SET and not, say, VARCHAR? > > > yes Indeed it is, and knowing that, I can actually decode your original post. I apologize that I didn't see the forest for all the trees you gave us. Your problem is that you are inspecting the metadata of a table to find out which possible values can be stored in a particular SET column of a particular table, and when you get the description of the table, you're getting a Python string object that describes the column, rather than a list (or set) of strings. The only solution is the one you already resigned to using, which is to dissect the string into its parts, as confirmed by this article: http://dev.mysql.com/tech-resources/articles/mysql-set-datatype.html . > Anyway, I don't think MySQLdb is able to handle the SET data type > correctly. > > > Oh, lovely! What do? MySQLdb does too handle the SET data type correctly, or at least as correctly as the underlying database itself will allow. It seems that SET-typed values can only be retrieved as strings or integers, and the latter only by "casting" the value to an integer by adding 0 to it. Oh, the humanity! The best advice I can give you is to rethink your data schema and avoid using the SET data type altogether. (Note that I'm only referring to the MySQL data type here. There's nothing wrong with Python's Set type.) The above-mentioned article has a section called "Why you shouldn't use SET." You should read it. HTH, -- Carsten Haese http://informixdb.sourceforge.net From gadfetrfqrq at gmail.com Sat Dec 12 10:06:50 2009 From: gadfetrfqrq at gmail.com (Franky Frank) Date: Sun, 13 Dec 2009 00:06:50 +0900 Subject: Python for simulating BRDF Message-ID: Dear python users, Greetings. I would like to write a simulation program using Python language for simulating bidirectional reflectance distribution function (BRDF) obtained from multi-angular remote sensing. I have a program written in C language. Can I convert it into Python language? In Python, being a higher level programming language, do we encounter more problems in debugging while developing such simulating program? Thank you very much for your kind help in the advance. Sincerely, Franky Frank -------------- next part -------------- An HTML attachment was scrubbed... URL: From victorsubervi at gmail.com Sat Dec 12 10:16:40 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Sat, 12 Dec 2009 10:16:40 -0500 Subject: Getting Default Values Out of MySQL Message-ID: <4dc0cfea0912120716n5322e3a1me14d1acc2e56817d@mail.gmail.com> Hi; I'm using MySQLdb. If I do a cursor.execute('describe myTable;') it gives me all sorts of data but not my default values. How do I retrieve them? TIA, Victor -------------- next part -------------- An HTML attachment was scrubbed... URL: From lie.1296 at gmail.com Sat Dec 12 10:35:56 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Sun, 13 Dec 2009 02:35:56 +1100 Subject: Problems with debugging Lists In-Reply-To: References: <200912120011.38311.sancar.saran@evodot.com> Message-ID: <4b23b85f$1@dnews.tpgi.com.au> On 12/12/2009 8:28 PM, Sancar Saran wrote: > repr works as you say and I had some complaints, it wont format the output. > Finding some string in 100 key dictionary in formatted in single line bit > problematic. Is it any way to format it ? As has been mentioned, use pprint.pformat() to get what pprint.pprint() would print as a str instead of being printed. > Also, very interesting things are happen. > > def debug(self): > > r = '
'
> 	r += repr(self.data)
> 	r += '
' > > return r > > following code works and does not work ever reload ? > > One time work another reload wont work. What I missing ? What do you mean by it doesn't work? Does it produce the wrong output? What's wrong with the output? Does it raises an error? Are you sure it isn't because self.data is empty? > And is possible to get this ? (I store the environ here) > > r += repr(self.data['environ']['mod_wsgi.listener_port']) > > or similar multi sub level elements ? python had no problem with that. From lie.1296 at gmail.com Sat Dec 12 10:40:38 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Sun, 13 Dec 2009 02:40:38 +1100 Subject: Spawning an interactive interpreter in a running python process? In-Reply-To: References: Message-ID: <4b23b97b@dnews.tpgi.com.au> On 12/12/2009 3:49 PM, Tim Chase wrote: >> I'm curious, in an academic sense, if it's possible to spawn the >> interactive interpreter (>>>) in a running python application. Ideally, I >> would like to be able to access the modules, functions and variables the >> application can. >> >> Is something like this possible? you can also use the -i switch to start the interactive interpreter once the script reaches execution: $ python -i myprogram.py program output >>> # names that are not been deleted at the end of program execution >>> # can be accessed here >>> From lie.1296 at gmail.com Sat Dec 12 10:52:30 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Sun, 13 Dec 2009 02:52:30 +1100 Subject: a list/re problem In-Reply-To: References: Message-ID: <4b23bc42$1@dnews.tpgi.com.au> import re r = re.compile('\*(.+)\*') def f(s): m = r.match(s) if m: return m.group(1) l = ['asc', '*nbh*', 'jlsdjfdk', 'ikjh', '*jkjsdfjasd*', 'rewr'] n = [y for y in (f(x) for x in l) if y] From carsten.haese at gmail.com Sat Dec 12 10:54:29 2009 From: carsten.haese at gmail.com (Carsten Haese) Date: Sat, 12 Dec 2009 10:54:29 -0500 Subject: Getting Default Values Out of MySQL In-Reply-To: <4dc0cfea0912120716n5322e3a1me14d1acc2e56817d@mail.gmail.com> References: <4dc0cfea0912120716n5322e3a1me14d1acc2e56817d@mail.gmail.com> Message-ID: Victor Subervi wrote: > Hi; > I'm using MySQLdb. If I do a > cursor.execute('describe myTable;') > it gives me all sorts of data but not my default values. That function call doesn't "give" any data at all, except for the rowcount (which would be the number of columns in the table). You must use some other command to retrieve the result set. What command are you using, and what are the results? > How do I > retrieve them? In my version of MySQL, he default value is in the fifth column of the result set. -- Carsten Haese http://informixdb.sourceforge.net From victorsubervi at gmail.com Sat Dec 12 11:18:35 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Sat, 12 Dec 2009 11:18:35 -0500 Subject: Getting Default Values Out of MySQL In-Reply-To: References: <4dc0cfea0912120716n5322e3a1me14d1acc2e56817d@mail.gmail.com> Message-ID: <4dc0cfea0912120818j3df20187h5701c17dc54bc7dd@mail.gmail.com> On Sat, Dec 12, 2009 at 10:54 AM, Carsten Haese wrote: > Victor Subervi wrote: > > Hi; > > I'm using MySQLdb. If I do a > > cursor.execute('describe myTable;') > > it gives me all sorts of data but not my default values. > > That function call doesn't "give" any data at all, except for the > rowcount (which would be the number of columns in the table). Really? cursor.execute('describe %s;' % store) storeDescription = cursor.fetchall() print storeDescription Prints out this: (('ID', 'tinyint(5) unsigned', 'NO', 'PRI', None, 'auto_increment'), ('SKU', 'varchar(40)', 'NO', 'UNI', None, ''), ('Category', 'varchar(40)', 'YES', '', None, ''), ('Name', 'varchar(50)', 'NO', '', None, ''), ('Title', 'varchar(100)', 'NO', '', None, ''), ('Description', 'mediumtext', 'NO', '', None, ''), ('Price', 'float(8,2)', 'YES', '', None, ''), ('SortFactor', 'int(4)', 'YES', '', '500', ''), ('Availability', 'tinyint(1)', 'NO', '', None, ''), ('ShipFlatFee', 'float(5,2)', 'NO', '', '10.00', ''), ('ShipPercentPrice', 'tinyint(2) unsigned', 'NO', '', '5', ''), ('ShipPercentWeight', 'tinyint(2) unsigned', 'NO', '', '2', ''), ('Associations', 'varchar(40)', 'NO', '', None, ''), ('TempPrice', 'float(7,2)', 'NO', '', None, ''), ('LastDatePrice', 'date', 'NO', '', None, ''), ('Weight', 'float(7,2)', 'NO', '', None, ''), ('Metal', "enum('14k gold','18k gold','white gold','silver','tungsten','titanium')", 'NO', '', None, ''), ('PercentMetal', 'tinyint(2) unsigned', 'NO', '', None, ''), ('pic1', 'blob', 'YES', '', None, ''), ('pic2', 'blob', 'YES', '', None, ''), ('sizes', "set('Extra-small','Small','Medium','Large','XLarge','XXLarge','XXXLarge')", 'YES', '', None, ''), ('colorsShadesNumbersShort', "set('blue:333399','gray:465945','purple:50404D','navy-blue:CC7722','fuchsia:FF77FF','aqua:7FFFD4','maroon:B03060','black:0000FF','yellow:9ACD32','teal:E2725B','olive:6B8E23','green:00A550','white:0F4D92','silver:708090','red:FE2712','lime:32CD32')", 'YES', '', None, '')) In my version of MySQL, he default value is in the fifth column of the > result set. > Nice. As you can see, I only get 4 columns by default. How do I get the fifth? TIA, V -------------- next part -------------- An HTML attachment was scrubbed... URL: From lie.1296 at gmail.com Sat Dec 12 11:22:19 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Sun, 13 Dec 2009 03:22:19 +1100 Subject: a list/re problem In-Reply-To: References: Message-ID: <4b23c33e$1@dnews.tpgi.com.au> On 12/12/2009 8:24 AM, Peter Otten wrote: >> >> But it is inefficient, because it is matching the regex twice for each >> item, and it is a bit ugly. >> >> I could use: >> >> >> n = [] >> for x in keys: >> m = r.match(x) >> if m: >> n.append(m.group(1)) >> >> >> It is more efficient, but much uglier. > > It's efficient and easy to understand; maybe you have to readjust your > taste. I agree, it's easy to understand, but it's also ugly because of the level of indentation (which is too deep for such a simple problem). >> Does anyone have a better solution? (sorry to ramble around) A few months ago, I suggested an improvement in the python-ideas list to add a post-filter to list-comprehension, somewhere in this line: a = [f(x) as F for x in l if c(F)] where the evaluation of f(x) will be the value of F so F can be used in the if-expression as a post-filter (complementing list-comps' pre-filter). Many doubted its usefulness since they say it's easy to wrap in another list-comp: a = [y for y in (f(x) for x in l) if c(y)] or with a map and filter a = filter(None, map(f, l)) Up till now, I don't really like the alternatives. From python at mrabarnett.plus.com Sat Dec 12 11:38:41 2009 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 12 Dec 2009 16:38:41 +0000 Subject: Getting Default Values Out of MySQL In-Reply-To: <4dc0cfea0912120818j3df20187h5701c17dc54bc7dd@mail.gmail.com> References: <4dc0cfea0912120716n5322e3a1me14d1acc2e56817d@mail.gmail.com> <4dc0cfea0912120818j3df20187h5701c17dc54bc7dd@mail.gmail.com> Message-ID: <4B23C711.5080607@mrabarnett.plus.com> Victor Subervi wrote: > > > On Sat, Dec 12, 2009 at 10:54 AM, Carsten Haese > wrote: > > Victor Subervi wrote: > > Hi; > > I'm using MySQLdb. If I do a > > cursor.execute('describe myTable;') > > it gives me all sorts of data but not my default values. > > That function call doesn't "give" any data at all, except for the > rowcount (which would be the number of columns in the table). > > > Really? > > cursor.execute('describe %s;' % store) > storeDescription = cursor.fetchall() > print storeDescription > > Prints out this: > > (('ID', 'tinyint(5) unsigned', 'NO', 'PRI', None, 'auto_increment'), > ('SKU', 'varchar(40)', 'NO', 'UNI', None, ''), ('Category', > 'varchar(40)', 'YES', '', None, ''), ('Name', 'varchar(50)', 'NO', '', > None, ''), ('Title', 'varchar(100)', 'NO', '', None, ''), > ('Description', 'mediumtext', 'NO', '', None, ''), ('Price', > 'float(8,2)', 'YES', '', None, ''), ('SortFactor', 'int(4)', 'YES', '', > '500', ''), ('Availability', 'tinyint(1)', 'NO', '', None, ''), > ('ShipFlatFee', 'float(5,2)', 'NO', '', '10.00', ''), > ('ShipPercentPrice', 'tinyint(2) unsigned', 'NO', '', '5', ''), > ('ShipPercentWeight', 'tinyint(2) unsigned', 'NO', '', '2', ''), > ('Associations', 'varchar(40)', 'NO', '', None, ''), ('TempPrice', > 'float(7,2)', 'NO', '', None, ''), ('LastDatePrice', 'date', 'NO', '', > None, ''), ('Weight', 'float(7,2)', 'NO', '', None, ''), ('Metal', > "enum('14k gold','18k gold','white > gold','silver','tungsten','titanium')", 'NO', '', None, ''), > ('PercentMetal', 'tinyint(2) unsigned', 'NO', '', None, ''), ('pic1', > 'blob', 'YES', '', None, ''), ('pic2', 'blob', 'YES', '', None, ''), > ('sizes', > "set('Extra-small','Small','Medium','Large','XLarge','XXLarge','XXXLarge')", > 'YES', '', None, ''), ('colorsShadesNumbersShort', > "set('blue:333399','gray:465945','purple:50404D','navy-blue:CC7722','fuchsia:FF77FF','aqua:7FFFD4','maroon:B03060','black:0000FF','yellow:9ACD32','teal:E2725B','olive:6B8E23','green:00A550','white:0F4D92','silver:708090','red:FE2712','lime:32CD32')", > 'YES', '', None, '')) > > In my version of MySQL, he default value is in the fifth column of the > result set. > > > Nice. As you can see, I only get 4 columns by default. How do I get the > fifth? > That's strange, I count 6! For example, the first field has the following columns: 1. 'ID' 2. 'tinyint(5) unsigned' 3. 'NO' 4. 'PRI' 5. None 6. 'auto_increment' From victorsubervi at gmail.com Sat Dec 12 12:04:42 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Sat, 12 Dec 2009 12:04:42 -0500 Subject: Getting Default Values Out of MySQL In-Reply-To: <4B23C711.5080607@mrabarnett.plus.com> References: <4dc0cfea0912120716n5322e3a1me14d1acc2e56817d@mail.gmail.com> <4dc0cfea0912120818j3df20187h5701c17dc54bc7dd@mail.gmail.com> <4B23C711.5080607@mrabarnett.plus.com> Message-ID: <4dc0cfea0912120904k582738e7i389ca75272539183@mail.gmail.com> On Sat, Dec 12, 2009 at 11:38 AM, MRAB wrote: > That's strange, I count 6! > > For example, the first field has the following columns: > > 1. 'ID' > > 2. 'tinyint(5) unsigned' > > 3. 'NO' > > 4. 'PRI' > > 5. None > > 6. 'auto_increment' Dunno why I counted 4 last time. Maybe changed something. Thanks, V -------------- next part -------------- An HTML attachment was scrubbed... URL: From cjwilliams43 at gmail.com Sat Dec 12 12:22:34 2009 From: cjwilliams43 at gmail.com (Colin W.) Date: Sat, 12 Dec 2009 12:22:34 -0500 Subject: Perl to Python conversion In-Reply-To: <87zl5rnayz.fsf@crunchbang.Belkin> References: <87zl5rnayz.fsf@crunchbang.Belkin> Message-ID: On 09-Dec-09 15:33 PM, Martin Sch??n wrote: > First off: I am new here and this is my first post after > lurking for quite some time. > > Second off: I don't know much Python---yet. > > Problem: I have come across a small open source application > that I find quite useful. It does have one major flaw though. > Its output is in imperial units. Converting isn't a big deal > for occasional use but if I start to use this stuff on a > regular basis... > > So I down-loaded the source code and found this thing is written > in Perl. > > Should I learn enough Perl to add the conversion? Probably > but this may be a nice excuse to get my Python education > going and if I do I might as well re-do the user interface. > > If I do re-write this thing in Python I might need to learn both > Perl and Python... > > Hence, are there any Perl to Python converters? So far I > have only found bridgekeeper which really is (was?) consultancy. > Apart from that I only find people recommending a manual re-write. > > Any thoughts/recommendations? > > TIA, > > /Martin Martin, If you convert the Perl, you continue the other fellow's errors. If you do it yourself, you'll be able to make your own - there should be fewer of them. Google: unit conversion python you'll have lots of offers. Colin W. From carsten.haese at gmail.com Sat Dec 12 13:31:39 2009 From: carsten.haese at gmail.com (Carsten Haese) Date: Sat, 12 Dec 2009 13:31:39 -0500 Subject: Getting Default Values Out of MySQL In-Reply-To: <4dc0cfea0912120818j3df20187h5701c17dc54bc7dd@mail.gmail.com> References: <4dc0cfea0912120716n5322e3a1me14d1acc2e56817d@mail.gmail.com> <4dc0cfea0912120818j3df20187h5701c17dc54bc7dd@mail.gmail.com> Message-ID: Victor Subervi wrote: > > > On Sat, Dec 12, 2009 at 10:54 AM, Carsten Haese > wrote: > > Victor Subervi wrote: > > Hi; > > I'm using MySQLdb. If I do a > > cursor.execute('describe myTable;') > > it gives me all sorts of data but not my default values. > > That function call doesn't "give" any data at all, except for the > rowcount (which would be the number of columns in the table). > > > Really? Yes, really. > cursor.execute('describe %s;' % store) > storeDescription = cursor.fetchall() > print storeDescription > > Prints out this: > [snip...] So it does. And if you look really, really carefully, maybe you'll be able to tell the difference between this, your original code snippet: cursor.execute('describe %s;' % store) And this, which is what *actually* produces your output: cursor.execute('describe %s;' % store) storeDescription = cursor.fetchall() print storeDescription The "all sorts of data" you referred to in your original post is obtained in the fetchall() call and then printed in the print statement. As I said, your output did not come from the execute() call. As usual, in your original post you didn't include the code that produces the output that's causing you grief, and you didn't include the output, either. This information is essential for helping you, and you have been asked many times before to provide this information. Persistently asking for help and not providing enough information is, as has been noted before, a form of rudeness. -- Carsten Haese http://informixdb.sourceforge.net From tjreedy at udel.edu Sat Dec 12 14:41:28 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 12 Dec 2009 14:41:28 -0500 Subject: Best way to conduct a google search In-Reply-To: <20091211124139.GA28813@debian-hp.lan> References: <20091211124139.GA28813@debian-hp.lan> Message-ID: Daniel Dalton wrote: > Hi, > > I need to do the following in my program: > 1. Conduct a google search, supplying the variable "text" to the > search. Is there a google api or something similar I should use? > 2. I then need to be able to get the url, of the page, or the html > content, so I can dump it to text. google 'python google api' From tjreedy at udel.edu Sat Dec 12 14:49:15 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 12 Dec 2009 14:49:15 -0500 Subject: Python for simulating BRDF In-Reply-To: References: Message-ID: Franky Frank wrote: > I would like to write a simulation program using Python language for > simulating bidirectional reflectance distribution function (BRDF) obtained > from multi-angular remote sensing. I have a program written in C language. > Can I convert it into Python language? Yes, but it would be slower unless you use numpy to the heavy calculation. Or you can wrap your current C program or routines within it so that they can be called from Python. If you compile to a .dll or .so, you can access function with the ctypes module. Google gives 20K hits with 'python brdf' >In Python, being a higher level > programming language, do we encounter more problems in debugging while > developing such simulating program? If you know Python well, you should have fewer problems. That is why people sometimes develop prototypes in Python and then translate to C if they need more speed. Terry Jan Reedy From martin at v.loewis.de Sat Dec 12 14:53:20 2009 From: martin at v.loewis.de (Martin v. Loewis) Date: Sat, 12 Dec 2009 20:53:20 +0100 Subject: When will Python 3 be fully deployed In-Reply-To: References: <4b20ac0a$0$1596$742ec2ed@news.sonic.net> Message-ID: <4B23F4B0.4070701@v.loewis.de> > In addition to Ned Deily's previous comments, I'd like to note that 2to3 > assumes the source is valid 2.6 code - you have to ensure the code runs > fine with Python 2.6 before using 2to3 to convert to 3.x That's wrong - 2to3 works just fine on, say, 2.3 code that has never been run on 2.6. Regards, Martin From me at firecrow.com Sat Dec 12 15:20:06 2009 From: me at firecrow.com (Fire Crow) Date: Sat, 12 Dec 2009 12:20:06 -0800 (PST) Subject: power of explicit self? References: <73d81fbc-95c5-4897-bca1-852471eb7938@q16g2000vbc.googlegroups.com> <0e1c9da1-a8e7-486e-aa28-341ef2c8d1bf@2g2000prl.googlegroups.com> Message-ID: > It's not implemented in the compiler. There's a place in the runtime > for invoking a method where the object is inserted at the beginning > of the parameter list. IIRC, that's done by wrapping the function > object. This is the source of Objects/methodobject.c it look like this is where self is added to the argument list, but I'll have to do some more digging. thanks for the tip. 50 PyObject * 51 PyCFunction_GetSelf(PyObject *op) 52 { 53 if (!PyCFunction_Check(op)) { 54 PyErr_BadInternalCall(); 55 return NULL; 56 } 57 return ((PyCFunctionObject *)op) -> m_self; 58 } .... 69 70 PyObject * 71 PyCFunction_Call(PyObject *func, PyObject *arg, PyObject *kw) 72 { ... 75 PyObject *self = PyCFunction_GET_SELF(func); ... 78 switch (PyCFunction_GET_FLAGS(func) & ~(METH_CLASS | METH_STATIC | METH_COEXIST)) { 79 case METH_VARARGS: 80 if (kw == NULL || PyDict_Size(kw) == 0) 81 return (*meth)(self, arg); 82 break; 83 case METH_VARARGS | METH_KEYWORDS: ... 126 } From nobody at nowhere.com Sat Dec 12 15:41:46 2009 From: nobody at nowhere.com (Nobody) Date: Sat, 12 Dec 2009 20:41:46 +0000 Subject: a list/re problem References: Message-ID: On Fri, 11 Dec 2009 12:49:42 -0800, Ed Keith wrote: > the following works: > > r = re.compile('\*(.+)\*') > > def f(s): > m = r.match(s) > if m: > return m.group(1) > else: > return '' > > n = [f(x) for x in l if r.match(x)] > > > > But it is inefficient, because it is matching the regex twice for each > item, and it is a bit ugly. > Does anyone have a better solution? Use a language with *real* list comprehensions? Flamebait aside, you can use another level of comprehension, i.e.: n = [m.group(1) for m in (r.match(x) for x in l) if m] From tino at wildenhain.de Sat Dec 12 15:59:28 2009 From: tino at wildenhain.de (Tino Wildenhain) Date: Sat, 12 Dec 2009 21:59:28 +0100 Subject: Moving from PHP to Python. Is it Possible In-Reply-To: <4B227A32.9060300@mrabarnett.plus.com> References: <3c4778e3-e31a-4484-ae9a-f6d5b737fa68@x25g2000prf.googlegroups.com> <4B227A32.9060300@mrabarnett.plus.com> Message-ID: <4B240430.8060505@wildenhain.de> MRAB schrieb: > zeph wrote: > [snip] >> 4) It's better to collect all your eventual output into a string that >> you print - there are examples at [3]. You can import from other >> modules as needed (even conditionally), grow your string for output, >> then finally print it like (this example was adapted from one found on >> [3]): >> >> output = '' >> output += 'My Page' >> output += '' >> output += '

Powers of two

\n
    ' >> for n in range(1,11): >> output += '
  1. '+str(2**n)+'
  2. ' >> >> output += '
' >> print output >> >> >> You can copy-paste this right into your Python interactive shell to >> see the output. Note: += is inline string concatenation. >> > It's better to put the strings into a list and then concatenate them in > one go: > > output = [''] > output.append('My Page') > output.append('') > output.append('

Powers of two

\n
    ') > for n in range(1, 11): > output.append('
  1. %s
  2. ' % (2 ** n)) > > output.append('
') > print ''.join(output) Actually I'd use a proper template engine in any case. The above construction of mixing code and representation (or rather code with code and data for another interpreter - the users browser) is not only unlucky, it is almost everytime very dangerous. Keep in mind if you are using a user supplied string, like coming from a form entry and just include it as above literally into your HTML, you have created a way of cross site scripting, a very common attack. To prevent that, you should always propery quote strings for the context where they are used. Template engines such as Zope Page Templates (also usable stand allone) are doing this for you. Regards Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3254 bytes Desc: S/MIME Cryptographic Signature URL: From victorsubervi at gmail.com Sat Dec 12 16:34:52 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Sat, 12 Dec 2009 16:34:52 -0500 Subject: Manipulating MySQL Sets Message-ID: <4dc0cfea0912121334gcf5af27l71a173c6a71f59d2@mail.gmail.com> Hi; What type does python consider a MySQL Set?? if isinstance(colValue[0], (str, int, long, float, long, complex, unicode, list, buffer, xrange, tuple)): pass else: print 'XXX' And the following fields pass through this net: Set and datetime. What type is a datetime? How do I parse a Set? Can't slice it. What do I do with the &*$( thing? Victor -------------- next part -------------- An HTML attachment was scrubbed... URL: From carsten.haese at gmail.com Sat Dec 12 17:11:17 2009 From: carsten.haese at gmail.com (Carsten Haese) Date: Sat, 12 Dec 2009 17:11:17 -0500 Subject: Manipulating MySQL Sets In-Reply-To: <4dc0cfea0912121334gcf5af27l71a173c6a71f59d2@mail.gmail.com> References: <4dc0cfea0912121334gcf5af27l71a173c6a71f59d2@mail.gmail.com> Message-ID: Victor Subervi wrote: > Hi; > What type does python consider a MySQL Set?? Let's take a look: >>> import MySQLdb >>> conn = MySQLdb.connect(db="carsten", user="blah", passwd="blah") >>> cur = conn.cursor() >>> cur.execute(""" ... create table pizza ( ... id integer, ... toppings set('cheese','sauce','peperoni','mushrooms') ... ) ... """) 0L >>> cur.execute(""" ... insert into pizza values(1, 'cheese,sauce,peperoni') ... """) 1L >>> cur.execute("select * from pizza") 1L >>> rows = cur.fetchall() >>> toppings = rows[0][1] >>> print toppings cheese,sauce,peperoni >>> print type(toppings) Looks like a string to me. -- Carsten Haese http://informixdb.sourceforge.net From debatem1 at gmail.com Sat Dec 12 17:32:18 2009 From: debatem1 at gmail.com (geremy condra) Date: Sat, 12 Dec 2009 17:32:18 -0500 Subject: Graph library for Python In-Reply-To: References: <4B1D5CB3.8030805@egenix.com> <00a70ac5$0$15659$c3e8da3@news.astraweb.com> <4B1E464B.6090408@chamonix.reportlab.co.uk> Message-ID: On Thu, Dec 10, 2009 at 10:57 AM, Bearophile wrote: > Geremy Condra: > >> is there a particular way you want your attribution line to read? > > You can just use my nickname (in all lowercase), with the list of > parts you have used. Don't worry. > > >> Well, we all seem to have reinvented the wheel differently ;) > > Maybe also because they are designed for different purposes. > > >> Bearophile, Tiago- any interest in trying to combine the >> best parts of our libraries, with an eye towards eventual >> integration into the standard library? > > The first thing to do is to ask Guido and Hettinger if they are > willing to put a "good" graph module into the std lib. If their answer > is positive for some definition of "good", then we can think about > doing something. > > Several years ago I have suggested to put a graph module in the std > lib, and the answer was something like: "Put the lib online, and if > people use it a lot, we'll see to put it into the std lib." In the > meantime my lib was used by no one and ten other graph libs are used > (networkx seems among the most used), but I think no one of them has > shown a strong usage. (In the meantime Hettinger has written and added > two or three or four GOOD data structures to the std lib using a "fast > lane", avoiding the step of popular usage test). Well, I've just concluded a short conversation with Raymond Hettinger, and I think its fair to characterize him as being opposed to the idea at present. In addition to the popularity test, he's also noted that ideally a core CPython dev should be involved in the project. Putting the two together is, AFAICS, a death knell for any extant graph lib. Having said that, I'd still like to see how much common ground we could find among the existing libraries. IMHO, there's a lot more in common than there is different. Geremy Condra From rhodri at wildebst.demon.co.uk Sat Dec 12 17:40:36 2009 From: rhodri at wildebst.demon.co.uk (Rhodri James) Date: Sat, 12 Dec 2009 22:40:36 -0000 Subject: read text file byte by byte In-Reply-To: References: <00acf5b1$0$15654$c3e8da3@news.astraweb.com> Message-ID: On Sat, 12 Dec 2009 11:14:13 -0000, census wrote: > Steven D'Aprano wrote: > >> On Sat, 12 Dec 2009 10:35:55 +0100, census wrote: >> >>>> I've got some questions - >>>> 1) How do I read the file byte by byte 2) Should I use streams? If so >>>> and I get my entire scrambled text in stream can I just write it to >>>> the >>>> binary file? >>>> >>>> Thanks >>>> Dave >>> >>> f = open ("binaryfile", "r") >>> bytearray = map (ord, f.read () ) >>> >>> Stores the content of binaryfile in the list bytearray. >> >> If it's a binary file, you should open it in binary mode: >> >> f = open ("binaryfile", "rb") >> >> >> > > Add the "b" flag to both in and out file if you prefer it: It's not a matter of preferring. Depending on your operating system and/or version of Python, reading a binary file without the "b" flag will give you wrong answers. -- Rhodri James *-* Wildebeest Herder to the Masses From fonnesbeck at gmail.com Sat Dec 12 17:58:40 2009 From: fonnesbeck at gmail.com (hardcoreUFO) Date: Sat, 12 Dec 2009 14:58:40 -0800 (PST) Subject: umath import error for Numpy builds on OSX 10.6 References: <6b6c00c1-edb8-4469-ab3c-af886aee841f@v15g2000prn.googlegroups.com> <762e37ef-b06a-400c-a61a-125775cb3940@k13g2000prh.googlegroups.com> Message-ID: <1d627655-c90a-44aa-b45a-33bfdce5a17f@u25g2000prh.googlegroups.com> On Dec 12, 5:44?pm, Robert Kern wrote: > On 2009-12-11 20:55 PM, hardcoreUFO wrote: > > > > > > > On Dec 11, 5:47 pm, Robert Kern ?wrote: > > >> Right, when the -lnpymath stuff got checked in. Looking at the build log you > >> posted to numpy-discusson, it does appear that the $LDFLAGS is obliterating the > >> intended flags. Please post a build log without setting those flags to > >> numpy-discussion. A correct link line should look something like this: > > >> gcc -arch i386 -arch ppc -isysroot /Developer/SDKs/MacOSX10.4u.sdk -g -bundle > >> -undefined dynamic_lookup > >> build/temp.macosx-10.3-i386-2.5/numpy/core/src/umath/umathmodule_onefile.o > >> -Lbuild/temp.macosx-10.3-i386-2.5 -lnpymath -o > >> build/lib.macosx-10.3-i386-2.5/numpy/core/umath.so > > > Thanks Robert, > > > Here is the log from a build without the LDFLAGS set. ?Having a quick > > look, all I can see are a few warnings and a CAPI version mismatch > > message. Any insight most appreciated. The build still gives the same > > umath error. > > On numpy-discussion, please. But first, start with a clean checkout. I think you > have stale files. Log from build with clean checkout posted to the numpy list. Thanks, cf From victorsubervi at gmail.com Sat Dec 12 18:07:12 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Sat, 12 Dec 2009 18:07:12 -0500 Subject: Manipulating MySQL Sets In-Reply-To: References: <4dc0cfea0912121334gcf5af27l71a173c6a71f59d2@mail.gmail.com> Message-ID: <4dc0cfea0912121507u499aa5e3j3316f8bef425fef1@mail.gmail.com> On Sat, Dec 12, 2009 at 5:11 PM, Carsten Haese wrote: > Victor Subervi wrote: > > Hi; > > What type does python consider a MySQL Set?? > > Let's take a look: > > >>> import MySQLdb > >>> conn = MySQLdb.connect(db="carsten", user="blah", passwd="blah") > >>> cur = conn.cursor() > >>> cur.execute(""" > ... create table pizza ( > ... id integer, > ... toppings set('cheese','sauce','peperoni','mushrooms') > ... ) > ... """) > 0L > >>> cur.execute(""" > ... insert into pizza values(1, 'cheese,sauce,peperoni') > ... """) > 1L > >>> cur.execute("select * from pizza") > 1L > >>> rows = cur.fetchall() > >>> toppings = rows[0][1] > >>> print toppings > cheese,sauce,peperoni > >>> print type(toppings) > > > > Looks like a string to me. > Yep, sure does, but it isn't. Again: if isinstance(colValue[0], (str, int, long, float, long, complex, unicode, list, buffer, xrange, tuple)): pass else: print 'XXX' and those "strings" printed triple-X. It ain't no string. Besides, if it were a string, I'd be able to slice it, wouldn't I? Can't slice it either. V -------------- next part -------------- An HTML attachment was scrubbed... URL: From victorsubervi at gmail.com Sat Dec 12 18:13:18 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Sat, 12 Dec 2009 18:13:18 -0500 Subject: Manipulating MySQL Sets In-Reply-To: <4dc0cfea0912121507u499aa5e3j3316f8bef425fef1@mail.gmail.com> References: <4dc0cfea0912121334gcf5af27l71a173c6a71f59d2@mail.gmail.com> <4dc0cfea0912121507u499aa5e3j3316f8bef425fef1@mail.gmail.com> Message-ID: <4dc0cfea0912121513y82451b9lbc31c6f54394a89f@mail.gmail.com> On Sat, Dec 12, 2009 at 6:07 PM, Victor Subervi wrote: > On Sat, Dec 12, 2009 at 5:11 PM, Carsten Haese wrote: > >> Victor Subervi wrote: >> > Hi; >> > What type does python consider a MySQL Set?? >> >> Let's take a look: >> >> >>> import MySQLdb >> >>> conn = MySQLdb.connect(db="carsten", user="blah", passwd="blah") >> >>> cur = conn.cursor() >> >>> cur.execute(""" >> ... create table pizza ( >> ... id integer, >> ... toppings set('cheese','sauce','peperoni','mushrooms') >> ... ) >> ... """) >> 0L >> >>> cur.execute(""" >> ... insert into pizza values(1, 'cheese,sauce,peperoni') >> ... """) >> 1L >> >>> cur.execute("select * from pizza") >> 1L >> >>> rows = cur.fetchall() >> >>> toppings = rows[0][1] >> >>> print toppings >> cheese,sauce,peperoni >> >>> print type(toppings) >> >> >> >> Looks like a string to me. >> > > Yep, sure does, but it isn't. Again: > > if isinstance(colValue[0], (str, int, long, float, long, > complex, unicode, list, buffer, xrange, tuple)): > pass > else: > print 'XXX' > > and those "strings" printed triple-X. It ain't no string. Besides, if it > were a string, I'd be able to slice it, wouldn't I? Can't slice it either. > V > PS: Changed the code to this: elif col[:3] != 'pic': if isinstance(colValue[0], (str, int, long, float, long, complex, unicode, list, buffer, xrange, tuple)): pass else: print 'XXX' if col == 'sizes': # One of those lovely sets print colValue[0][0] throws this lovely error: /var/www/html/angrynates.com/cart/display.py 96 raise 97 cursor.close() 98 bottom() 99 100 display() display = /var/www/html/angrynates.com/cart/display.py in display() 50 print 'XXX' 51 if col == 'sizes': 52 print colValue[0][0] 53 # ourValue = string.split(colValue[0][6:-3], "','") 54 # print ourValue colValue = (Set(['Small', 'Extra-small', 'Medium']),) TypeError: unindexable object args = ('unindexable object',) V -------------- next part -------------- An HTML attachment was scrubbed... URL: From carsten.haese at gmail.com Sat Dec 12 18:22:52 2009 From: carsten.haese at gmail.com (Carsten Haese) Date: Sat, 12 Dec 2009 18:22:52 -0500 Subject: Manipulating MySQL Sets In-Reply-To: <4dc0cfea0912121507u499aa5e3j3316f8bef425fef1@mail.gmail.com> References: <4dc0cfea0912121334gcf5af27l71a173c6a71f59d2@mail.gmail.com> <4dc0cfea0912121507u499aa5e3j3316f8bef425fef1@mail.gmail.com> Message-ID: Victor Subervi wrote: > Yep, sure does, but it isn't. Again: > > if isinstance(colValue[0], (str, int, long, float, long, > complex, unicode, list, buffer, xrange, tuple)): > pass > else: > print 'XXX' > > and those "strings" printed triple-X. It ain't no string. Besides, if it > were a string, I'd be able to slice it, wouldn't I? Can't slice it either. Well, then colValue[0] is not a string. This in turn probably means that colValue[0] does not represent the contents of a SET-type column. However, I can't tell you what it actually is, because you're once again not providing enough information. We'd need to see where colValue is coming from to find out what colValue[0] is. -- Carsten Haese http://informixdb.sourceforge.net From carsten.haese at gmail.com Sat Dec 12 18:35:55 2009 From: carsten.haese at gmail.com (Carsten Haese) Date: Sat, 12 Dec 2009 18:35:55 -0500 Subject: Manipulating MySQL Sets In-Reply-To: <4dc0cfea0912121513y82451b9lbc31c6f54394a89f@mail.gmail.com> References: <4dc0cfea0912121334gcf5af27l71a173c6a71f59d2@mail.gmail.com> <4dc0cfea0912121507u499aa5e3j3316f8bef425fef1@mail.gmail.com> <4dc0cfea0912121513y82451b9lbc31c6f54394a89f@mail.gmail.com> Message-ID: Victor Subervi wrote: > PS: > > Changed the code to this: > > elif col[:3] != 'pic': > if isinstance(colValue[0], (str, int, long, float, long, > complex, unicode, list, buffer, xrange, tuple)): > pass > else: > print 'XXX' > if col == 'sizes': # One of those lovely sets > print colValue[0][0] > > > throws this lovely error: > > /var/www/html/angrynates.com/cart/display.py > > 96 raise > 97 cursor.close() > 98 bottom() > 99 > 100 display() > display = > /var/www/html/angrynates.com/cart/display.py > in display() > 50 print 'XXX' > 51 if col == 'sizes': > 52 print colValue[0][0] > 53 # ourValue = string.split(colValue[0][6:-3], "','") > 54 # print ourValue > colValue = (Set(['Small', 'Extra-small', 'Medium']),) > > TypeError: unindexable object > args = ('unindexable object',) The traceback helpfully shows us that colValue is a 1-tuple whose zeroth entry, colValue[0], is an actual bona-fide Python Set object. Such objects aren't indexable, because sets are unordered. That still doesn't tell us where colValue is coming from, though, so why it is a Python Set object when you expected it to be a string remains an unsolved mystery. -- Carsten Haese http://informixdb.sourceforge.net From python at mrabarnett.plus.com Sat Dec 12 18:36:06 2009 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 12 Dec 2009 23:36:06 +0000 Subject: Manipulating MySQL Sets In-Reply-To: <4dc0cfea0912121507u499aa5e3j3316f8bef425fef1@mail.gmail.com> References: <4dc0cfea0912121334gcf5af27l71a173c6a71f59d2@mail.gmail.com> <4dc0cfea0912121507u499aa5e3j3316f8bef425fef1@mail.gmail.com> Message-ID: <4B2428E6.6070407@mrabarnett.plus.com> Victor Subervi wrote: > On Sat, Dec 12, 2009 at 5:11 PM, Carsten Haese > wrote: > > Victor Subervi wrote: > > Hi; > > What type does python consider a MySQL Set?? > > Let's take a look: > [snip] > > Looks like a string to me. > > > Yep, sure does, but it isn't. Again: > > if isinstance(colValue[0], (str, int, long, float, long, > complex, unicode, list, buffer, xrange, tuple)): > pass > else: > print 'XXX' > > and those "strings" printed triple-X. It ain't no string. Besides, if it > were a string, I'd be able to slice it, wouldn't I? Can't slice it either. > If you want to know what type colValue[0] is, print type(colValue[0]). From tom.machinski at gmail.com Sat Dec 12 19:15:23 2009 From: tom.machinski at gmail.com (Tom Machinski) Date: Sat, 12 Dec 2009 16:15:23 -0800 Subject: Dangerous behavior of list(generator) Message-ID: In most cases, `list(generator)` works as expected. Thus, `list()` is generally equivalent to `[]`. Here's a minimal case where this equivalence breaks, causing a serious and hard-to-detect bug in a program: >>> def sit(): raise StopIteration() ... >>> [f() for f in (lambda:1, sit, lambda:2)] Traceback (most recent call last): File "", line 1, in File "", line 1, in sit StopIteration >>> list(f() for f in (lambda:1, sit, lambda:2)) [1] I was bitten hard by this inconsistency when sit() was returning the idiom `(foo for foo in bar if foo.is_baz()).next()`. The nonexistence of a foo with is_baz() True in that query raises an exception as designed, which expresses itself when I use the list comprehension version of the code above; the generator version muffles the error and silently introduces a subtle, confusing bug: `lambda:2` is never reached, and a truncated list of 1 element (instead of 3) is "successfully" generated.. Just wondered what you guys think, -- Tom From bsneddon at yahoo.com Sat Dec 12 19:16:32 2009 From: bsneddon at yahoo.com (bsneddon) Date: Sat, 12 Dec 2009 16:16:32 -0800 (PST) Subject: parse a string of parameters and values Message-ID: <57a39e82-08e3-406a-9483-7fa28b180f82@w19g2000pre.googlegroups.com> I have a problem that I can come up with a brute force solution to solve but it occurred to me that there may be an "one-- and preferably only one --obvious way to do it". I am going to read a text file that is an export from a control system. It has lines with information like base=1 name="first one" color=blue I would like to put this info into a dictionary for processing. I have looked at optparse and getopt maybe they are the answer but there could be and very straight forward way to do this task. Thanks for your help From python.list at tim.thechases.com Sat Dec 12 19:41:58 2009 From: python.list at tim.thechases.com (Tim Chase) Date: Sat, 12 Dec 2009 18:41:58 -0600 Subject: read text file byte by byte In-Reply-To: <00acf601$0$15654$c3e8da3@news.astraweb.com> References: <00acf601$0$15654$c3e8da3@news.astraweb.com> Message-ID: <4B243856.3010506@tim.thechases.com> Steven D'Aprano wrote: >> 2) Should I use streams? > > What do you mean by "streams"? they're what come out of proton packs...just don't cross them. It would be bad. -tkc (I suspect the OP is a Java/C++ programmer where "streams" are somewhat akin to generators, but less powerful; so the answer is "you can if you want, but it may not get you what you think you want") From benjamin.kaplan at case.edu Sat Dec 12 19:53:57 2009 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Sat, 12 Dec 2009 19:53:57 -0500 Subject: Dangerous behavior of list(generator) In-Reply-To: References: Message-ID: On Sat, Dec 12, 2009 at 7:15 PM, Tom Machinski wrote: > In most cases, `list(generator)` works as expected. Thus, > `list()` is generally equivalent to `[ expression>]`. > Actually, it's list(generator) vs. a list comprehension. I agree that it can be confusing, but Python considers them to be two different constructs. >>> list(xrange(10)) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> [xrange(10)] [xrange(10)] > Here's a minimal case where this equivalence breaks, causing a serious > and hard-to-detect bug in a program: > > ?>>> def sit(): raise StopIteration() > ?... > ?>>> [f() for f in (lambda:1, sit, lambda:2)] > ?Traceback (most recent call last): > ? ?File "", line 1, in > ? ?File "", line 1, in sit > ?StopIteration > ?>>> list(f() for f in (lambda:1, sit, lambda:2)) > ?[1] > > I was bitten hard by this inconsistency when sit() was returning the > idiom `(foo for foo in bar if foo.is_baz()).next()`. The nonexistence > of a foo with is_baz() True in that query raises an exception as > designed, which expresses itself when I use the list comprehension > version of the code above; the generator version muffles the error and > silently introduces a subtle, confusing bug: `lambda:2` is never > reached, and a truncated list of 1 element (instead of 3) is > "successfully" generated.. > > Just wondered what you guys think, > > ?-- Tom > -- > http://mail.python.org/mailman/listinfo/python-list > From zephjc at gmail.com Sat Dec 12 20:13:21 2009 From: zephjc at gmail.com (zeph) Date: Sat, 12 Dec 2009 17:13:21 -0800 (PST) Subject: parallelpython 1.5.7 crash References: Message-ID: I looked in the browsable svn repo for parallel python at http://parallelpython.googlecode.com/svn/trunk/ 1) OverflowError: long int too large to convert to int This is a bug in their code (comments are mine) in pytransport.py: size_packed = self.r.read(struct.calcsize("!Q")) # reads in 8- character string msg_len = struct.unpack("!Q", size_packed)[0] # unpacks to a long value, e.g. "12345678" -> 3544952156018063160L msg = self.r.read(msg_len) # 3544952156018063160L is too long for file.read, which I presume must be able to cast as an int As an example: >>> sys.stdin.read(3544952156018063160L) Traceback (most recent call last): File "", line 1, in OverflowError: long int too large to convert to int 2) UnboundLocalError: local variable 'sresult' referenced before assignment This is another bug in their code. This is an error in pp.py (again, comments are mine, some code omitted for brevity): try: # ...snip... sresult = worker.t.receive() # sets sresult except: if self.__exiting: return else: # at this point, __run doesn't return, but sresult was not defined since the # execution was unwound because, presumable, the first fatal you got, the OverflowError sys.excepthook(*sys.exc_info()) # ...snip... job.finalize(sresult) # UnboundLocalError here from missing sresult You can submit these as a bug report to the author if you want - feel free to copy-paste or link to this post :-) - zeph From nad at acm.org Sat Dec 12 21:01:24 2009 From: nad at acm.org (Ned Deily) Date: Sat, 12 Dec 2009 18:01:24 -0800 Subject: Dangerous behavior of list(generator) References: Message-ID: In article , Benjamin Kaplan wrote: > On Sat, Dec 12, 2009 at 7:15 PM, Tom Machinski > wrote: > > In most cases, `list(generator)` works as expected. Thus, > > `list()` is generally equivalent to `[ > expression>]`. > Actually, it's list(generator) vs. a list comprehension. I agree that > it can be confusing, but Python considers them to be two different > constructs. > > >>> list(xrange(10)) > [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] > >>> [xrange(10)] > [xrange(10)] That's not a list comprehension, that's a list with one element. >>> [x for x in xrange(10)] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] Now *that's* a list comprehension. -- Ned Deily, nad at acm.org From benjamin.kaplan at case.edu Sat Dec 12 21:16:36 2009 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Sat, 12 Dec 2009 21:16:36 -0500 Subject: Dangerous behavior of list(generator) In-Reply-To: References: Message-ID: On Sat, Dec 12, 2009 at 9:01 PM, Ned Deily wrote: > In article > , > ?Benjamin Kaplan wrote: >> On Sat, Dec 12, 2009 at 7:15 PM, Tom Machinski >> wrote: >> > In most cases, `list(generator)` works as expected. Thus, >> > `list()` is generally equivalent to `[> > expression>]`. >> Actually, it's list(generator) vs. a list comprehension. I agree that >> it can be confusing, but Python considers them to be two different >> constructs. >> >> >>> list(xrange(10)) >> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >> >>> [xrange(10)] >> [xrange(10)] > > That's not a list comprehension, that's a list with one element. > >>>> [x for x in xrange(10)] > [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] > > Now *that's* a list comprehension. > I know. But the OP was wondering why list() was behaving differently than [] and I was pointing out that list comprehensions are considered their own syntax- the list comprehension [x for x in xrange(10)] is different than [(x for x in xrange(10)]. > -- > ?Ned Deily, > ?nad at acm.org > > -- > http://mail.python.org/mailman/listinfo/python-list > From nad at acm.org Sat Dec 12 21:43:20 2009 From: nad at acm.org (Ned Deily) Date: Sat, 12 Dec 2009 18:43:20 -0800 Subject: Dangerous behavior of list(generator) References: Message-ID: In article , Ned Deily wrote: > In article > , > Benjamin Kaplan wrote: > > On Sat, Dec 12, 2009 at 7:15 PM, Tom Machinski > > wrote: > > > In most cases, `list(generator)` works as expected. Thus, > > > `list()` is generally equivalent to `[ > > expression>]`. > > Actually, it's list(generator) vs. a list comprehension. I agree that > > it can be confusing, but Python considers them to be two different > > constructs. > > > > >>> list(xrange(10)) > > [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] > > >>> [xrange(10)] > > [xrange(10)] > > That's not a list comprehension, that's a list with one element. > > >>> [x for x in xrange(10)] > [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] > > Now *that's* a list comprehension. Which is not quite the point Benjamin was trying to make - sorry! Consulting the adjacent sections on "List displays" and "Generator expressions" in the Language Reference: http://docs.python.org/reference/expressions.html#list-displays for generator expressions "the parentheses can be omitted on calls with only one argument " but the expressions in a list_comprehension are not in a call context. So there is no ambiguity: [] requires parens around the generator expression and that list display produces a list with one element as Benjamin points out. -- Ned Deily, nad at acm.org From steve at REMOVE-THIS-cybersource.com.au Sat Dec 12 22:27:49 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 13 Dec 2009 03:27:49 GMT Subject: parse a string of parameters and values References: <57a39e82-08e3-406a-9483-7fa28b180f82@w19g2000pre.googlegroups.com> Message-ID: <00ade3d3$0$15654$c3e8da3@news.astraweb.com> On Sat, 12 Dec 2009 16:16:32 -0800, bsneddon wrote: > I have a problem that I can come up with a brute force solution to solve > but it occurred to me that there may be an > "one-- and preferably only one --obvious way to do it". I'm not sure that "brute force" is the right description here. Generally, "brute force" is used for situations where you check every single possible value rather than calculate the answer directly. One classical example is guessing the password that goes with an account. The brute force attack is to guess every imaginable password -- eventually you'll find the matching one. A non-brute force attack is to say "I know the password is a recent date", which reduces the space of possible passwords from many trillions to mere millions. So I'm not sure that brute force is an appropriate description for this problem. One way or another you have to read every line in the file. Whether you read them or you farm the job out to some pre-existing library function, they still have to be read. > I am going to read a text file that is an export from a control system. > It has lines with information like > > base=1 name="first one" color=blue > > I would like to put this info into a dictionary for processing. Have you looked at the ConfigParser module? Assuming that ConfigParser isn't suitable, you can do this if each key=value pair is on its own line: d = {} for line in open(filename, 'r'): if not line.strip(): # skip blank lines continue key, value = line.split('=', 1) d[key.strip()] = value.strip() If you have multiple keys per line, you need a more sophisticated way of splitting them. Something like this should work: d = {} for line in open(filename, 'r'): if not line.strip(): continue terms = line.split('=') keys = terms[0::2] # every second item starting from the first values = terms[1::2] # every second item starting from the second for key, value in zip(keys, values): d[key.strip()] = value.strip() -- Steven From sjmachin at lexicon.net Sun Dec 13 00:52:04 2009 From: sjmachin at lexicon.net (John Machin) Date: Sun, 13 Dec 2009 05:52:04 +0000 (UTC) Subject: parse a string of parameters and values References: <57a39e82-08e3-406a-9483-7fa28b180f82@w19g2000pre.googlegroups.com> <00ade3d3$0$15654$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano REMOVE-THIS-cybersource.com.au> writes: > > On Sat, 12 Dec 2009 16:16:32 -0800, bsneddon wrote: > > > > I am going to read a text file that is an export from a control system. > > It has lines with information like > > > > base=1 name="first one" color=blue > > > > I would like to put this info into a dictionary for processing. > > Have you looked at the ConfigParser module? > > Assuming that ConfigParser isn't suitable, you can do this if each > key=value pair is on its own line: > [snip] > If you have multiple keys per line, you need a more sophisticated way of > splitting them. Something like this should work: > > d = {} > for line in open(filename, 'r'): > if not line.strip(): > continue > terms = line.split('=') > keys = terms[0::2] # every second item starting from the first > values = terms[1::2] # every second item starting from the second > for key, value in zip(keys, values): > d[key.strip()] = value.strip() > There appears to be a problem with the above snippet, or you have a strange interpretation of "put this info into a dictionary": | >>> line = 'a=1 b=2 c=3 d=4' | >>> d = {} | >>> terms = line.split('=') | >>> print terms | ['a', '1 b', '2 c', '3 d', '4'] | >>> keys = terms[0::2] # every second item starting from the first | >>> values = terms[1::2] # every second item starting from the second | >>> for key, value in zip(keys, values): | ... d[key.strip()] = value.strip() | ... | >>> print d | {'a': '1 b', '2 c': '3 d'} | >>> Perhaps you meant terms = re.split(r'[= ]', line) which is an improvement, but this fails on cosmetic spaces e.g. a = 1 b = 2 ... Try terms = filter(None, re.split(r'[= ]', line)) Now we get to the really hard part: handling the name="first one" in the OP's example. The splitting approach has run out of steam. The OP will need to divulge what is the protocol for escaping the " character if it is present in the input. If nobody knows of a packaged solution to his particular scheme, then he'll need to use something like pyparsing. From daved170 at gmail.com Sun Dec 13 01:15:50 2009 From: daved170 at gmail.com (daved170) Date: Sat, 12 Dec 2009 22:15:50 -0800 (PST) Subject: read text file byte by byte References: Message-ID: <4519638f-c62b-46f6-ba1e-619035d48036@j14g2000yqm.googlegroups.com> On Dec 13, 2:34?am, Dennis Lee Bieber wrote: > On Sat, 12 Dec 2009 10:46:01 +0100, census > declaimed the following in gmane.comp.python.general: > > > > > def scramble (a): return (a + 13) % 256 > > ? ? ? ? I'll see your modulo rot 13 and raise with a exclusive or... > > -=-=-=-=- > > import sys > > def scramble(block, key="don't look"): > ? ? copies = int(len(block) / len(key)) + 1 > ? ? keystring = key * copies > ? ? return "".join([ chr( ord(block[i]) > ? ? ? ? ? ? ? ? ? ? ? ? ? ^ ord(keystring[i])) > ? ? ? ? ? ? ? ? ? ? ?for i in range(len(block))]) > > def process(fin, fout, key=None): > ? ? din = open(fin, "rb") > ? ? dout = open(fout, "wb") > ? ? while True: > ? ? ? ? block = din.read(1024) > ? ? ? ? if not block: break > ? ? ? ? if key is None: > ? ? ? ? ? ? block = scramble(block) > ? ? ? ? else: > ? ? ? ? ? ? block = scramble(block, key) > ? ? ? ? dout.write(block) > ? ? dout.close() > ? ? din.close() > > if __name__ == "__main__": > ? ? fin = sys.argv[1] > ? ? fout = sys.argv[2] > ? ? if len(sys.argv) > 3: > ? ? ? ? key = sys.argv[3] > ? ? else: > ? ? ? ? key = None > ? ? process(fin, fout, key) > -- > ? ? ? ? Wulfraed ? ? ? ? Dennis Lee Bieber ? ? ? ? ? ? ? KD6MOG > ? ? ? ? wlfr... at ix.netcom.com ? ? ?HTTP://wlfraed.home.netcom.com/ Thank you all. Dennis I really liked you solution for the issue but I have two question about it: 1) My origin file is Text file and not binary 2) I need to read each time 1 byte. I didn't see that on your example code. Thanks again All of you Dave From technologiclee at gmail.com Sun Dec 13 01:34:59 2009 From: technologiclee at gmail.com (technologiclee) Date: Sat, 12 Dec 2009 22:34:59 -0800 (PST) Subject: Nanoengineer-1 Simulator Message-ID: <0fbf2e89-fe93-4110-944f-ad825a46e9c3@f16g2000yqm.googlegroups.com> This is from a thread started at the Open Manufacturing Group. It is about the Nanoengineer-1 molecular modeling program. It is released under GPL license. I would like to know if this project can be forked and continued - as development seems to have ceased, but it is still the best software of its kind that I can find. All the details are in the thread. http://groups.google.com/group/openmanufacturing/browse_thread/thread/aff728b7182ebd44 Specifically, I would like to ask this community about an error trying to use the simulator: This is the error from Netbeans when I try to run the simulator. Any suggestions? error trying to import dylib sim: : No module named sim [runSim.py:787] sim parameters used by NE1 read from: [/home/lee/nesuite1.1.12./cad/plugins/NanoDynamics-1/sim-params.txt] bug in simulator-calling code: : SimRunner instance has no attribute 'system_parameters_file' [runSim.py:372] [runSim.py:970] [runSim.py:1089] exception opening trace file '/home/lee/Nanorex/Untitled.2009-12-13-00-18-10-trace.txt': : [Errno 2] No such file or directory: '/home/lee/Nanorex/Untitled.2009-12-13-00-18-10-trace.txt' [runSim.py:1936] From steve at REMOVE-THIS-cybersource.com.au Sun Dec 13 01:44:54 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 13 Dec 2009 06:44:54 GMT Subject: read text file byte by byte References: <4519638f-c62b-46f6-ba1e-619035d48036@j14g2000yqm.googlegroups.com> Message-ID: <00ae1204$0$15654$c3e8da3@news.astraweb.com> On Sat, 12 Dec 2009 22:15:50 -0800, daved170 wrote: > Thank you all. > Dennis I really liked you solution for the issue but I have two question > about it: > 1) My origin file is Text file and not binary That's a statement, not a question. > 2) I need to read each time 1 byte. f = open(filename, 'r') # open in text mode f.read(1) # read one byte -- Steven From steve at REMOVE-THIS-cybersource.com.au Sun Dec 13 01:45:45 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 13 Dec 2009 06:45:45 GMT Subject: parse a string of parameters and values References: <57a39e82-08e3-406a-9483-7fa28b180f82@w19g2000pre.googlegroups.com> <00ade3d3$0$15654$c3e8da3@news.astraweb.com> Message-ID: <00ae1237$0$15654$c3e8da3@news.astraweb.com> On Sun, 13 Dec 2009 05:52:04 +0000, John Machin wrote: > Steven D'Aprano REMOVE-THIS-cybersource.com.au> writes: [snip] >> If you have multiple keys per line, you need a more sophisticated way >> of splitting them. Something like this should work: [...] > There appears to be a problem with the above snippet, or you have a > strange interpretation of "put this info into a dictionary": D'oh! In my defence, I said it "should" work, not that it did work! -- Steven From lie.1296 at gmail.com Sun Dec 13 02:25:55 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Sun, 13 Dec 2009 18:25:55 +1100 Subject: read text file byte by byte In-Reply-To: <4519638f-c62b-46f6-ba1e-619035d48036@j14g2000yqm.googlegroups.com> References: <4519638f-c62b-46f6-ba1e-619035d48036@j14g2000yqm.googlegroups.com> Message-ID: <4b24970a$1@dnews.tpgi.com.au> On 12/13/2009 5:15 PM, daved170 wrote: > Thank you all. > Dennis I really liked you solution for the issue but I have two > question about it: > 1) My origin file is Text file and not binary > 2) I need to read each time 1 byte. I didn't see that on your example > code. That's where you're confusing things. The counting unit in text is characters, not bytes. Text is binary as well, it's just binary encoded in specific way (like ASCII or UTF-8), and computers decoded that binary stream into characters. What you actually need? Reading the text character-per-character OR treating an encoded text as binary and reading it byte-per-byte. Rather, why don't you explain the problem you're trying to solve so we can see which you actually need. From davea at ieee.org Sun Dec 13 02:32:46 2009 From: davea at ieee.org (Dave Angel) Date: Sun, 13 Dec 2009 02:32:46 -0500 Subject: read text file byte by byte In-Reply-To: <4519638f-c62b-46f6-ba1e-619035d48036@j14g2000yqm.googlegroups.com> References: <4519638f-c62b-46f6-ba1e-619035d48036@j14g2000yqm.googlegroups.com> Message-ID: <4B24989E.5050204@ieee.org> daved170 wrote: > On Dec 13, 2:34 am, Dennis Lee Bieber wrote: > >> On Sat, 12 Dec 2009 10:46:01 +0100, census >> declaimed the following in gmane.comp.python.general: >> >> >> >> >>> def scramble (a): return (a + 13) % 256 >>> >> I'll see your modulo rot 13 and raise with a exclusive or... >> >> -=-=-=- >> >> import sys >> >> def scramble(block, key=on't look"): >> copies =nt(len(block) / len(key)) + 1 >> keystring =ey * copies >> return "".join([ chr( ord(block[i]) >> ^ ord(keystring[i])) >> for i in range(len(block))]) >> >> def process(fin, fout, key=ne): >> din =pen(fin, "rb") >> dout =pen(fout, "wb") >> while True: >> block =in.read(1024) >> if not block: break >> if key is None: >> block =cramble(block) >> else: >> block =cramble(block, key) >> dout.write(block) >> dout.close() >> din.close() >> >> if __name__ ="__main__": >> fin =ys.argv[1] >> fout =ys.argv[2] >> if len(sys.argv) > 3: >> key =ys.argv[3] >> else: >> key =one >> process(fin, fout, key) >> -- >> Wulfraed Dennis Lee Bieber KD6MOG >> wlfr... at ix.netcom.com HTTP://wlfraed.home.netcom.com/ >> > > > Thank you all. > Dennis I really liked you solution for the issue but I have two > question about it: > 1) My origin file is Text file and not binary > 2) I need to read each time 1 byte. I didn't see that on your example > code. > Thanks again All of you > Dave > > If you really need to see each byte of the file, you need to open it as binary. You can then decide that the bytes represent text, in some encoding. If you don't use the "b" flag, the library may change the newline characters out from under you. You have to decide if that matters. I may have missed it, but I don't think you ever explained why you insist on the data being read one byte at a time. Usually, it's more efficient to read it into a buffer, and process that one byte at a time. But in any case, you can supply your own count to read(). Instead of using 1024, use 1. DaveA From enleverLesX_XXmcX at XmclavXeauX.com.invalid Sun Dec 13 03:20:24 2009 From: enleverLesX_XXmcX at XmclavXeauX.com.invalid (Michel Claveau - MVP) Date: Sun, 13 Dec 2009 09:20:24 +0100 Subject: read text file byte by byte References: <00acf5b1$0$15654$c3e8da3@news.astraweb.com> Message-ID: <4b24a3c8$0$937$ba4acef3@news.orange.fr> Hi! > If it's a binary file... OK, but... what is a "binary" file? @+ -- Michel Claveau From clp2 at rebertia.com Sun Dec 13 03:35:16 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 13 Dec 2009 00:35:16 -0800 Subject: read text file byte by byte In-Reply-To: <4b24a3c8$0$937$ba4acef3@news.orange.fr> References: <00acf5b1$0$15654$c3e8da3@news.astraweb.com> <4b24a3c8$0$937$ba4acef3@news.orange.fr> Message-ID: <50697b2c0912130035sab323c5ja174d90602aefaf@mail.gmail.com> On Sun, Dec 13, 2009 at 12:20 AM, Michel Claveau - MVP wrote: > Hi! > >> If it's a binary file... > > OK, but... what is a "binary" file? http://en.wikipedia.org/wiki/Binary_file Cheers, Chris -- http://blog.rebertia.com From tjreedy at udel.edu Sun Dec 13 03:38:12 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 13 Dec 2009 03:38:12 -0500 Subject: Graph library for Python In-Reply-To: References: <4B1D5CB3.8030805@egenix.com> <00a70ac5$0$15659$c3e8da3@news.astraweb.com> <4B1E464B.6090408@chamonix.reportlab.co.uk> Message-ID: geremy condra wrote: > Well, I've just concluded a short conversation with Raymond Hettinger, > and I think its fair to characterize him as being opposed to the idea > at present. In addition to the popularity test, he's also noted that > ideally a core CPython dev should be involved in the project. Putting > the two together is, AFAICS, a death knell for any extant graph lib. > > Having said that, I'd still like to see how much common ground we > could find among the existing libraries. IMHO, there's a lot more > in common than there is different. The large number of current projects practically guarantees that none will be popular enough, and perhaps than none get the usage needed to shake out a broadly useful api. So any consolidation wuold be good. From tjreedy at udel.edu Sun Dec 13 03:45:39 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 13 Dec 2009 03:45:39 -0500 Subject: Dangerous behavior of list(generator) In-Reply-To: References: Message-ID: Tom Machinski wrote: > In most cases, `list(generator)` works as expected. Thus, > `list()` is generally equivalent to `[ expression>]`. > > Here's a minimal case where this equivalence breaks, causing a serious > and hard-to-detect bug in a program: > > >>> def sit(): raise StopIteration() StopIteration is intended to be used only within the .__next__ method of iterators. The devs know that other 'off-label' use results in the inconsistency you noted, but their and my view is 'don't do that'. From gagsl-py2 at yahoo.com.ar Sun Dec 13 03:53:33 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 13 Dec 2009 05:53:33 -0300 Subject: Dangerous behavior of list(generator) References: Message-ID: En Sat, 12 Dec 2009 23:43:20 -0300, Ned Deily escribi?: > In article , > Ned Deily wrote: >> In article >> , >> Benjamin Kaplan wrote: >> > On Sat, Dec 12, 2009 at 7:15 PM, Tom Machinski >> >> > wrote: >> > > >>> def sit(): raise StopIteration() >> > > ... >> > > >>> [f() for f in (lambda:1, sit, lambda:2)] >> > > Traceback (most recent call last): >> > > File "", line 1, in >> > > File "", line 1, in sit >> > > StopIteration >> > > >>> list(f() for f in (lambda:1, sit, lambda:2)) >> > > [1] >> > > In most cases, `list(generator)` works as expected. Thus, >> > > `list()` is generally equivalent to >> `[> > > expression>]`. >> > Actually, it's list(generator) vs. a list comprehension. I agree that >> > it can be confusing, but Python considers them to be two different >> > constructs. I think nobody has addressed the OP arguments (as I understand them). First, except the obvious outer delimiters (and some corner cases in 2.x, fixed in Python 3), a list comprehension and a generator expression share the same syntax: (x for x in some_values) vs [x for x in some_values]. Also, *almost* always, both list() and [], when evaluated, yield the same result [1]. *Almost* because StopIteration is handled differently as the OP discovered: the list comprehension propagates a StopIteration exception to its caller; the list constructor swallows the exception and the caller never sees it. Despite a promise in PEP 289, generator expressions semantics isn't explained in detail in the language reference. I can't tell if the difference is intentional, accidental, undocumented behavior, an implementation accident, a bug, or what... [1] being a syntactic construct like: x**2 for x in range(5) or: f() for f in [lambda:1, sit, lambda:2] -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Sun Dec 13 03:53:33 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 13 Dec 2009 05:53:33 -0300 Subject: Dangerous behavior of list(generator) References: Message-ID: En Sat, 12 Dec 2009 23:43:20 -0300, Ned Deily escribi?: > In article , > Ned Deily wrote: >> In article >> , >> Benjamin Kaplan wrote: >> > On Sat, Dec 12, 2009 at 7:15 PM, Tom Machinski >> >> > wrote: >> > > >>> def sit(): raise StopIteration() >> > > ... >> > > >>> [f() for f in (lambda:1, sit, lambda:2)] >> > > Traceback (most recent call last): >> > > File "", line 1, in >> > > File "", line 1, in sit >> > > StopIteration >> > > >>> list(f() for f in (lambda:1, sit, lambda:2)) >> > > [1] >> > > In most cases, `list(generator)` works as expected. Thus, >> > > `list()` is generally equivalent to >> `[> > > expression>]`. >> > Actually, it's list(generator) vs. a list comprehension. I agree that >> > it can be confusing, but Python considers them to be two different >> > constructs. I think nobody has addressed the OP arguments (as I understand them). First, except the obvious outer delimiters (and some corner cases in 2.x, fixed in Python 3), a list comprehension and a generator expression share the same syntax: (x for x in some_values) vs [x for x in some_values]. Also, *almost* always, both list() and [], when evaluated, yield the same result [1]. *Almost* because StopIteration is handled differently as the OP discovered: the list comprehension propagates a StopIteration exception to its caller; the list constructor swallows the exception and the caller never sees it. Despite a promise in PEP 289, generator expressions semantics isn't explained in detail in the language reference. I can't tell if the difference is intentional, accidental, undocumented behavior, an implementation accident, a bug, or what... [1] being a syntactic construct like: x**2 for x in range(5) or: f() for f in [lambda:1, sit, lambda:2] -- Gabriel Genellina From debatem1 at gmail.com Sun Dec 13 04:31:15 2009 From: debatem1 at gmail.com (geremy condra) Date: Sun, 13 Dec 2009 04:31:15 -0500 Subject: Graph library for Python In-Reply-To: References: <00a70ac5$0$15659$c3e8da3@news.astraweb.com> <4B1E464B.6090408@chamonix.reportlab.co.uk> Message-ID: On Sun, Dec 13, 2009 at 3:38 AM, Terry Reedy wrote: > geremy condra wrote: > >> Well, I've just concluded a short conversation with Raymond Hettinger, >> and I think its fair to characterize him as being opposed to the idea >> at present. In addition to the popularity test, he's also noted that >> ideally a core CPython dev should be involved in the project. Putting >> the two together is, AFAICS, a death knell for any extant graph lib. >> >> Having said that, I'd still like to see how much common ground we >> could find among the existing libraries. IMHO, there's a lot more >> in common than there is different. > > The large number of current projects practically guarantees that none will > be popular enough, and perhaps than none get the usage needed to shake out a > broadly useful api. So any consolidation wuold be good. While I agree, I think it's going to be extremely difficult to get any kind of buy in without a great deal of support from within python. Any devs willing to throw the time required into this? Geremy Condra From __peter__ at web.de Sun Dec 13 05:28:24 2009 From: __peter__ at web.de (Peter Otten) Date: Sun, 13 Dec 2009 11:28:24 +0100 Subject: parse a string of parameters and values References: <57a39e82-08e3-406a-9483-7fa28b180f82@w19g2000pre.googlegroups.com> Message-ID: bsneddon wrote: > I have a problem that I can come up with a brute force solution to > solve but it occurred to me that there may be an > "one-- and preferably only one --obvious way to do it". > > I am going to read a text file that is an export from a control > system. > It has lines with information like > > base=1 name="first one" color=blue > > I would like to put this info into a dictionary for processing. > I have looked at optparse and getopt maybe they are the answer but > there could > be and very straight forward way to do this task. > > Thanks for your help Have a look at shlex: >>> import shlex >>> s = 'base=1 name="first one" color=blue equal="alpha=beta" empty' >>> dict(t.partition("=")[::2] for t in shlex.split(s)) {'color': 'blue', 'base': '1', 'name': 'first one', 'empty': '', 'equal': 'alpha=beta'} Peter From anand.ibmgsi at gmail.com Sun Dec 13 05:32:13 2009 From: anand.ibmgsi at gmail.com (anand jeyahar) Date: Sun, 13 Dec 2009 16:02:13 +0530 Subject: Graph library for Python In-Reply-To: References: <00a70ac5$0$15659$c3e8da3@news.astraweb.com> <4B1E464B.6090408@chamonix.reportlab.co.uk> Message-ID: <1a3a139e0912130232v5d334bf1q6cff7f3ecc5db20e@mail.gmail.com> While I agree, I think it's going to be extremely difficult to get any > kind of buy in without a great deal of support from within python. > Any devs willing to throw the time required into this? > > Geremy Condra > -- > http://mail.python.org/mailman/listinfo/python-list > yep i am interested..... Currently as am on between jobs can devote most of my time over the next 2 months.. but then am not sure.. I have been happy using python-graph.........but recently have grown tired of the number of implementations (not in small part owing to this thread)... A crucial element in this hypothetical module would be the main graph data structure. The simplest approach would be to implement it in pure python, with lists, dicts and such, as many libraries do. However, this would rule out its use by high-performance code, which would need a simpler C-based data structure for direct interaction. On the other hand, I'm not sure if there is a need for a high performance graph module in python's standard library... I disagree...I am not sure of the current need in terms of a precise survey.....But IMO, as bearophile pointed out.....networkx is the most popular........and from their claims it is targeted at mathematicians, physicists, biologists, computer scientists, social scientists. Given the current trend in the growth of social and professional networks..... and social scientists (Disclaimer: i aspire to be one).. i do expect a growing demand for graph data structures and high performance ones soon enough.. so IMHO if we are going in for it we should go for the high performance graphs too.. ============================================== Anand J http://sites.google.com/a/cbcs.ac.in/students/anand ============================================== The man who is really serious, with the urge to find out what truth is, has no style at all. He lives only in what is. ~Bruce Lee Love is a trade with lousy accounting policies. ~Aang Jie -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Sun Dec 13 05:58:55 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 13 Dec 2009 07:58:55 -0300 Subject: Parsing html with Beautifulsoup References: <20091210091519.GA14175@sun.ac.za> <4B21EF06.1040505@sun.ac.za> Message-ID: En Fri, 11 Dec 2009 04:04:38 -0300, Johann Spies escribi?: > Gabriel Genellina het geskryf: >> En Thu, 10 Dec 2009 06:15:19 -0300, Johann Spies >> escribi?: >> >>> How do I get Beautifulsoup to render (taking the above line as >>> example) >>> >>> sunentint for  >> href=#OBJ_sunetint>sunetint
>>> >>> and still provide the text-parts in the 's with plain text? >> >> Hard to tell if we don't see what's inside those 's - please >> provide at least a few rows of the original HTML table. >> > Thanks for your reply. Here are a few lines: > > > 2 src=icons/usrgroup.png> All Users at Any
 Any
src=icons/clientencrypt.png> clientencrypt    I *think* I finally understand what you want (your previous example above confused me). If you want for Rule 1 to generate a line like this: 2,All Users at Any, cell; I preprocess all \n and   in each text node, and join them all. lines is a list of lists (each entry one cell), as expected by the csv module used to write the output file. -- Gabriel Genellina From vicente.soler at gmail.com Sun Dec 13 06:20:03 2009 From: vicente.soler at gmail.com (vsoler) Date: Sun, 13 Dec 2009 03:20:03 -0800 (PST) Subject: unable to read the __main__ namespace Message-ID: I'm learning Python, and I am very fond of it. Using Python 2.6 I am able to list all the names in a class namespace: class abc: pass abc.a1=7 abc.a2='Text' print abc.__dict__.keys() a) However, I do not know how to read the __main__ namespace print __main__.__dict__.keys() # Just does not work b) How do i read an imported module namespace? c) How could I possibly list the names and contents of the namespace of my python session? Thank you for your help. Vicente Soler From __peter__ at web.de Sun Dec 13 06:34:11 2009 From: __peter__ at web.de (Peter Otten) Date: Sun, 13 Dec 2009 12:34:11 +0100 Subject: unable to read the __main__ namespace References: Message-ID: vsoler wrote: > I'm learning Python, and I am very fond of it. > > Using Python 2.6 > > I am able to list all the names in a class namespace: > > class abc: pass > abc.a1=7 > abc.a2='Text' > > print abc.__dict__.keys() > > a) However, I do not know how to read the __main__ namespace > > print __main__.__dict__.keys() # Just does not work It should work. Did you forget to import __main__ before trying? > b) How do i read an imported module namespace? > > c) How could I possibly list the names and contents of the namespace > of my python session? The answer to all your questions is dir() for names and vars() for the complete namespace dictionary: >>> x = 42 >>> dir() ['__builtins__', '__doc__', '__name__', '__package__', 'x'] >>> import os >>> dir(os)[:5] ['EX_CANTCREAT', 'EX_CONFIG', 'EX_DATAERR', 'EX_IOERR', 'EX_NOHOST'] >>> vars() {'__builtins__': , '__package__': None, 'x': 42, '__name__': '__main__', 'os': , '__doc__': None} Peter From clp2 at rebertia.com Sun Dec 13 06:34:30 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 13 Dec 2009 03:34:30 -0800 Subject: unable to read the __main__ namespace In-Reply-To: References: Message-ID: <50697b2c0912130334m64713370v3ba147ac521d8c1f@mail.gmail.com> On Sun, Dec 13, 2009 at 3:20 AM, vsoler wrote: > I'm learning Python, and I am very fond of it. > > Using Python 2.6 > > I am able to list all the names in a class namespace: > > class abc: pass > abc.a1=7 > abc.a2='Text' > > print abc.__dict__.keys() That is more simply written as: print dir(abc) > a) However, I do not know how to read the __main__ namespace > > print __main__.__dict__.keys() ? ?# Just does not work __main__ is not used or set and has no special meaning to the Python interpreter. It's true that __name__ == "__main__" in the body of the main module, but you can't actually access it by that name. > b) How do i read an imported module namespace? import module print dir(module) > c) How could I possibly list the names and contents of the namespace > of my python session? print dir() I'd advise reading the docs on it: http://docs.python.org/library/functions.html#dir Cheers, Chris -- http://blog.rebertia.com From tiago at forked.de Sun Dec 13 07:01:32 2009 From: tiago at forked.de (Tiago de Paula Peixoto) Date: Sun, 13 Dec 2009 10:01:32 -0200 Subject: Graph library for Python In-Reply-To: <1a3a139e0912130232v5d334bf1q6cff7f3ecc5db20e@mail.gmail.com> References: <00a70ac5$0$15659$c3e8da3@news.astraweb.com> <4B1E464B.6090408@chamonix.reportlab.co.uk> <1a3a139e0912130232v5d334bf1q6cff7f3ecc5db20e@mail.gmail.com> Message-ID: On 12/13/2009 08:32 AM, anand jeyahar wrote: > A crucial element in this hypothetical module would be the main graph > data structure. The simplest approach would be to implement it in pure > python, with lists, dicts and such, as many libraries do. However, this > would rule out its use by high-performance code, which would need a > simpler C-based data structure for direct interaction. On the other > hand, I'm not sure if there is a need for a high performance graph > module in python's standard library... > > I disagree...I am not sure of the current need in terms of a precise > survey.....But IMO, as bearophile pointed out.....networkx is the most > popular........and from their claims it is targeted at mathematicians, > physicists, biologists, computer scientists, social scientists. > > Given the current trend in the growth of social and professional > networks..... and social scientists (Disclaimer: i aspire to be one).. i > do expect a growing demand for graph data structures and high > performance ones soon enough.. > > so IMHO if we are going in for it we should go for the high performance > graphs too.. I certainly think it is important to have a high-performance graph library, that is why I started to write one. I was talking simply about its inclusion in the standard library. Since something as basic for scientific computing as, for instance, numpy does not belong in the standard library, I don't think it makes sense to push for the inclusion of a scientific graph library. Could we (or rather should we) even make it _independent_ of numpy? But if the idea is to consolidate the existing graph libraries into an uniform package, I'm certainly not against it in principle. But I think we should first familiarize ourselves with the existing variants, to see if there is really a common ground. The basic interface to the graph data structure should not vary much, I believe, but the implementation may. For instance, I chose in graph-tool to implement most of it in C++ with the Boost Graph Library... When I get some time, I'll take a careful look at the implementations listed in this thread, some of which I don't yet know. Cheers, Tiago -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 262 bytes Desc: OpenPGP digital signature URL: From invalid at invalid.invalid Sun Dec 13 09:28:24 2009 From: invalid at invalid.invalid (Grant Edwards) Date: Sun, 13 Dec 2009 14:28:24 +0000 (UTC) Subject: read text file byte by byte References: <00acf5b1$0$15654$c3e8da3@news.astraweb.com> <4b24a3c8$0$937$ba4acef3@news.orange.fr> Message-ID: On 2009-12-13, Michel Claveau - MVP wrote: > Hi! > >> If it's a binary file... > > OK, but... what is a "binary" file? One containing data encoded in base-2. -- Grant From exarkun at twistedmatrix.com Sun Dec 13 09:35:21 2009 From: exarkun at twistedmatrix.com (exarkun at twistedmatrix.com) Date: Sun, 13 Dec 2009 14:35:21 -0000 Subject: Dangerous behavior of list(generator) In-Reply-To: References: Message-ID: <20091213143521.2549.845539319.divmod.xquotient.731@localhost.localdomain> On 08:45 am, tjreedy at udel.edu wrote: >Tom Machinski wrote: >>In most cases, `list(generator)` works as expected. Thus, >>`list()` is generally equivalent to `[>expression>]`. >> >>Here's a minimal case where this equivalence breaks, causing a serious >>and hard-to-detect bug in a program: >> >> >>> def sit(): raise StopIteration() > >StopIteration is intended to be used only within the .__next__ method >of iterators. The devs know that other 'off-label' use results in the >inconsistency you noted, but their and my view is 'don't do that'. Which is unfortunate, because it's not that hard to get StopIteration without explicitly raising it yourself and this behavior makes it difficult to debug such situations. What's with this view, exactly? Is it just that it's hard to implement the more desirable behavior? Jean-Paul From python.list at tim.thechases.com Sun Dec 13 09:42:26 2009 From: python.list at tim.thechases.com (Tim Chase) Date: Sun, 13 Dec 2009 08:42:26 -0600 Subject: read text file byte by byte In-Reply-To: References: <00acf5b1$0$15654$c3e8da3@news.astraweb.com> <4b24a3c8$0$937$ba4acef3@news.orange.fr> Message-ID: <4B24FD52.3010306@tim.thechases.com> Grant Edwards wrote: >>> If it's a binary file... >> OK, but... what is a "binary" file? > > One containing data encoded in base-2. Or one of a system of two files that orbits around a common center of mass? So if you see two files orbiting around a cathedral, they're binary files. f.open('binaryfile.bin', 'wb') f.write(data.encode('binary')) f.close() :-) -tkc From bsneddon at yahoo.com Sun Dec 13 10:23:19 2009 From: bsneddon at yahoo.com (bsneddon) Date: Sun, 13 Dec 2009 07:23:19 -0800 (PST) Subject: parse a string of parameters and values References: <57a39e82-08e3-406a-9483-7fa28b180f82@w19g2000pre.googlegroups.com> Message-ID: On Dec 13, 5:28?am, Peter Otten <__pete... at web.de> wrote: > bsneddon wrote: > > I have a problem that I can come up with a brute force solution to > > solve but it occurred to me that there may be an > > ?"one-- and preferably only one --obvious way to do it". > > > I am going to read a text file that is an export from a control > > system. > > It has lines with information like > > > base=1 name="first one" color=blue > > > I would like to put this info into a dictionary for processing. > > I have looked at optparse and getopt maybe they are the answer but > > there could > > be and very straight forward way to do this task. > > > Thanks for your help > > Have a look at shlex: > > >>> import shlex > >>> s = 'base=1 name="first one" color=blue equal="alpha=beta" empty' > >>> dict(t.partition("=")[::2] for t in shlex.split(s)) > > {'color': 'blue', 'base': '1', 'name': 'first one', 'empty': '', 'equal': > 'alpha=beta'} > > Peter Thanks to all for your input. It seems I miss stated the problem. Text is always quoted so blue above -> "blue". Peter, The part I was missing was t.partition("=") and slicing skipping by two. It looks like a normal split will work for me to get the arguments I need. To my way of thinking your is very clean any maybe the "--obvious way to do it" Although it was not obvious to me until seeing your post. Bill From victorsubervi at gmail.com Sun Dec 13 10:48:45 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Sun, 13 Dec 2009 10:48:45 -0500 Subject: Manipulating MySQL Sets In-Reply-To: References: <4dc0cfea0912121334gcf5af27l71a173c6a71f59d2@mail.gmail.com> <4dc0cfea0912121507u499aa5e3j3316f8bef425fef1@mail.gmail.com> <4dc0cfea0912121513y82451b9lbc31c6f54394a89f@mail.gmail.com> Message-ID: <4dc0cfea0912130748u186092ct952f2e582b81d932@mail.gmail.com> On Sat, Dec 12, 2009 at 6:35 PM, Carsten Haese wrote: > The traceback helpfully shows us that colValue is a 1-tuple whose zeroth > entry, colValue[0], is an actual bona-fide Python Set object. Such > objects aren't indexable, because sets are unordered. That still doesn't > tell us where colValue is coming from, though, so why it is a Python Set > object when you expected it to be a string remains an unsolved mystery. > Who said I was expecting a string? I don't know what I'm expecting! I need to be able to parse this thing, whatever it is. You say it's a Python Set object. How do I parse it? Googling has been disappointing. TIA, V -------------- next part -------------- An HTML attachment was scrubbed... URL: From sbassi at clubdelarazon.org Sun Dec 13 11:26:53 2009 From: sbassi at clubdelarazon.org (Sebastian Bassi) Date: Sun, 13 Dec 2009 13:26:53 -0300 Subject: Manipulating MySQL Sets In-Reply-To: <4dc0cfea0912130748u186092ct952f2e582b81d932@mail.gmail.com> References: <4dc0cfea0912121334gcf5af27l71a173c6a71f59d2@mail.gmail.com> <4dc0cfea0912121507u499aa5e3j3316f8bef425fef1@mail.gmail.com> <4dc0cfea0912121513y82451b9lbc31c6f54394a89f@mail.gmail.com> <4dc0cfea0912130748u186092ct952f2e582b81d932@mail.gmail.com> Message-ID: <9e2f512b0912130826v2e6e57c9kc05c525b737758d7@mail.gmail.com> On Sun, Dec 13, 2009 at 12:48 PM, Victor Subervi wrote: > Who said I was expecting a string? I don't know what I'm expecting! I need > to be able to parse this thing, whatever it is. You say it's a Python Set > object. How do I parse it? Googling has been disappointing. You can walk thought a set object like any iterable object like for x in myset: #do something like parse it. If you want to slice it, convert it to a list: mylist = list(myset) Or read about sets: http://docs.python.org/library/sets.html From carsten.haese at gmail.com Sun Dec 13 11:36:44 2009 From: carsten.haese at gmail.com (Carsten Haese) Date: Sun, 13 Dec 2009 11:36:44 -0500 Subject: Manipulating MySQL Sets In-Reply-To: <4dc0cfea0912130748u186092ct952f2e582b81d932@mail.gmail.com> References: <4dc0cfea0912121334gcf5af27l71a173c6a71f59d2@mail.gmail.com> <4dc0cfea0912121507u499aa5e3j3316f8bef425fef1@mail.gmail.com> <4dc0cfea0912121513y82451b9lbc31c6f54394a89f@mail.gmail.com> <4dc0cfea0912130748u186092ct952f2e582b81d932@mail.gmail.com> Message-ID: Victor Subervi wrote: > On Sat, Dec 12, 2009 at 6:35 PM, Carsten Haese > wrote: > > The traceback helpfully shows us that colValue is a 1-tuple whose zeroth > entry, colValue[0], is an actual bona-fide Python Set object. Such > objects aren't indexable, because sets are unordered. That still doesn't > tell us where colValue is coming from, though, so why it is a Python Set > object when you expected it to be a string remains an unsolved mystery. > > > Who said I was expecting a string? You did, indirectly, since you were expecting the value to be the contents of a MySQL SET column, which as far as I can determine should be returned as a string. (Recall that I showed a complete example that demonstrates this.) The fact that you don't get a string is something that you ought to be interested in investigating. > I don't know what I'm expecting! That statement is the most succinct summary of the root cause of all your problems. If you don't know what to expect, how could you possibly write code that produces what you expect? (Don't answer this question. It's a rhetorical question.) > I need to be able to parse this thing, whatever it is. You say it's a > Python Set object. How do I parse it? Googling has been disappointing. What do you mean by "parse"? What is the end result you are hoping to achieve by "parsing" a Set object? -- Carsten Haese http://informixdb.sourceforge.net From gervaz at gmail.com Sun Dec 13 11:37:20 2009 From: gervaz at gmail.com (mattia) Date: 13 Dec 2009 16:37:20 GMT Subject: insert unique data in a list Message-ID: <4b251840$0$30959$4fafbaef@reader3.news.tin.it> How can I insert non-duplicate data in a list? I mean, is there a particular option in the creation of a list that permit me not to use something like: def append_unique(l, val): if val not in l: l.append(val) Thanks, Mattia From victorsubervi at gmail.com Sun Dec 13 11:46:44 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Sun, 13 Dec 2009 11:46:44 -0500 Subject: Manipulating MySQL Sets In-Reply-To: References: <4dc0cfea0912121334gcf5af27l71a173c6a71f59d2@mail.gmail.com> <4dc0cfea0912121507u499aa5e3j3316f8bef425fef1@mail.gmail.com> <4dc0cfea0912121513y82451b9lbc31c6f54394a89f@mail.gmail.com> <4dc0cfea0912130748u186092ct952f2e582b81d932@mail.gmail.com> Message-ID: <4dc0cfea0912130846o3e111063g284e3de644ae6270@mail.gmail.com> On Sun, Dec 13, 2009 at 11:36 AM, Carsten Haese wrote: > > I don't know what I'm expecting! > > That statement is the most succinct summary of the root cause of all > your problems. If you don't know what to expect, how could you possibly > write code that produces what you expect? (Don't answer this question. > It's a rhetorical question.) > LOL! Yeah. Not entirely true, obviously, or even mostly so...but enough to be humorous ;) > > > I need to be able to parse this thing, whatever it is. You say it's a > > Python Set object. How do I parse it? Googling has been disappointing. > > What do you mean by "parse"? What is the end result you are hoping to > achieve by "parsing" a Set object? > I need to get at the individual elements of the set (that which is between the single quotes). TIA, V -------------- next part -------------- An HTML attachment was scrubbed... URL: From rpjday at crashcourse.ca Sun Dec 13 11:56:30 2009 From: rpjday at crashcourse.ca (Robert P. J. Day) Date: Sun, 13 Dec 2009 11:56:30 -0500 (EST) Subject: Manipulating MySQL Sets In-Reply-To: <4dc0cfea0912130846o3e111063g284e3de644ae6270@mail.gmail.com> References: <4dc0cfea0912121334gcf5af27l71a173c6a71f59d2@mail.gmail.com> <4dc0cfea0912121507u499aa5e3j3316f8bef425fef1@mail.gmail.com> <4dc0cfea0912121513y82451b9lbc31c6f54394a89f@mail.gmail.com> <4dc0cfea0912130748u186092ct952f2e582b81d932@mail.gmail.com> <4dc0cfea0912130846o3e111063g284e3de644ae6270@mail.gmail.com> Message-ID: On Sun, 13 Dec 2009, Victor Subervi wrote: > On Sun, Dec 13, 2009 at 11:36 AM, Carsten Haese > wrote: > > I don't know what I'm expecting! > > That statement is the most succinct summary of the root cause of all > your problems. If you don't know what to expect, how could you > possibly write code that produces what you expect? (Don't answer > this question. It's a rhetorical question.) http://twitter.com/rpjday/status/6576145809 rday -- ======================================================================== Robert P. J. Day Waterloo, Ontario, CANADA Linux Consulting, Training and Kernel Pedantry. Web page: http://crashcourse.ca Twitter: http://twitter.com/rpjday ======================================================================== From victorsubervi at gmail.com Sun Dec 13 12:01:56 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Sun, 13 Dec 2009 12:01:56 -0500 Subject: Manipulating MySQL Sets In-Reply-To: References: <4dc0cfea0912121334gcf5af27l71a173c6a71f59d2@mail.gmail.com> <4dc0cfea0912121507u499aa5e3j3316f8bef425fef1@mail.gmail.com> <4dc0cfea0912121513y82451b9lbc31c6f54394a89f@mail.gmail.com> <4dc0cfea0912130748u186092ct952f2e582b81d932@mail.gmail.com> <4dc0cfea0912130846o3e111063g284e3de644ae6270@mail.gmail.com> Message-ID: <4dc0cfea0912130901u1a939885ha0ce308ba470c3be@mail.gmail.com> On Sun, Dec 13, 2009 at 11:56 AM, Robert P. J. Day wrote: > On Sun, 13 Dec 2009, Victor Subervi wrote: > > > On Sun, Dec 13, 2009 at 11:36 AM, Carsten Haese > > > wrote: > > > I don't know what I'm expecting! > > > > That statement is the most succinct summary of the root cause of all > > your problems. If you don't know what to expect, how could you > > possibly write code that produces what you expect? (Don't answer > > this question. It's a rhetorical question.) > > http://twitter.com/rpjday/status/6576145809 > Indeed. Specification, however, is as much art as it is science. Are you a better programmer today than your first day programming? Have you learned how to specify better in the process? More rhetorical questions ;) V -------------- next part -------------- An HTML attachment was scrubbed... URL: From half.italian at gmail.com Sun Dec 13 12:05:31 2009 From: half.italian at gmail.com (Sean DiZazzo) Date: Sun, 13 Dec 2009 09:05:31 -0800 (PST) Subject: insert unique data in a list References: <4b251840$0$30959$4fafbaef@reader3.news.tin.it> Message-ID: <51b5f5c6-fac6-4210-89f5-c84a7c6d42be@j9g2000prh.googlegroups.com> On Dec 13, 8:37?am, mattia wrote: > How can I insert non-duplicate data in a list? I mean, is there a > particular option in the creation of a list that permit me not to use > something like: > def append_unique(l, val): > ? ? if val not in l: > ? ? ? ? l.append(val) > > Thanks, > Mattia Check out the set() data type. ~Sean From gherron at islandtraining.com Sun Dec 13 12:07:08 2009 From: gherron at islandtraining.com (Gary Herron) Date: Sun, 13 Dec 2009 09:07:08 -0800 Subject: insert unique data in a list In-Reply-To: <4b251840$0$30959$4fafbaef@reader3.news.tin.it> References: <4b251840$0$30959$4fafbaef@reader3.news.tin.it> Message-ID: <4B251F3C.7020205@islandtraining.com> mattia wrote: > How can I insert non-duplicate data in a list? I mean, is there a > particular option in the creation of a list that permit me not to use > something like: > def append_unique(l, val): > if val not in l: > l.append(val) > > Thanks, > Mattia > Unless the insertion order is important, you could use a set -- where a second insertion will have no effect. >>> s = set() >>> s.add(1) >>> s.add(2) >>> s.add(1) >>> print s set([1, 2]) Gary Herron From alfps at start.no Sun Dec 13 12:08:41 2009 From: alfps at start.no (Alf P. Steinbach) Date: Sun, 13 Dec 2009 18:08:41 +0100 Subject: insert unique data in a list In-Reply-To: <4b251840$0$30959$4fafbaef@reader3.news.tin.it> References: <4b251840$0$30959$4fafbaef@reader3.news.tin.it> Message-ID: * mattia: > How can I insert non-duplicate data in a list? I mean, is there a > particular option in the creation of a list that permit me not to use > something like: > def append_unique(l, val): > if val not in l: > l.append(val) > How about using a set instead? >>> a = {1, 2, 3} >>> a {1, 2, 3} >>> a |= {4} >>> a {1, 2, 3, 4} >>> a |= {4} >>> a {1, 2, 3, 4} >>> _ Cheers, - Alf From rpjday at crashcourse.ca Sun Dec 13 12:10:19 2009 From: rpjday at crashcourse.ca (Robert P. J. Day) Date: Sun, 13 Dec 2009 12:10:19 -0500 (EST) Subject: Manipulating MySQL Sets In-Reply-To: <4dc0cfea0912130901u1a939885ha0ce308ba470c3be@mail.gmail.com> References: <4dc0cfea0912121334gcf5af27l71a173c6a71f59d2@mail.gmail.com> <4dc0cfea0912121507u499aa5e3j3316f8bef425fef1@mail.gmail.com> <4dc0cfea0912121513y82451b9lbc31c6f54394a89f@mail.gmail.com> <4dc0cfea0912130748u186092ct952f2e582b81d932@mail.gmail.com> <4dc0cfea0912130846o3e111063g284e3de644ae6270@mail.gmail.com> <4dc0cfea0912130901u1a939885ha0ce308ba470c3be@mail.gmail.com> Message-ID: On Sun, 13 Dec 2009, Victor Subervi wrote: > On Sun, Dec 13, 2009 at 11:56 AM, Robert P. J. Day > wrote: > On Sun, 13 Dec 2009, Victor Subervi wrote: > > > On Sun, Dec 13, 2009 at 11:36 AM, Carsten Haese > > > wrote: > > ? ? ? > I don't know what I'm expecting! > > > > That statement is the most succinct summary of the root cause > of all > > your problems. If you don't know what to expect, how could you > > possibly write code that produces what you expect? (Don't > answer > > this question. It's a rhetorical question.) > > ?http://twitter.com/rpjday/status/6576145809 > > > Indeed. Specification, however, is as much art as it is science. Are > you a better programmer today than your first day programming? Have > you learned how to specify better in the process? More rhetorical > questions ;) it's sunday, i have beer and there's an NFL game on soon. do not ask tough questions. that is all. rday -- ======================================================================== Robert P. J. Day Waterloo, Ontario, CANADA Linux Consulting, Training and Kernel Pedantry. Web page: http://crashcourse.ca Twitter: http://twitter.com/rpjday ======================================================================== From carsten.haese at gmail.com Sun Dec 13 12:10:45 2009 From: carsten.haese at gmail.com (Carsten Haese) Date: Sun, 13 Dec 2009 12:10:45 -0500 Subject: Manipulating MySQL Sets In-Reply-To: <4dc0cfea0912130846o3e111063g284e3de644ae6270@mail.gmail.com> References: <4dc0cfea0912121334gcf5af27l71a173c6a71f59d2@mail.gmail.com> <4dc0cfea0912121507u499aa5e3j3316f8bef425fef1@mail.gmail.com> <4dc0cfea0912121513y82451b9lbc31c6f54394a89f@mail.gmail.com> <4dc0cfea0912130748u186092ct952f2e582b81d932@mail.gmail.com> <4dc0cfea0912130846o3e111063g284e3de644ae6270@mail.gmail.com> Message-ID: Victor Subervi wrote: > I need to get at the individual elements of the set (that which is > between the single quotes). It's not quite clear what you mean by "get at the individual elements", so I'll just show you a couple of things you can do to a set, and maybe one of them comes close to what you need: >>> from sets import Set >>> aSet = Set(['Small', 'Extra-small', 'Medium']) Do something for each element: >>> for element in aSet: ... print element ... Small Extra-small Medium Convert the set to list: >>> list(aSet) ['Small', 'Extra-small', 'Medium'] Test membership in the set: >>> 'Small' in aSet True >>> 'Banana' in aSet False HTH, -- Carsten Haese http://informixdb.sourceforge.net From victorsubervi at gmail.com Sun Dec 13 12:20:58 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Sun, 13 Dec 2009 12:20:58 -0500 Subject: Manipulating MySQL Sets In-Reply-To: <9e2f512b0912130826v2e6e57c9kc05c525b737758d7@mail.gmail.com> References: <4dc0cfea0912121334gcf5af27l71a173c6a71f59d2@mail.gmail.com> <4dc0cfea0912121507u499aa5e3j3316f8bef425fef1@mail.gmail.com> <4dc0cfea0912121513y82451b9lbc31c6f54394a89f@mail.gmail.com> <4dc0cfea0912130748u186092ct952f2e582b81d932@mail.gmail.com> <9e2f512b0912130826v2e6e57c9kc05c525b737758d7@mail.gmail.com> Message-ID: <4dc0cfea0912130920l3a6b88c8s2a55102d9b160e50@mail.gmail.com> On Sun, Dec 13, 2009 at 11:26 AM, Sebastian Bassi wrote: > On Sun, Dec 13, 2009 at 12:48 PM, Victor Subervi > wrote: > > Who said I was expecting a string? I don't know what I'm expecting! I > need > > to be able to parse this thing, whatever it is. You say it's a Python Set > > object. How do I parse it? Googling has been disappointing. > > You can walk thought a set object like any iterable object like > > for x in myset: > #do something like parse it. > > If you want to slice it, convert it to a list: > > mylist = list(myset) > > Or read about sets: > http://docs.python.org/library/sets.html > Both the following solutions threw the same error: newCol = list(colValue[0]) print newCol[0:20] and for x in colValue[0]: print x /var/www/html/angrynates.com/cart/display.py 98 raise 99 cursor.close() 100 bottom() 101 102 display() display = /var/www/html/angrynates.com/cart/display.py in display() 50 # newCol = list(colValue[0]) 51 # print newCol[0:20] 52 for x in colValue[0]: 53 print x 54 print 'XXX' x undefined, colValue = (datetime.date(2009, 10, 22),) TypeError: iteration over non-sequence args = ('iteration over non-sequence',) V -------------- next part -------------- An HTML attachment was scrubbed... URL: From sbassi at clubdelarazon.org Sun Dec 13 12:26:33 2009 From: sbassi at clubdelarazon.org (Sebastian Bassi) Date: Sun, 13 Dec 2009 14:26:33 -0300 Subject: Manipulating MySQL Sets In-Reply-To: References: <4dc0cfea0912121334gcf5af27l71a173c6a71f59d2@mail.gmail.com> <4dc0cfea0912121507u499aa5e3j3316f8bef425fef1@mail.gmail.com> <4dc0cfea0912121513y82451b9lbc31c6f54394a89f@mail.gmail.com> <4dc0cfea0912130748u186092ct952f2e582b81d932@mail.gmail.com> <4dc0cfea0912130846o3e111063g284e3de644ae6270@mail.gmail.com> Message-ID: <9e2f512b0912130926p1b4905e9q4c2ec3fcb7dde593@mail.gmail.com> On Sun, Dec 13, 2009 at 2:10 PM, Carsten Haese wrote: >>>> from sets import Set >>>> aSet = Set(['Small', 'Extra-small', 'Medium']) You don't need to import "Set" since it is built in now: >>> a=set([1,2,2,3,4,5]) >>> a set([1, 2, 3, 4, 5]) (I have Python 2.6.2 but I think that this is available from 2.4 or 2.5). From victorsubervi at gmail.com Sun Dec 13 12:39:41 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Sun, 13 Dec 2009 12:39:41 -0500 Subject: Manipulating MySQL Sets In-Reply-To: References: <4dc0cfea0912121334gcf5af27l71a173c6a71f59d2@mail.gmail.com> <4dc0cfea0912121507u499aa5e3j3316f8bef425fef1@mail.gmail.com> <4dc0cfea0912121513y82451b9lbc31c6f54394a89f@mail.gmail.com> <4dc0cfea0912130748u186092ct952f2e582b81d932@mail.gmail.com> <4dc0cfea0912130846o3e111063g284e3de644ae6270@mail.gmail.com> Message-ID: <4dc0cfea0912130939u315046a0w892ee414d5324be2@mail.gmail.com> On Sun, Dec 13, 2009 at 12:10 PM, Carsten Haese wrote: > Victor Subervi wrote: > > I need to get at the individual elements of the set (that which is > > between the single quotes). > > It's not quite clear what you mean by "get at the individual elements", > so I'll just show you a couple of things you can do to a set, and maybe > one of them comes close to what you need: > > >>> from sets import Set > >>> aSet = Set(['Small', 'Extra-small', 'Medium']) > > Do something for each element: > > >>> for element in aSet: > ... print element > ... > Small > Extra-small > Medium > > Convert the set to list: > > >>> list(aSet) > ['Small', 'Extra-small', 'Medium'] > > Test membership in the set: > > >>> 'Small' in aSet > True > >>> 'Banana' in aSet > False > > Carsten, thank you (once again ;) for your patience. I didn't know I had to import something. Thanks again, V -------------- next part -------------- An HTML attachment was scrubbed... URL: From victorsubervi at gmail.com Sun Dec 13 12:40:46 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Sun, 13 Dec 2009 12:40:46 -0500 Subject: Manipulating MySQL Sets In-Reply-To: <4dc0cfea0912130939u315046a0w892ee414d5324be2@mail.gmail.com> References: <4dc0cfea0912121334gcf5af27l71a173c6a71f59d2@mail.gmail.com> <4dc0cfea0912121507u499aa5e3j3316f8bef425fef1@mail.gmail.com> <4dc0cfea0912121513y82451b9lbc31c6f54394a89f@mail.gmail.com> <4dc0cfea0912130748u186092ct952f2e582b81d932@mail.gmail.com> <4dc0cfea0912130846o3e111063g284e3de644ae6270@mail.gmail.com> <4dc0cfea0912130939u315046a0w892ee414d5324be2@mail.gmail.com> Message-ID: <4dc0cfea0912130940y7e365fc8s34c4cbfd8d95c28d@mail.gmail.com> On Sun, Dec 13, 2009 at 12:39 PM, Victor Subervi wrote: PS: I have another field that's a datetime with the same problem. How do I parse and otherwise work with that? TIA, V -------------- next part -------------- An HTML attachment was scrubbed... URL: From gervaz at gmail.com Sun Dec 13 12:57:47 2009 From: gervaz at gmail.com (mattia) Date: 13 Dec 2009 17:57:47 GMT Subject: insert unique data in a list References: <4b251840$0$30959$4fafbaef@reader3.news.tin.it> Message-ID: <4b252b1b$0$644$4fafbaef@reader4.news.tin.it> Il Sun, 13 Dec 2009 16:37:20 +0000, mattia ha scritto: > How can I insert non-duplicate data in a list? I mean, is there a > particular option in the creation of a list that permit me not to use > something like: > def append_unique(l, val): > if val not in l: > l.append(val) > > Thanks, > Mattia Ok, so you all suggest to use a set. Now the second question, more interesting. Why can't I insert a list into a set? I mean, I have a function that returns a list. I call this function several times and maybe the list returned is the same as another one already returned. I usually put all this lists into another list. How can I assure that my list contains only unique lists? Using set does'n work (i.e. the python interpreter tells me: TypeError: unhashable type: 'list')... From usenot at geekmail.INVALID Sun Dec 13 13:19:10 2009 From: usenot at geekmail.INVALID (Andreas Waldenburger) Date: Sun, 13 Dec 2009 19:19:10 +0100 Subject: insert unique data in a list References: <4b251840$0$30959$4fafbaef@reader3.news.tin.it> <4b252b1b$0$644$4fafbaef@reader4.news.tin.it> Message-ID: <20091213191910.4b855963@geekmail.INVALID> On 13 Dec 2009 17:57:47 GMT mattia wrote: > Using set does'n work (i.e. the python interpreter tells me: > TypeError: unhashable type: 'list')... Convert the lists to tuples before adding them. Tuples are hashable. /W -- INVALID? DE! From gherron at islandtraining.com Sun Dec 13 13:20:29 2009 From: gherron at islandtraining.com (Gary Herron) Date: Sun, 13 Dec 2009 10:20:29 -0800 Subject: insert unique data in a list In-Reply-To: <4b252b1b$0$644$4fafbaef@reader4.news.tin.it> References: <4b251840$0$30959$4fafbaef@reader3.news.tin.it> <4b252b1b$0$644$4fafbaef@reader4.news.tin.it> Message-ID: <4B25306D.7030406@islandtraining.com> mattia wrote: > Il Sun, 13 Dec 2009 16:37:20 +0000, mattia ha scritto: > > >> How can I insert non-duplicate data in a list? I mean, is there a >> particular option in the creation of a list that permit me not to use >> something like: >> def append_unique(l, val): >> if val not in l: >> l.append(val) >> >> Thanks, >> Mattia >> > > Ok, so you all suggest to use a set. Now the second question, more > interesting. Why can't I insert a list into a set? I mean, I have a > function that returns a list. I call this function several times and > maybe the list returned is the same as another one already returned. I > usually put all this lists into another list. How can I assure that my > list contains only unique lists? Using set does'n work (i.e. the python > interpreter tells me: TypeError: unhashable type: 'list')... > Sets can contain *only* hashable objects, but lists are not hashable (since they are mutable). Perhaps, you could convert your list to a tuple first -- tuples *are* hashable. >>> s = set() >>> l = [1,2,3] >>> s.add(l) Traceback (most recent call last): File "", line 1, in TypeError: unhashable type: 'list' >>> s.add(tuple(l)) >>> s set([(1, 2, 3)]) From victorsubervi at gmail.com Sun Dec 13 13:22:36 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Sun, 13 Dec 2009 13:22:36 -0500 Subject: Another MySQL Problem Message-ID: <4dc0cfea0912131022n1f54985alc77a507c2ab7b0a2@mail.gmail.com> Hi; mysql> truncate tem126072414516; Query OK, 0 rows affected (0.00 sec) Then I run a script: if whatDo == 'insert': try: sql = 'insert into %s (ProdID, Quantity) values ("%s", "%s");' % (tmpTable, prodid, quantity) print sql cursor.execute(sql) that runs this (printed out) sql insert statement: insert into tem126072832767 (ProdID, Quantity) values ("2", "2"); But then this... mysql> select * from tem12607282453 t join products p on t.ID=p.ID; Empty set (0.00 sec) mysql> insert into tem126072829782 (ProdID, Quantity) values ("2", "2"); ERROR 1062 (23000): Duplicate entry '2' for key 2 I have to manually truncate the table to manually insert it, and then it works. But programmatically, it doesn't insert...but it apparently inserts something, or it wouldn't throw the duplicate entry error. Where is the problem? TIA, Victor -------------- next part -------------- An HTML attachment was scrubbed... URL: From vicente.soler at gmail.com Sun Dec 13 13:23:20 2009 From: vicente.soler at gmail.com (vsoler) Date: Sun, 13 Dec 2009 10:23:20 -0800 (PST) Subject: unable to read the __main__ namespace References: Message-ID: <3e3adfcf-5c6a-4609-9024-09cfdba8b234@v25g2000yqk.googlegroups.com> On Dec 13, 12:34?pm, Chris Rebert wrote: > On Sun, Dec 13, 2009 at 3:20 AM, vsoler wrote: > > I'm learning Python, and I am very fond of it. > > > Using Python 2.6 > > > I am able to list all the names in a class namespace: > > > class abc: pass > > abc.a1=7 > > abc.a2='Text' > > > print abc.__dict__.keys() > > That is more simply written as: > > print dir(abc) > > > a) However, I do not know how to read the __main__ namespace > > > print __main__.__dict__.keys() ? ?# Just does not work > > __main__ is not used or set and has no special meaning to the Python > interpreter. It's true that __name__ == "__main__" in the body of the > main module, but you can't actually access it by that name. > > > b) How do i read an imported module namespace? > > import module > print dir(module) > > > c) How could I possibly list the names and contents of the namespace > > of my python session? > > print dir() > > I'd advise reading the docs on it:http://docs.python.org/library/functions.html#dir > > Cheers, > Chris > --http://blog.rebertia.com Thank you very much. I now know how to proceed From python at mrabarnett.plus.com Sun Dec 13 13:31:58 2009 From: python at mrabarnett.plus.com (MRAB) Date: Sun, 13 Dec 2009 18:31:58 +0000 Subject: Manipulating MySQL Sets In-Reply-To: <4dc0cfea0912130920l3a6b88c8s2a55102d9b160e50@mail.gmail.com> References: <4dc0cfea0912121334gcf5af27l71a173c6a71f59d2@mail.gmail.com> <4dc0cfea0912121507u499aa5e3j3316f8bef425fef1@mail.gmail.com> <4dc0cfea0912121513y82451b9lbc31c6f54394a89f@mail.gmail.com> <4dc0cfea0912130748u186092ct952f2e582b81d932@mail.gmail.com> <9e2f512b0912130826v2e6e57c9kc05c525b737758d7@mail.gmail.com> <4dc0cfea0912130920l3a6b88c8s2a55102d9b160e50@mail.gmail.com> Message-ID: <4B25331E.4090908@mrabarnett.plus.com> Victor Subervi wrote: > On Sun, Dec 13, 2009 at 11:26 AM, Sebastian Bassi > > wrote: > > On Sun, Dec 13, 2009 at 12:48 PM, Victor Subervi > > wrote: > > Who said I was expecting a string? I don't know what I'm > expecting! I need > > to be able to parse this thing, whatever it is. You say it's a > Python Set > > object. How do I parse it? Googling has been disappointing. > > You can walk thought a set object like any iterable object like > > for x in myset: > #do something like parse it. > > If you want to slice it, convert it to a list: > > mylist = list(myset) > > Or read about sets: > http://docs.python.org/library/sets.html > > > Both the following solutions threw the same error: > > newCol = list(colValue[0]) > print newCol[0:20] > > and > > for x in colValue[0]: > print x > > /var/www/html/angrynates.com/cart/display.py > > 98 raise > 99 cursor.close() > 100 bottom() > 101 > 102 display() > display = > /var/www/html/angrynates.com/cart/display.py > in display() > 50 # newCol = list(colValue[0]) > 51 # print newCol[0:20] > 52 for x in colValue[0]: > 53 print x > 54 print 'XXX' > x undefined, colValue = (datetime.date(2009, 10, 22),) > > TypeError: iteration over non-sequence > args = ('iteration over non-sequence',) > That tells me that, in this case, colValue[0] is an instance of datetime, not Set. From victorsubervi at gmail.com Sun Dec 13 13:35:51 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Sun, 13 Dec 2009 13:35:51 -0500 Subject: Manipulating MySQL Sets In-Reply-To: <4dc0cfea0912130940y7e365fc8s34c4cbfd8d95c28d@mail.gmail.com> References: <4dc0cfea0912121334gcf5af27l71a173c6a71f59d2@mail.gmail.com> <4dc0cfea0912121507u499aa5e3j3316f8bef425fef1@mail.gmail.com> <4dc0cfea0912121513y82451b9lbc31c6f54394a89f@mail.gmail.com> <4dc0cfea0912130748u186092ct952f2e582b81d932@mail.gmail.com> <4dc0cfea0912130846o3e111063g284e3de644ae6270@mail.gmail.com> <4dc0cfea0912130939u315046a0w892ee414d5324be2@mail.gmail.com> <4dc0cfea0912130940y7e365fc8s34c4cbfd8d95c28d@mail.gmail.com> Message-ID: <4dc0cfea0912131035p6f971968n5741c77e25f6f4b9@mail.gmail.com> On Sun, Dec 13, 2009 at 12:40 PM, Victor Subervi wrote: > On Sun, Dec 13, 2009 at 12:39 PM, Victor Subervi wrote: > > PS: I have another field that's a datetime with the same problem. How do I > parse and otherwise work with that? > I have yet another problem with this. Once I've determined it's a Set or a datetime, I do this: for itm in colValue[0]: try: color, number = string.split(itm, ':') html += "" % (itm, color) except: html += "" % (itm, itm) The reason is I've entered my colors into my table as nameOfColor:colorNumber and I want to break them out for presentation purposes. However, the try never executes, only the except, and that shouldn't be. I can slice the itm. What gives? TIA, V -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at mrabarnett.plus.com Sun Dec 13 13:37:30 2009 From: python at mrabarnett.plus.com (MRAB) Date: Sun, 13 Dec 2009 18:37:30 +0000 Subject: Another MySQL Problem In-Reply-To: <4dc0cfea0912131022n1f54985alc77a507c2ab7b0a2@mail.gmail.com> References: <4dc0cfea0912131022n1f54985alc77a507c2ab7b0a2@mail.gmail.com> Message-ID: <4B25346A.7000805@mrabarnett.plus.com> Victor Subervi wrote: > Hi; > > mysql> truncate tem126072414516; > Query OK, 0 rows affected (0.00 sec) > > Then I run a script: > > if whatDo == 'insert': > try: > sql = 'insert into %s (ProdID, Quantity) values ("%s", "%s");' % > (tmpTable, prodid, quantity) > print sql > cursor.execute(sql) > > that runs this (printed out) sql insert statement: > > insert into tem126072832767 (ProdID, Quantity) values ("2", "2"); > > But then this... > > mysql> select * from tem12607282453 t join products p on t.ID=p.ID; > Empty set (0.00 sec) > > mysql> insert into tem126072829782 (ProdID, Quantity) values ("2", "2"); > ERROR 1062 (23000): Duplicate entry '2' for key 2 > > I have to manually truncate the table to manually insert it, and then it > works. But programmatically, it doesn't insert...but it apparently > inserts something, or it wouldn't throw the duplicate entry error. Where > is the problem? > 1. The table names look different. 2. Did you commit the changes? From python at mrabarnett.plus.com Sun Dec 13 13:40:09 2009 From: python at mrabarnett.plus.com (MRAB) Date: Sun, 13 Dec 2009 18:40:09 +0000 Subject: Manipulating MySQL Sets In-Reply-To: <4dc0cfea0912130940y7e365fc8s34c4cbfd8d95c28d@mail.gmail.com> References: <4dc0cfea0912121334gcf5af27l71a173c6a71f59d2@mail.gmail.com> <4dc0cfea0912121507u499aa5e3j3316f8bef425fef1@mail.gmail.com> <4dc0cfea0912121513y82451b9lbc31c6f54394a89f@mail.gmail.com> <4dc0cfea0912130748u186092ct952f2e582b81d932@mail.gmail.com> <4dc0cfea0912130846o3e111063g284e3de644ae6270@mail.gmail.com> <4dc0cfea0912130939u315046a0w892ee414d5324be2@mail.gmail.com> <4dc0cfea0912130940y7e365fc8s34c4cbfd8d95c28d@mail.gmail.com> Message-ID: <4B253509.1070205@mrabarnett.plus.com> Victor Subervi wrote: > On Sun, Dec 13, 2009 at 12:39 PM, Victor Subervi > > wrote: > > PS: I have another field that's a datetime with the same problem. How do > I parse and otherwise work with that? > Look at the documentation for the datetime class. From me at firecrow.com Sun Dec 13 13:48:11 2009 From: me at firecrow.com (Fire Crow) Date: Sun, 13 Dec 2009 10:48:11 -0800 (PST) Subject: insert unique data in a list References: <4b251840$0$30959$4fafbaef@reader3.news.tin.it> Message-ID: <5dbc7128-c04d-414a-9a9f-d4ab0a74d994@h2g2000vbd.googlegroups.com> On Dec 13, 11:37?am, mattia wrote: > How can I insert non-duplicate data in a list? I mean, is there a > particular option in the creation of a list that permit me not to use > something like: > def append_unique(l, val): > ? ? if val not in l: > ? ? ? ? l.append(val) > > Thanks, > Mattia You could also define a custom object that manages a custom ordered set class unique_set(object): def __init__(self,list): self.list = list def __add___(self,val): if val not in self.list self.list.append(val) return True return False >>> unique_list = unique_set(['a','b','c']) >>> unique_list.list ['a', 'b', 'c'] >>> unique_list + 'd' True >>> unique_list + 'e' True >>> unique_list + 'd' False >>> unique_list.list ['a', 'b', 'c', 'd', 'e'] >>> I've used this on a few projects, it makes for wonderfully clean code, because you can look at your program as an overview without all the arithmetic behind it. hope it helps From python at mrabarnett.plus.com Sun Dec 13 14:03:48 2009 From: python at mrabarnett.plus.com (MRAB) Date: Sun, 13 Dec 2009 19:03:48 +0000 Subject: Manipulating MySQL Sets In-Reply-To: <4dc0cfea0912131035p6f971968n5741c77e25f6f4b9@mail.gmail.com> References: <4dc0cfea0912121334gcf5af27l71a173c6a71f59d2@mail.gmail.com> <4dc0cfea0912121507u499aa5e3j3316f8bef425fef1@mail.gmail.com> <4dc0cfea0912121513y82451b9lbc31c6f54394a89f@mail.gmail.com> <4dc0cfea0912130748u186092ct952f2e582b81d932@mail.gmail.com> <4dc0cfea0912130846o3e111063g284e3de644ae6270@mail.gmail.com> <4dc0cfea0912130939u315046a0w892ee414d5324be2@mail.gmail.com> <4dc0cfea0912130940y7e365fc8s34c4cbfd8d95c28d@mail.gmail.com> <4dc0cfea0912131035p6f971968n5741c77e25f6f4b9@mail.gmail.com> Message-ID: <4B253A94.1040700@mrabarnett.plus.com> Victor Subervi wrote: > On Sun, Dec 13, 2009 at 12:40 PM, Victor Subervi > > wrote: > > On Sun, Dec 13, 2009 at 12:39 PM, Victor Subervi > > wrote: > > PS: I have another field that's a datetime with the same problem. > How do I parse and otherwise work with that? > > > I have yet another problem with this. Once I've determined it's a Set or > a datetime, I do this: > > for itm in colValue[0]: > try: > color, number = string.split(itm, ':') > html += "" % (itm, color) > except: > html += "" % (itm, itm) > > The reason is I've entered my colors into my table as > nameOfColor:colorNumber and I want to break them out for presentation > purposes. However, the try never executes, only the except, and that > shouldn't be. I can slice the itm. What gives? > 1. Print repr(itm) so that you can check what it actually is. Is it what you expected? 2. DON'T USE BARE EXCEPTS! From steve at REMOVE-THIS-cybersource.com.au Sun Dec 13 15:09:36 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 13 Dec 2009 20:09:36 GMT Subject: insert unique data in a list References: <4b251840$0$30959$4fafbaef@reader3.news.tin.it> <5dbc7128-c04d-414a-9a9f-d4ab0a74d994@h2g2000vbd.googlegroups.com> Message-ID: <00aecea0$0$15654$c3e8da3@news.astraweb.com> On Sun, 13 Dec 2009 10:48:11 -0800, Fire Crow wrote: > You could also define a custom object that manages a custom ordered set [...] > I've used this on a few projects, it makes for wonderfully clean code, > because you can look at your program as an overview without all the > arithmetic behind it. Which is all very good, but beware that your "ordered set" implementation is O(N) for insertions, which may be slow once the set grows large enough. Also, I'm not sure I like your abuse of the + operator to modify the object in place and return a flag. It is an API not shared by (as far as I can see) any other data type in Python. -- Steven From steve at REMOVE-THIS-cybersource.com.au Sun Dec 13 15:18:47 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 13 Dec 2009 20:18:47 GMT Subject: Dangerous behavior of list(generator) References: Message-ID: <00aed0c7$0$15654$c3e8da3@news.astraweb.com> On Sun, 13 Dec 2009 14:35:21 +0000, exarkun wrote: >>StopIteration is intended to be used only within the .__next__ method of >>iterators. The devs know that other 'off-label' use results in the >>inconsistency you noted, but their and my view is 'don't do that'. > > Which is unfortunate, because it's not that hard to get StopIteration > without explicitly raising it yourself and this behavior makes it > difficult to debug such situations. I can't think of any way to get StopIteration without explicitly raising it yourself. It's not like built-ins or common data structures routinely raise StopIteration. I don't think I've *ever* seen a StopIteration that I didn't raise myself. > What's with this view, exactly? Is it just that it's hard to implement > the more desirable behavior? What is that "more desirable behaviour"? That StopIteration is used to signal that Python should stop iterating except when you want it to be ignored? Unfortunately, yes, it's quite hard to implement "do what the caller actually wants, not what he asked for" behaviour -- and even if it were possible, it goes against the grain of the Zen of Python. If you've ever had to debug faulty "Do What I Mean" software, you'd see this as a good thing. -- Steven From aioe.org at technicalbloke.com Sun Dec 13 16:08:50 2009 From: aioe.org at technicalbloke.com (r0g) Date: Sun, 13 Dec 2009 21:08:50 +0000 Subject: Perl to Python conversion References: <87zl5rnayz.fsf@crunchbang.Belkin> <85pr6modkb.fsf@agentultra.com> <873a3imw5l.fsf@crunchbang.Belkin> Message-ID: Martin Sch??n wrote: > Thanks all, great response! > > A little more background: > > I am not a programmer but I have done some programming in the past. > This was all humble number crunching as part of my PhD project using > FORTRAN. I also did some Rocky Mountain Basic coding for programs > manipulating measurement instruments. And I did a minute amount > of Turbo Pascal code, too little and too many years ago to count. > > Since then I have done some stuff in Matlab and (very basic) UNIX > scripts. > > Does HTML, css and LaTeX count? > > So why Python? Well, I thought it would be fun to learn a little > about GUI programming and a friend who is a real programmer recommended > Python + PyQt. I have bought some books and lurked here for about > a year but haven't managed to get going yet. I figured I needed > some kind of project for that and now I have two. > > Learning Python and PyQt is spare time killer/brain teaser activity. > > The thermal contact conductance stuff is something that come in > handy at work. > > So here is what I plan to do based on your kind advice and some > thinking of my own. > > 1) I fix the unit thing by adding a conversion to the results > presentation routine. > > 2) Recreating the functionality of the program in Python and PyQt > will be a 'long term' educational project at home. There are > various bits and pieces there: data base handling, GUI design, math, > logic, error/exception handling... > > We have long, dark winters where I live :-) > > All the best, > > /Martin I'd recommend you start from scratch and refer to the perl version if and when you need to. You'll probably find the majority of code in a GUI app is boring window handling stuff rather, often this is machine generated (by progs like glade) rather than hand coded anyway so it will probably provide little insight. Also, they probably didn't make it with QT which is fairly different from GTK. It's like the housing industry, demolition + newbuild is almost always cheaper than renovation. If you can spare yourself the ordeal of learning perl and the chore of interpreting somebody else's perl then grasp it with both hands! Good luck. I'm sure you'll be fine - python is a deeply pleasing language to work in :) Roger. From davea at ieee.org Sun Dec 13 16:35:30 2009 From: davea at ieee.org (Dave Angel) Date: Sun, 13 Dec 2009 16:35:30 -0500 Subject: Manipulating MySQL Sets In-Reply-To: <4dc0cfea0912130939u315046a0w892ee414d5324be2@mail.gmail.com> References: <4dc0cfea0912121334gcf5af27l71a173c6a71f59d2@mail.gmail.com> <4dc0cfea0912121507u499aa5e3j3316f8bef425fef1@mail.gmail.com> <4dc0cfea0912121513y82451b9lbc31c6f54394a89f@mail.gmail.com> <4dc0cfea0912130748u186092ct952f2e582b81d932@mail.gmail.com> <4dc0cfea0912130846o3e111063g284e3de644ae6270@mail.gmail.com> <4dc0cfea0912130939u315046a0w892ee414d5324be2@mail.gmail.com> Message-ID: <4B255E22.6080201@ieee.org> Victor Subervi wrote: > On Sun, Dec 13, 2009 at 12:10 PM, Carsten Haese wrote: > > >> Victor Subervi wrote: >> >>> I need to get at the individual elements of the set (that which is >>> between the single quotes). >>> >> It's not quite clear what you mean by "get at the individual elements", >> so I'll just show you a couple of things you can do to a set, and maybe >> one of them comes close to what you need: >> >> >>>>> from sets import Set >>>>> aSet = Set(['Small', 'Extra-small', 'Medium']) >>>>> >> Do something for each element: >> >> >>>>> for element in aSet: >>>>> >> ... print element >> ... >> Small >> Extra-small >> Medium >> >> Convert the set to list: >> >> >>>>> list(aSet) >>>>> >> ['Small', 'Extra-small', 'Medium'] >> >> Test membership in the set: >> >> >>>>> 'Small' in aSet >>>>> >> True >> >>>>> 'Banana' in aSet >>>>> >> False >> >> Carsten, thank you (once again ;) for your patience. I didn't know I had to >> > import something. > Thanks again, > V > > Have you bothered to find the help file for your particular version of Python? In Windows, it's a .chm file, a compiled help file, but I'm sure the same information is available on other distributions.. Anyway, sets was a module introduced in Python 2.3, and deprecated in Python 2.6, where it's replaced by the built-in type set. So the answer of whether you need to import or not depends on what version you're running. In Python 2.5, it's (untested) import sets data = sets.Set(mylist) In Python 2.6 it's data = set(mylist) The name datetime is both a module and a class. import datetime #import the module obj = datetime.datetime() #use the class within the module you just imported You can find the same information online, at least for version 2.6: Sometimes I'll use google to find stuff specifically on python.org, typing the following at the google serarch prompt:: datetime site:python.org the first link in the results page is: http://docs.python.org/library/datetime.html which is the online version of the 2.6.4 help Other useful links for the 2.6.4 documentation: http://docs.python.org/modindex.html to search for modules http://docs.python.org/genindex.html to search for anything Each of these pages has a "quick search" option. For example, I found the following page: http://docs.python.org/library/stdtypes.html#set DaveA From victorsubervi at gmail.com Sun Dec 13 16:51:57 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Sun, 13 Dec 2009 16:51:57 -0500 Subject: Another MySQL Problem In-Reply-To: <4B25346A.7000805@mrabarnett.plus.com> References: <4dc0cfea0912131022n1f54985alc77a507c2ab7b0a2@mail.gmail.com> <4B25346A.7000805@mrabarnett.plus.com> Message-ID: <4dc0cfea0912131351q7cf6628crbf492935983d3953@mail.gmail.com> On Sun, Dec 13, 2009 at 1:37 PM, MRAB wrote: > 2. Did you commit the changes? > Ah, yes, caught me napping! db.commit() has bit me in the a$$ again. Thanks, V -------------- next part -------------- An HTML attachment was scrubbed... URL: From david at boddie.org.uk Sun Dec 13 17:10:52 2009 From: david at boddie.org.uk (David Boddie) Date: Sun, 13 Dec 2009 23:10:52 +0100 Subject: pyZui - anyone know about this? References: Message-ID: On Friday 11 December 2009 05:41, Donn wrote: > I happened upon this youtube link: > http://www.youtube.com/watch?v=57nWm984wdY > It fairly blew my socks off. In it a fellow by the name of David Roberts > demos a zui written in Python. Aside from the zooming (which is impressive > enough) it show embedding of images, pdf files, web pages and text. > > He says nothing about what toolkits were used or how it might have been > done. It's Linux-based, but no other info. On some googling, I can only > find a few bug reports on pypi related to pyQt. I would really like to > find out how that ZUI was done, it's simply amazing. > > Any clues out there? Doesn't the author give his e-mail address at the end of the video? (Maybe I'm thinking of a different video.) David From martin.schoon at gmail.com Sun Dec 13 17:23:04 2009 From: martin.schoon at gmail.com (Martin =?utf-8?B?U2Now7bDtm4=?=) Date: Sun, 13 Dec 2009 23:23:04 +0100 Subject: Perl to Python conversion References: <87zl5rnayz.fsf@crunchbang.Belkin> <85pr6modkb.fsf@agentultra.com> <873a3imw5l.fsf@crunchbang.Belkin> Message-ID: <874onused3.fsf@crunchbang.Belkin> r0g writes: > > I'd recommend you start from scratch and refer to the perl version if > and when you need to. That is my plan. > You'll probably find the majority of code in a GUI > app is boring window handling stuff rather, often this is machine > generated (by progs like glade) rather than hand coded anyway so it will > probably provide little insight. Also, they probably didn't make it with > QT which is fairly different from GTK. Tk is what they used. /Martin From exarkun at twistedmatrix.com Sun Dec 13 17:45:58 2009 From: exarkun at twistedmatrix.com (exarkun at twistedmatrix.com) Date: Sun, 13 Dec 2009 22:45:58 -0000 Subject: Dangerous behavior of list(generator) In-Reply-To: <00aed0c7$0$15654$c3e8da3@news.astraweb.com> References: <00aed0c7$0$15654$c3e8da3@news.astraweb.com> Message-ID: <20091213224558.2667.629746967.divmod.xquotient.15@localhost.localdomain> On 08:18 pm, steve at remove-this-cybersource.com.au wrote: >On Sun, 13 Dec 2009 14:35:21 +0000, exarkun wrote: >>>StopIteration is intended to be used only within the .__next__ method >>>of >>>iterators. The devs know that other 'off-label' use results in the >>>inconsistency you noted, but their and my view is 'don't do that'. >> >>Which is unfortunate, because it's not that hard to get StopIteration >>without explicitly raising it yourself and this behavior makes it >>difficult to debug such situations. > >I can't think of any way to get StopIteration without explicitly >raising >it yourself. It's not like built-ins or common data structures >routinely >raise StopIteration. I don't think I've *ever* seen a StopIteration >that >I didn't raise myself. Call next on an iterator. For example: iter(()).next() > >>What's with this view, exactly? Is it just that it's hard to >>implement >>the more desirable behavior? > >What is that "more desirable behaviour"? That StopIteration is used to >signal that Python should stop iterating except when you want it to be >ignored? Unfortunately, yes, it's quite hard to implement "do what the >caller actually wants, not what he asked for" behaviour -- and even if >it >were possible, it goes against the grain of the Zen of Python. > >If you've ever had to debug faulty "Do What I Mean" software, you'd see >this as a good thing. I have plenty of experience developing and debugging software, Steven. Your argument is specious, as it presupposes that only two possibilities exist: the current behavior of some kind of magical faerie land behavior. I'm surprised to hear you say that the magical faerie land behavior isn't desirable either, though. I'd love a tool that did what I wanted, not what I asked. The only serious argument against this, I think, is that it is beyond our current ability to create (and so anyone claiming to be able to do it is probably mistaken). You chopped out all the sections of this thread which discussed the more desirable behavior. You can go back and read them in earlier messages if you need to be reminded. I'm not talking about anything beyond what's already been raised. I'm pretty sure I know the answer to my question, though - it's hard to implement, so it's not implemented. Jean-Paul From rhodri at wildebst.demon.co.uk Sun Dec 13 17:56:04 2009 From: rhodri at wildebst.demon.co.uk (Rhodri James) Date: Sun, 13 Dec 2009 22:56:04 -0000 Subject: read text file byte by byte In-Reply-To: <00ae1204$0$15654$c3e8da3@news.astraweb.com> References: <4519638f-c62b-46f6-ba1e-619035d48036@j14g2000yqm.googlegroups.com> <00ae1204$0$15654$c3e8da3@news.astraweb.com> Message-ID: On Sun, 13 Dec 2009 06:44:54 -0000, Steven D'Aprano wrote: > On Sat, 12 Dec 2009 22:15:50 -0800, daved170 wrote: > >> Thank you all. >> Dennis I really liked you solution for the issue but I have two question >> about it: >> 1) My origin file is Text file and not binary > > That's a statement, not a question. > > >> 2) I need to read each time 1 byte. > > f = open(filename, 'r') # open in text mode > f.read(1) # read one byte The OP hasn't told us what version of Python he's using on what OS. On Windows, text mode will compress the end-of-line sequence into a single "\n". In Python 3.x, f.read(1) will read one character, which may be more than one byte depending on the encoding. If you really want bytes, opening the file in text mode will come back and by^Hite you eventually. -- Rhodri James *-* Wildebeest Herder to the Masses From debatem1 at gmail.com Sun Dec 13 18:04:36 2009 From: debatem1 at gmail.com (geremy condra) Date: Sun, 13 Dec 2009 18:04:36 -0500 Subject: insert unique data in a list In-Reply-To: <00aecea0$0$15654$c3e8da3@news.astraweb.com> References: <4b251840$0$30959$4fafbaef@reader3.news.tin.it> <5dbc7128-c04d-414a-9a9f-d4ab0a74d994@h2g2000vbd.googlegroups.com> <00aecea0$0$15654$c3e8da3@news.astraweb.com> Message-ID: On Sun, Dec 13, 2009 at 3:09 PM, Steven D'Aprano wrote: > On Sun, 13 Dec 2009 10:48:11 -0800, Fire Crow wrote: > >> You could also define a custom object that manages a custom ordered set > [...] >> I've used this on a few projects, it makes for wonderfully clean code, >> because you can look at your program as an overview without all the >> arithmetic behind it. > > Which is all very good, but beware that your "ordered set" implementation > is O(N) for insertions, which may be slow once the set grows large enough. > > Also, I'm not sure I like your abuse of the + operator to modify the > object in place and return a flag. It is an API not shared by (as far as > I can see) any other data type in Python. Could probably just abuse an odict as cleanly. The other option that leaps to mind is to use a bloom filter and a list. Geremy Condra From deets at nospam.web.de Sun Dec 13 19:10:16 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 14 Dec 2009 01:10:16 +0100 Subject: Moving from PHP to Python. Is it Possible In-Reply-To: References: <3c4778e3-e31a-4484-ae9a-f6d5b737fa68@x25g2000prf.googlegroups.com> Message-ID: <7ole38F3qetj5U1@mid.uni-berlin.de> >> 1) PHP does some really nasty things in how it treats globals, and you >> will have to break yourself of those sorts of habits -- Python offers >> much cleaner alternatives, like grouping similar functionality into >> modules which can be imported; the import functionality in python is >> pretty flexible. >> Python won't pack a ton of garbage into a giant, global >> 'dictionary' (what python calls associative arrays). There are >> modules (bundled of code) which you can import to handle your needs. > > PHP was doing tons of nasty things. 10 years after I'm starting to understand > some those and still not understand most programmers point of view to GLOBALS > are evil. Anyhow I'm self learner plus I got heavy English limitation or > probably I'm too narrow minded to see right thing. > > In my usage GLOBALS are too much useful to discard it. The problem with global variables is their scope. If you have a piece of code, the important thing to know is what influences it's behavior when being executed. Functional programs take this to the extreme and usually don't allow any global or otherwise shared state, so if you have a function that reads a = f(x) and you invoke it twice with the same value for x, you get the same result. But sometimes, you need state that is preserved over time. Object orientied design encapsulates this in objects. Each function (method) in a car-object shares the cars state. But *not* the state of *all* cars, which global variables would. Now when reading code, you have to juggle with all the state that influences it. The broader the scope (and global is the biggest one you can get) the harder it is to understand. And believe me, the longer a system exists and the older the code is you look at, the harder it is to understand what's happening. > > Anyway, I need to save my lots and lots of config variables in dictionary style > global accessible location. > > Because. > > In my design We got lots of plugins, and those plugins may show in multiple > times and multiple locations in a page. > > Each plugin may have setup values to affect entire page output. > > Because of this. I have to put those values in global location for future use. No, you don't. Because of this, you can e.g. use ToscaWidgets as a framework for creating widgets that encapsulate code, HTML, javascript and CSS. And no global state is shared. Also, I think you should *really* look into one of the available web-frameworks such as Django or Turbogears to learn how to write webapps in python - instead of shoehorning your tried & trusted PHP techniques that don't translate well. Diez From me at firecrow.com Sun Dec 13 19:49:27 2009 From: me at firecrow.com (Fire Crow) Date: Sun, 13 Dec 2009 16:49:27 -0800 (PST) Subject: insert unique data in a list References: <4b251840$0$30959$4fafbaef@reader3.news.tin.it> <5dbc7128-c04d-414a-9a9f-d4ab0a74d994@h2g2000vbd.googlegroups.com> <00aecea0$0$15654$c3e8da3@news.astraweb.com> Message-ID: <9a86427b-3b38-4aff-970d-479db730c74f@o9g2000vbj.googlegroups.com> > Also, I'm not sure I like your abuse of the + operator to modify the > object in place and return a flag. It is an API not shared by (as far as > I can see) any other data type in Python. I agree it couuld be more consisten with other object apis, I also think that if every api has to conform to every other api nothing will ever get done. Heres a slightly more familiar version, it returns the value added or none to conform with other APIs. class unique_set(object): def __init__(self,list): self.list = list def __add___(self,val): if val not in self.list self.list.append(val) return val return None >>> unique_list = unique_set(['a','b','c']) >>> unique_list.list ['a', 'b', 'c'] >>> unique_list + 'd' 'd' then a test opperand to verify if a value was inserted could be if unique_list + 'd': # done some stuff but it could also be used in cases like this unique_added = unique_list + 'd' or 'not added' From sancar.saran at evodot.com Sun Dec 13 20:04:08 2009 From: sancar.saran at evodot.com (Sancar Saran) Date: Mon, 14 Dec 2009 03:04:08 +0200 Subject: Moving from PHP to Python. Is it Possible In-Reply-To: <7ole38F3qetj5U1@mid.uni-berlin.de> References: <7ole38F3qetj5U1@mid.uni-berlin.de> Message-ID: <200912140304.08843.sancar.saran@evodot.com> On Monday 14 December 2009 02:10:16 am Diez B. Roggisch wrote: > >> 1) PHP does some really nasty things in how it treats globals, and you > >> will have to break yourself of those sorts of habits -- Python offers > >> much cleaner alternatives, like grouping similar functionality into > >> modules which can be imported; the import functionality in python is > >> pretty flexible. > >> Python won't pack a ton of garbage into a giant, global > >> 'dictionary' (what python calls associative arrays). There are > >> modules (bundled of code) which you can import to handle your needs. > > > > PHP was doing tons of nasty things. 10 years after I'm starting to > > understand some those and still not understand most programmers point of > > view to GLOBALS are evil. Anyhow I'm self learner plus I got heavy > > English limitation or probably I'm too narrow minded to see right thing. > > > > In my usage GLOBALS are too much useful to discard it. > > The problem with global variables is their scope. If you have a piece of > code, the important thing to know is what influences it's behavior when > being executed. Functional programs take this to the extreme and usually > don't allow any global or otherwise shared state, so if you have a > function that reads > > a = f(x) > > and you invoke it twice with the same value for x, you get the same result. > > But sometimes, you need state that is preserved over time. Object > orientied design encapsulates this in objects. Each function (method) in > a car-object shares the cars state. But *not* the state of *all* cars, > which global variables would. > > Now when reading code, you have to juggle with all the state that > influences it. The broader the scope (and global is the biggest one you > can get) the harder it is to understand. And believe me, the longer a > system exists and the older the code is you look at, the harder it is to > understand what's happening. Yes, I understood. And I'm using large Global dictionary (or Array) to replicate those objects. State of the thing will store in there. But it wasn't an object. Just Assocative array. Staying in global space, Because. In web programming we do not store anything except session. Every object we created was destroyed after execution. Using objects in this conditions was non sense to me. (of course I'm not very capable programmer probably it was my fault to take full advantage of oo programming) Plus. In php we can store arrays in files very easy. Combining this with any PHP opcode cache can save those arrays in memory. So we got damn cheap state saver. Of course things may differ in python. Anyhow I generate a Registry class to replicate global dictionary. Probably it much better than my PHP Direct $GLOBAL usage. So I have no problem with that. > > Anyway, I need to save my lots and lots of config variables in dictionary > > style global accessible location. > > > > Because. > > > > In my design We got lots of plugins, and those plugins may show in > > multiple times and multiple locations in a page. > > > > Each plugin may have setup values to affect entire page output. > > > > Because of this. I have to put those values in global location for future > > use. > > No, you don't. Because of this, you can e.g. use ToscaWidgets as a > framework for creating widgets that encapsulate code, HTML, javascript > and CSS. And no global state is shared. > > Also, I think you should *really* look into one of the available > web-frameworks such as Django or Turbogears to learn how to write > webapps in python - instead of shoehorning your tried & trusted PHP > techniques that don't translate well. > Yes I download the django trying to learn but it was much different. My problem is not writing web apps. I'm doing well. My design was very good and I'm very proud its abilities. My problem is with PHP syntax and performance. I'm just trying to replicate my recepies in python... > Diez > Regards Sancar From knifenomad at gmail.com Sun Dec 13 20:19:17 2009 From: knifenomad at gmail.com (knifenomad) Date: Sun, 13 Dec 2009 17:19:17 -0800 (PST) Subject: insert unique data in a list References: <4b251840$0$30959$4fafbaef@reader3.news.tin.it> <4b252b1b$0$644$4fafbaef@reader4.news.tin.it> Message-ID: On 12?14?, ??2?57?, mattia wrote: > Il Sun, 13 Dec 2009 16:37:20 +0000, mattia ha scritto: > > > How can I insert non-duplicate data in a list? I mean, is there a > > particular option in the creation of a list that permit me not to use > > something like: > > def append_unique(l, val): > > ? ? if val not in l: > > ? ? ? ? l.append(val) > > > Thanks, > > Mattia > > Ok, so you all suggest to use a set. Now the second question, more > interesting. Why can't I insert a list into a set? I mean, I have a > function that returns a list. I call this function several times and > maybe the list returned is the same as another one already returned. I > usually put all this lists into another list. How can I assure that my > list contains only unique lists? Using set does'n work (i.e. the python > interpreter tells me: TypeError: unhashable type: 'list')... this makes the set type hashable. class Set(set): __hash__ = lambda self: id(self) s = Set() s.add(1) s.add(2) s.add(1) print s set([1, 2]) d = {} d[s] = 'voila' print d {Set([1,2]):'voila'} print d[s] 'voila' From knifenomad at gmail.com Sun Dec 13 20:24:18 2009 From: knifenomad at gmail.com (knifenomad) Date: Sun, 13 Dec 2009 17:24:18 -0800 (PST) Subject: insert unique data in a list References: <4b251840$0$30959$4fafbaef@reader3.news.tin.it> <4b252b1b$0$644$4fafbaef@reader4.news.tin.it> Message-ID: On 12?14?, ??10?19?, knifenomad wrote: > On 12?14?, ??2?57?, mattia wrote: > > > > > > > Il Sun, 13 Dec 2009 16:37:20 +0000, mattia ha scritto: > > > > How can I insert non-duplicate data in a list? I mean, is there a > > > particular option in the creation of a list that permit me not to use > > > something like: > > > def append_unique(l, val): > > > ? ? if val not in l: > > > ? ? ? ? l.append(val) > > > > Thanks, > > > Mattia > > > Ok, so you all suggest to use a set. Now the second question, more > > interesting. Why can't I insert a list into a set? I mean, I have a > > function that returns a list. I call this function several times and > > maybe the list returned is the same as another one already returned. I > > usually put all this lists into another list. How can I assure that my > > list contains only unique lists? Using set does'n work (i.e. the python > > interpreter tells me: TypeError: unhashable type: 'list')... > > this makes the set type hashable. > > class Set(set): > ? ? __hash__ = lambda self: id(self) > > s = Set() > s.add(1) > s.add(2) > s.add(1) > > print s > set([1, 2]) > > d = {} > d[s] = 'voila' > > print d > {Set([1,2]):'voila'} > > print d[s] > 'voila'- ?? ??? ??? - > > - ?? ??? ?? - although it's not what you've asked about. it's intereting to make set hashable using __hash__. From technologiclee at gmail.com Sun Dec 13 20:24:50 2009 From: technologiclee at gmail.com (technologiclee) Date: Sun, 13 Dec 2009 17:24:50 -0800 (PST) Subject: Nanoengineer-1 Simulator References: <0fbf2e89-fe93-4110-944f-ad825a46e9c3@f16g2000yqm.googlegroups.com> Message-ID: <93e2b571-d924-48f5-b4dc-91c1c83e0c31@b2g2000yqi.googlegroups.com> On Dec 13, 12:34?am, technologiclee wrote: > This is from a thread started at the Open Manufacturing Group. > > It is about the Nanoengineer-1 molecular modeling program. > It is released under GPL license. I would like to know if this project > can be forked and continued - as development seems to have ceased, but > it is still the best software of its kind that I can find. All the > details are in the thread. > > http://groups.google.com/group/openmanufacturing/browse_thread/thread... > > Specifically, I would like to ask this community about an error trying > to use the simulator: > > This is the error from Netbeans when I try to run the simulator. Any > suggestions? > > error trying to import dylib sim: : No > module > named sim > ? [runSim.py:787] > sim parameters used by NE1 read from: > [/home/lee/nesuite1.1.12./cad/plugins/NanoDynamics-1/sim-params.txt] > bug in simulator-calling code: : > SimRunner > instance has no attribute 'system_parameters_file' > ? [runSim.py:372] [runSim.py:970] [runSim.py:1089] > exception opening trace file > '/home/lee/Nanorex/Untitled.2009-12-13-00-18-10-trace.txt': 'exceptions.IOError'>: [Errno 2] No such file or directory: > '/home/lee/Nanorex/Untitled.2009-12-13-00-18-10-trace.txt' > ? [runSim.py:1936] For the benefit of all those searching for this answer, I am adding this response to the post. Thanks Tim. (sorry for replying off-list - the email I use on-list email isn't sending at the moment - feel free to post any reply back on-list) On Sat, 2009-12-12 at 22:34 -0800, technologiclee wrote: > It is released under GPL license. I would like to know if this project > can be forked and continued - as development seems to have ceased, but > it is still the best software of its kind that I can find. All the > details are in the thread. Yes - as long as you release all your changes under GPL as well - that's the great thing about the GPL. > Specifically, I would like to ask this community about an error trying > to use the simulator: > > This is the error from Netbeans when I try to run the simulator. Any > suggestions? Looking at the code - the module "sim" is a C extension module - from the setup.py file in the NanoEngineer directory: {{{ extra_compile_args = [ "-DDISTUTILS", "-O" ] setup(name = 'Simulator', ext_modules=[Extension("sim", ["sim.pyx", ... }}} - so you'll need to build the setup.py to get that working. But... I get compile errors when trying to build that library % python setup.py build running build running build_ext building 'sim' extension creating build/temp.linux-x86_64-2.4 gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall - Wstrict-prototypes -fPIC -I/usr/include/python2.4 -c sim.c -o build/ temp.linux-x86_64-2.4/sim.o -DDISTUTILS -O In file included from sim.c:30: simhelp.c:30:21: error: version.h: No such file or directory In file included from sim.c:30: simhelp.c:39: error: ?TRACE_PREFIX? undeclared here (not in a function) simhelp.c:39: error: expected ?,? or ?;? before ?TRACE_PREFIX_DISTUTILS? error: command 'gcc' failed with exit status 1 - and at this point it's a general C issue to be honest TRACE_PREFIX seems to be added at some point during automake - i.e. you've got to run the full build tools for sim to be able to be built. - the other "trace file" errors seem to be related. Hope that helps, Tim From nobody at nowhere.com Sun Dec 13 20:44:46 2009 From: nobody at nowhere.com (Nobody) Date: Mon, 14 Dec 2009 01:44:46 +0000 Subject: Moving from PHP to Python. Is it Possible References: Message-ID: On Fri, 11 Dec 2009 12:26:30 +0200, Sancar Saran wrote: > 1-) Can I create Global (read/write access anywhere from my code) Multi > dimensional, associative array (or hash) and store any kind of variable type. Global, no; at least not in the sense of e.g. C. Python doesn't have a global namespace; the highest level is a module. Read/write from anywhere in your code, yes. You just need to decide which module to put the variable in, then import that module (or even the specific variable) from the other modules. E.g. you can have a file state.py containing nothing but: state = {} Other modules can then use: from state import state to make the variable visible. From clp2 at rebertia.com Sun Dec 13 20:47:45 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 13 Dec 2009 17:47:45 -0800 Subject: insert unique data in a list In-Reply-To: References: <4b251840$0$30959$4fafbaef@reader3.news.tin.it> <4b252b1b$0$644$4fafbaef@reader4.news.tin.it> Message-ID: <50697b2c0912131747w14940bdv956f60658fce7da1@mail.gmail.com> On Sun, Dec 13, 2009 at 5:19 PM, knifenomad wrote: > On 12?14?, ??2?57?, mattia wrote: >> Il Sun, 13 Dec 2009 16:37:20 +0000, mattia ha scritto: >> > How can I insert non-duplicate data in a list? I mean, is there a >> > particular option in the creation of a list that permit me not to use >> > something like: >> > def append_unique(l, val): >> > ? ? if val not in l: >> > ? ? ? ? l.append(val) >> >> Ok, so you all suggest to use a set. Now the second question, more >> interesting. Why can't I insert a list into a set? I mean, I have a >> function that returns a list. I call this function several times and >> maybe the list returned is the same as another one already returned. I >> usually put all this lists into another list. How can I assure that my >> list contains only unique lists? Using set does'n work (i.e. the python >> interpreter tells me: TypeError: unhashable type: 'list')... > > this makes the set type hashable. > > class Set(set): > ? ?__hash__ = lambda self: id(self) Or you could just use frozenset and get the correct semantics: http://docs.python.org/library/stdtypes.html#frozenset Cheers, Chris -- http://blog.rebertia.com From lie.1296 at gmail.com Sun Dec 13 21:06:56 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Mon, 14 Dec 2009 13:06:56 +1100 Subject: insert unique data in a list In-Reply-To: <9a86427b-3b38-4aff-970d-479db730c74f@o9g2000vbj.googlegroups.com> References: <4b251840$0$30959$4fafbaef@reader3.news.tin.it> <5dbc7128-c04d-414a-9a9f-d4ab0a74d994@h2g2000vbd.googlegroups.com> <00aecea0$0$15654$c3e8da3@news.astraweb.com> <9a86427b-3b38-4aff-970d-479db730c74f@o9g2000vbj.googlegroups.com> Message-ID: <4b259dc9$1@dnews.tpgi.com.au> On 12/14/2009 11:49 AM, Fire Crow wrote: > I also think that if every api has to conform to every other api > nothing will ever get done. but if every object has its own distinct API, we will never finish reading the docs (assuming they do exist for each object). From steve at holdenweb.com Sun Dec 13 21:11:47 2009 From: steve at holdenweb.com (Steve Holden) Date: Sun, 13 Dec 2009 21:11:47 -0500 Subject: Introduction to Python: Change of Dates Message-ID: Please note that the dates of our upcoming "Introduction to Python" three-day class have been changed to avoid the federal holiday on Martin Luther King Day. The class will now run from January 19-21. Details at http://hwebpyintnyc01.eventbrite.com/ regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ UPCOMING EVENTS: http://holdenweb.eventbrite.com/ From lie.1296 at gmail.com Sun Dec 13 21:26:31 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Mon, 14 Dec 2009 13:26:31 +1100 Subject: Moving from PHP to Python. Is it Possible In-Reply-To: References: <7ole38F3qetj5U1@mid.uni-berlin.de> Message-ID: <4b25a262@dnews.tpgi.com.au> On 12/14/2009 12:04 PM, Sancar Saran wrote: > On Monday 14 December 2009 02:10:16 am Diez B. Roggisch wrote: >>> In my usage GLOBALS are too much useful to discard it. >> >> The problem with global variables is their scope. If you have a piece of >> code, the important thing to know is what influences it's behavior when >> being executed. Functional programs take this to the extreme and usually >> don't allow any global or otherwise shared state, so if you have a >> function that reads >> >> a = f(x) >> >> and you invoke it twice with the same value for x, you get the same result. >> >> But sometimes, you need state that is preserved over time. Object >> orientied design encapsulates this in objects. Each function (method) in >> a car-object shares the cars state. But *not* the state of *all* cars, >> which global variables would. >> >> Now when reading code, you have to juggle with all the state that >> influences it. The broader the scope (and global is the biggest one you >> can get) the harder it is to understand. And believe me, the longer a >> system exists and the older the code is you look at, the harder it is to >> understand what's happening. > > Yes, I understood. And I'm using large Global dictionary (or Array) to > replicate those objects. State of the thing will store in there. But it > wasn't an object. Just Assocative array. Staying in global space, In python, objects is just syntax sugar for dict/associative array. In even lower languages (like C++), object is just syntax sugar for a malloc-ated block of memory. Object-oriented is designed to eliminate the need for having a God Data Structure such as Global Associative Array that stores practically everything. > Because. > > In web programming we do not store anything except session. Every object we > created was destroyed after execution. Using objects in this conditions was > non sense to me. (of course I'm not very capable programmer probably it was my > fault to take full advantage of oo programming) Why is it nonsense? You can create an object that stores the session id, and the object's methods would query the database without you have to explicitly mention the session id each time. That's cheap and is very neat in organizational standpoint. > Plus. In php we can store arrays in files very easy. Combining this with any > PHP opcode cache can save those arrays in memory. So we got damn cheap state > saver. > > Of course things may differ in python. Things differ, but not by that much. From lie.1296 at gmail.com Sun Dec 13 21:50:10 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Mon, 14 Dec 2009 13:50:10 +1100 Subject: Dangerous behavior of list(generator) In-Reply-To: References: <00aed0c7$0$15654$c3e8da3@news.astraweb.com> Message-ID: <4b25a7ec$1@dnews.tpgi.com.au> On 12/14/2009 9:45 AM, exarkun at twistedmatrix.com wrote: > On 08:18 pm, steve at remove-this-cybersource.com.au wrote: >> On Sun, 13 Dec 2009 14:35:21 +0000, exarkun wrote: >>>> StopIteration is intended to be used only within the .__next__ >>>> method of >>>> iterators. The devs know that other 'off-label' use results in the >>>> inconsistency you noted, but their and my view is 'don't do that'. >>> >>> Which is unfortunate, because it's not that hard to get StopIteration >>> without explicitly raising it yourself and this behavior makes it >>> difficult to debug such situations. >> >> I can't think of any way to get StopIteration without explicitly raising >> it yourself. It's not like built-ins or common data structures routinely >> raise StopIteration. I don't think I've *ever* seen a StopIteration that >> I didn't raise myself. > > Call next on an iterator. For example: iter(()).next() .next() is not meant to be called directly, that's why it's renamed to .__next__() in python 3. Just like .__add__() is never meant to be called directly since you'll then have to handle NotImplemented. If you really need to call .__next__() you will call next() builtin function instead which has a second argument to return a sentinel value instead of StopIteration. IMNSHO next()'s sentinel should always be specified except if you're implementing __next__() or if the sequence is an infinite iterator. >>> What's with this view, exactly? Is it just that it's hard to implement >>> the more desirable behavior? >> >> What is that "more desirable behaviour"? That StopIteration is used to >> signal that Python should stop iterating except when you want it to be >> ignored? Unfortunately, yes, it's quite hard to implement "do what the >> caller actually wants, not what he asked for" behaviour -- and even if it >> were possible, it goes against the grain of the Zen of Python. >> >> If you've ever had to debug faulty "Do What I Mean" software, you'd see >> this as a good thing. > > I have plenty of experience developing and debugging software, Steven. > Your argument is specious, as it presupposes that only two possibilities > exist: the current behavior of some kind of magical faerie land behavior. > > I'm surprised to hear you say that the magical faerie land behavior > isn't desirable either, though. I'd love a tool that did what I wanted, > not what I asked. The only serious argument against this, I think, is > that it is beyond our current ability to create (and so anyone claiming > to be able to do it is probably mistaken). In your world, this is what happens: >>> list = [a, b, c] >>> # print list >>> print list ["a", "b", "c"] >>> # make a copy of list >>> alist = list(llst) # oops a mistype >>> alist = alist - "]" + ", "d"]" >>> print alist ["a", "b", "c", "d"] >>> alist[:6] + "i", + alist[6:] >>> print alist ["a", "i", "b", "c", "d"] >>> print alist >>> # hearing the sound of my deskjet printer... >>> C:\fikle.text.write(alist) >>> print open("C:\file.txt").read()

a

  • i
  • b
  • c d
  • >>> # great, exactly what I needed > You chopped out all the sections of this thread which discussed the more > desirable behavior. You can go back and read them in earlier messages if > you need to be reminded. I'm not talking about anything beyond what's > already been raised. > > I'm pretty sure I know the answer to my question, though - it's hard to > implement, so it's not implemented. > > Jean-Paul From nobody at nowhere.com Sun Dec 13 21:55:44 2009 From: nobody at nowhere.com (Nobody) Date: Mon, 14 Dec 2009 02:55:44 +0000 Subject: read text file byte by byte References: <4519638f-c62b-46f6-ba1e-619035d48036@j14g2000yqm.googlegroups.com> Message-ID: On Sun, 13 Dec 2009 12:39:26 -0800, Dennis Lee Bieber wrote: > You originally stated that you want to "scramble" the bytes -- if > you mean to implement some sort of encryption algorithm you should know > that most of them work in blocks as the "key" is longer than one byte. Block ciphers work in blocks. Stream ciphers work on bytes, regardless of the length of the key. From python at mrabarnett.plus.com Sun Dec 13 22:14:11 2009 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 14 Dec 2009 03:14:11 +0000 Subject: read text file byte by byte In-Reply-To: References: <4519638f-c62b-46f6-ba1e-619035d48036@j14g2000yqm.googlegroups.com> Message-ID: <4B25AD83.5020407@mrabarnett.plus.com> Nobody wrote: > On Sun, 13 Dec 2009 12:39:26 -0800, Dennis Lee Bieber wrote: > >> You originally stated that you want to "scramble" the bytes -- if >> you mean to implement some sort of encryption algorithm you should know >> that most of them work in blocks as the "key" is longer than one byte. > > Block ciphers work in blocks. Stream ciphers work on bytes, regardless of > the length of the key. > It's still more efficient to read in blocks, even if you're going to process the bytes one at a time. From exarkun at twistedmatrix.com Sun Dec 13 22:29:38 2009 From: exarkun at twistedmatrix.com (exarkun at twistedmatrix.com) Date: Mon, 14 Dec 2009 03:29:38 -0000 Subject: Dangerous behavior of list(generator) In-Reply-To: <4b25a7ec$1@dnews.tpgi.com.au> References: <00aed0c7$0$15654$c3e8da3@news.astraweb.com> <4b25a7ec$1@dnews.tpgi.com.au> Message-ID: <20091214032938.2667.483968939.divmod.xquotient.25@localhost.localdomain> On 02:50 am, lie.1296 at gmail.com wrote: >On 12/14/2009 9:45 AM, exarkun at twistedmatrix.com wrote: >>On 08:18 pm, steve at remove-this-cybersource.com.au wrote: >>>On Sun, 13 Dec 2009 14:35:21 +0000, exarkun wrote: >>>>>StopIteration is intended to be used only within the .__next__ >>>>>method of >>>>>iterators. The devs know that other 'off-label' use results in the >>>>>inconsistency you noted, but their and my view is 'don't do that'. >>>> >>>>Which is unfortunate, because it's not that hard to get >>>>StopIteration >>>>without explicitly raising it yourself and this behavior makes it >>>>difficult to debug such situations. >>> >>>I can't think of any way to get StopIteration without explicitly >>>raising >>>it yourself. It's not like built-ins or common data structures >>>routinely >>>raise StopIteration. I don't think I've *ever* seen a StopIteration >>>that >>>I didn't raise myself. >> >>Call next on an iterator. For example: iter(()).next() > >.next() is not meant to be called directly Doesn't matter. Sometimes it makes sense to call it directly. And I was just giving an example of a way to get StopIteration raised without doing it yourself - which is what Steve said he couldn't think of. >> >>I'm surprised to hear you say that the magical faerie land behavior >>isn't desirable either, though. I'd love a tool that did what I >>wanted, >>not what I asked. The only serious argument against this, I think, is >>that it is beyond our current ability to create (and so anyone >>claiming >>to be able to do it is probably mistaken). > >In your world, this is what happens: > >>> list = [a, b, c] > >>> # print list > >>> print list >["a", "b", "c"] > >>> # make a copy of list > >>> alist = list(llst) # oops a mistype > >>> alist = alist - "]" + ", "d"]" > >>> print alist >["a", "b", "c", "d"] > >>> alist[:6] + "i", + alist[6:] > >>> print alist >["a", "i", "b", "c", "d"] > >>> print alist > >>> # hearing the sound of my deskjet printer... > >>> C:\fikle.text.write(alist) > >>> print open("C:\file.txt").read() >

    a

    >
      >
    • i
    • >
    • b
    • >
    • c d
    • > >>> # great, exactly what I needed I don't understand the point of this code listing, sorry. I suspect you didn't completely understand the magical faerie land I was describing - where all your programs would work, no matter what mistakes you made while writing them. Jean-Paul From timr at probo.com Sun Dec 13 22:37:40 2009 From: timr at probo.com (Tim Roberts) Date: Sun, 13 Dec 2009 19:37:40 -0800 Subject: power of explicit self? References: <73d81fbc-95c5-4897-bca1-852471eb7938@q16g2000vbc.googlegroups.com> <0e1c9da1-a8e7-486e-aa28-341ef2c8d1bf@2g2000prl.googlegroups.com> Message-ID: Fire Crow wrote: >> It's not implemented in the compiler. There's a place in the runtime >> for invoking a method where the object is inserted at the beginning >> of the parameter list. IIRC, that's done by wrapping the function >> object. > >This is the source of Objects/methodobject.c it look like this is >where self is added to the argument list, but I'll have to do some >more digging. Well, that's where the owning object is added, but that would be required whether "self" were implicit or explicit. C++ would have the same kind of code to push "this", for example, even though "this" is not shown in the parameter list. I agree with the other repliers. "Explicit" self is not "implemented" anywhere. It's just an implementation decision. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From steven at REMOVE.THIS.cybersource.com.au Sun Dec 13 22:42:26 2009 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 14 Dec 2009 03:42:26 GMT Subject: insert unique data in a list References: <4b251840$0$30959$4fafbaef@reader3.news.tin.it> <4b252b1b$0$644$4fafbaef@reader4.news.tin.it> Message-ID: On Sun, 13 Dec 2009 17:19:17 -0800, knifenomad wrote: > this makes the set type hashable. > > class Set(set): > __hash__ = lambda self: id(self) That's a *seriously* broken hash function. >>> key = "voila" >>> d = { Set(key): 1 } >>> d {Set(['i', 'a', 'l', 'o', 'v']): 1} >>> d[ Set(key) ] Traceback (most recent call last): File "", line 1, in KeyError: Set(['i', 'a', 'l', 'o', 'v']) -- Steven From steven at REMOVE.THIS.cybersource.com.au Sun Dec 13 23:11:28 2009 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 14 Dec 2009 04:11:28 GMT Subject: Dangerous behavior of list(generator) References: <00aed0c7$0$15654$c3e8da3@news.astraweb.com> Message-ID: On Sun, 13 Dec 2009 22:45:58 +0000, exarkun wrote: > On 08:18 pm, steve at remove-this-cybersource.com.au wrote: >>On Sun, 13 Dec 2009 14:35:21 +0000, exarkun wrote: >>>>StopIteration is intended to be used only within the .__next__ method >>>>of >>>>iterators. The devs know that other 'off-label' use results in the >>>>inconsistency you noted, but their and my view is 'don't do that'. >>> >>>Which is unfortunate, because it's not that hard to get StopIteration >>>without explicitly raising it yourself and this behavior makes it >>>difficult to debug such situations. >> >>I can't think of any way to get StopIteration without explicitly raising >>it yourself. It's not like built-ins or common data structures routinely >>raise StopIteration. I don't think I've *ever* seen a StopIteration that >>I didn't raise myself. > > Call next on an iterator. For example: iter(()).next() Or in more recent versions of Python, next(iter(())). Good example. But next() is a special case, and since next() is documented as raising StopIteration if you call it and it raises StopIteration, you have raised it yourself. Just not explicitly. >>>What's with this view, exactly? Is it just that it's hard to implement >>>the more desirable behavior? >> >>What is that "more desirable behaviour"? That StopIteration is used to >>signal that Python should stop iterating except when you want it to be >>ignored? Unfortunately, yes, it's quite hard to implement "do what the >>caller actually wants, not what he asked for" behaviour -- and even if >>it were possible, it goes against the grain of the Zen of Python. >> >>If you've ever had to debug faulty "Do What I Mean" software, you'd see >>this as a good thing. > > I have plenty of experience developing and debugging software, Steven. > Your argument is specious, as it presupposes that only two possibilities > exist: the current behavior of some kind of magical faerie land > behavior. > > I'm surprised to hear you say that the magical faerie land behavior > isn't desirable either, though. I'd love a tool that did what I wanted, > not what I asked. The only serious argument against this, I think, is > that it is beyond our current ability to create (and so anyone claiming > to be able to do it is probably mistaken). I'd argue that tools that do what you want rather than what you ask for are not just currently impossible, but always will be -- no matter how good the state of the art of artificial intelligent mind-reading software becomes. > You chopped out all the sections of this thread which discussed the more > desirable behavior. You can go back and read them in earlier messages > if you need to be reminded. I'm not talking about anything beyond > what's already been raised. I'm glad for you. But would you mind explaining for those of us aren't mind-readers what YOU consider the "more desirable behaviour"? If you're talking the list constructor and list comprehensions treating StopIteration the same, then I don't think it is at all self-evident that the current behaviour is a bad thing, nor that the only reason for it is that to do otherwise would be hard. (I don't think it would be hard to have list comps swallow a StopIteration.) > I'm pretty sure I know the answer to my question, though - it's hard to > implement, so it's not implemented. > > Jean-Paul -- Steven From exarkun at twistedmatrix.com Sun Dec 13 23:33:04 2009 From: exarkun at twistedmatrix.com (exarkun at twistedmatrix.com) Date: Mon, 14 Dec 2009 04:33:04 -0000 Subject: Dangerous behavior of list(generator) In-Reply-To: References: <00aed0c7$0$15654$c3e8da3@news.astraweb.com> Message-ID: <20091214043304.2667.732037162.divmod.xquotient.91@localhost.localdomain> On 04:11 am, steven at remove.this.cybersource.com.au wrote: >On Sun, 13 Dec 2009 22:45:58 +0000, exarkun wrote: >>On 08:18 pm, steve at remove-this-cybersource.com.au wrote: >>>On Sun, 13 Dec 2009 14:35:21 +0000, exarkun wrote: >>>>>StopIteration is intended to be used only within the .__next__ >>>>>method >>>>>of >>>>>iterators. The devs know that other 'off-label' use results in the >>>>>inconsistency you noted, but their and my view is 'don't do that'. >>>> >>>>Which is unfortunate, because it's not that hard to get >>>>StopIteration >>>>without explicitly raising it yourself and this behavior makes it >>>>difficult to debug such situations. >>> >>>I can't think of any way to get StopIteration without explicitly >>>raising >>>it yourself. It's not like built-ins or common data structures >>>routinely >>>raise StopIteration. I don't think I've *ever* seen a StopIteration >>>that >>>I didn't raise myself. >> >>Call next on an iterator. For example: iter(()).next() > >Or in more recent versions of Python, next(iter(())). > >Good example. But next() is a special case, and since next() is >documented as raising StopIteration if you call it and it raises >StopIteration, you have raised it yourself. Just not explicitly. But if you mistakenly don't catch it, and you're trying to debug your code to find this mistake, you probably won't be aided in this pursuit by the exception-swallowing behavior of generator expressions. > >>>>What's with this view, exactly? Is it just that it's hard to >>>>implement >>>>the more desirable behavior? >>> >>>What is that "more desirable behaviour"? That StopIteration is used >>>to >>>signal that Python should stop iterating except when you want it to >>>be >>>ignored? Unfortunately, yes, it's quite hard to implement "do what >>>the >>>caller actually wants, not what he asked for" behaviour -- and even >>>if >>>it were possible, it goes against the grain of the Zen of Python. >>> >>>If you've ever had to debug faulty "Do What I Mean" software, you'd >>>see >>>this as a good thing. >> >>I have plenty of experience developing and debugging software, Steven. >>Your argument is specious, as it presupposes that only two >>possibilities >>exist: the current behavior of some kind of magical faerie land >>behavior. >> >>I'm surprised to hear you say that the magical faerie land behavior >>isn't desirable either, though. I'd love a tool that did what I >>wanted, >>not what I asked. The only serious argument against this, I think, is >>that it is beyond our current ability to create (and so anyone >>claiming >>to be able to do it is probably mistaken). > >I'd argue that tools that do what you want rather than what you ask for >are not just currently impossible, but always will be -- no matter how >good the state of the art of artificial intelligent mind-reading >software >becomes. That may be true. I won't try to make any predictions about the arbitrarily distant future, though. >>You chopped out all the sections of this thread which discussed the >>more >>desirable behavior. You can go back and read them in earlier messages >>if you need to be reminded. I'm not talking about anything beyond >>what's already been raised. > >I'm glad for you. But would you mind explaining for those of us aren't >mind-readers what YOU consider the "more desirable behaviour"? The behavior of list comprehensions is pretty good. The behavior of constructing a list out of a generator expression isn't as good. The behavior which is more desirable is for a StopIteration raised out of the `expression` part of a `generator_expression` to not be treated identically to the way a StopIteration raised out of the `genexpr_for` part is. This could provide behavior roughly equivalent to the behavior of a list comprehension. > >If you're talking the list constructor and list comprehensions treating >StopIteration the same, then I don't think it is at all self-evident >that >the current behaviour is a bad thing, nor that the only reason for it >is >that to do otherwise would be hard. I don't expect it to be self-evident. I wasn't even trying to convince anyone that it's desirable (although I did claim it, so I won't fault anyone for making counter-arguments). The only thing I asked was what the motivation for the current behavior is. If the motivation is that it is self-evident that the current behavior is the best possible behavior, then someone just needs to say that and my question is answered. :) Jean-Paul From knifenomad at gmail.com Mon Dec 14 00:17:28 2009 From: knifenomad at gmail.com (knifenomad) Date: Sun, 13 Dec 2009 21:17:28 -0800 (PST) Subject: insert unique data in a list References: <4b251840$0$30959$4fafbaef@reader3.news.tin.it> <4b252b1b$0$644$4fafbaef@reader4.news.tin.it> Message-ID: <07c342ef-fd02-4d6e-ab23-6effdd0598fc@b36g2000prf.googlegroups.com> On 12?14?, ??12?42?, Steven D'Aprano wrote: > On Sun, 13 Dec 2009 17:19:17 -0800, knifenomad wrote: > > this makes the set type hashable. > > > class Set(set): > > ? ? __hash__ = lambda self: id(self) > > That's a *seriously* broken hash function. > > >>> key = "voila" > >>> d = { Set(key): 1 } > >>> d > > {Set(['i', 'a', 'l', 'o', 'v']): 1}>>> d[ Set(key) ] > > Traceback (most recent call last): > ? File "", line 1, in > KeyError: Set(['i', 'a', 'l', 'o', 'v']) > > -- > Steven of course it is broken as long as it uses it's instance id. i added this to notify that unhashable can become hashable implementing __hash__ inside the class. which probably set to None by default. From tjreedy at udel.edu Mon Dec 14 01:46:52 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 14 Dec 2009 01:46:52 -0500 Subject: Dangerous behavior of list(generator) In-Reply-To: <20091214032938.2667.483968939.divmod.xquotient.25@localhost.localdomain> References: <00aed0c7$0$15654$c3e8da3@news.astraweb.com> <4b25a7ec$1@dnews.tpgi.com.au> <20091214032938.2667.483968939.divmod.xquotient.25@localhost.localdomain> Message-ID: On 12/13/2009 10:29 PM, exarkun at twistedmatrix.com wrote: > Doesn't matter. Sometimes it makes sense to call it directly. It only makes sense to call next (or .__next__) when you are prepared to explicitly catch StopIteration within a try..except construct. You did not catch it, so it stopped execution. Let me repeat: StopIteration is intended only for stopping iteration. Outside that use, it is a normal exception with no special meaning. Terry Jan Reedy From sjdevnull at yahoo.com Mon Dec 14 01:56:55 2009 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: Sun, 13 Dec 2009 22:56:55 -0800 (PST) Subject: read text file byte by byte References: <4519638f-c62b-46f6-ba1e-619035d48036@j14g2000yqm.googlegroups.com> <00ae1204$0$15654$c3e8da3@news.astraweb.com> Message-ID: On Dec 13, 5:56?pm, "Rhodri James" wrote: > On Sun, 13 Dec 2009 06:44:54 -0000, Steven D'Aprano ? > > wrote: > > On Sat, 12 Dec 2009 22:15:50 -0800, daved170 wrote: > > >> Thank you all. > >> Dennis I really liked you solution for the issue but I have two question > >> about it: > >> 1) My origin file is Text file and not binary > > > That's a statement, not a question. > > >> 2) I need to read each time 1 byte. > > > f = open(filename, 'r') ?# open in text mode > > f.read(1) ?# read one byte > > The OP hasn't told us what version of Python he's using on what OS. ?On ? > Windows, text mode will compress the end-of-line sequence into a single ? > "\n". ?In Python 3.x, f.read(1) will read one character, which may be more ? > than one byte depending on the encoding. The 3.1 documentation specifies that file.read returns bytes: file.read([size]) Read at most size bytes from the file (less if the read hits EOF before obtaining size bytes). If the size argument is negative or omitted, read all data until EOF is reached. The bytes are returned as a string object. An empty string is returned when EOF is encountered immediately. (For certain files, like ttys, it makes sense to continue reading after an EOF is hit.) Note that this method may call the underlying C function fread() more than once in an effort to acquire as close to size bytes as possible. Also note that when in non- blocking mode, less data than was requested may be returned, even if no size parameter was given. Does it need fixing? From jspies at sun.ac.za Mon Dec 14 01:58:34 2009 From: jspies at sun.ac.za (Johann Spies) Date: Mon, 14 Dec 2009 08:58:34 +0200 Subject: Parsing html with Beautifulsoup In-Reply-To: References: <20091210091519.GA14175@sun.ac.za> <4B21EF06.1040505@sun.ac.za> Message-ID: <20091214065834.GA18269@sun.ac.za> On Sun, Dec 13, 2009 at 07:58:55AM -0300, Gabriel Genellina wrote: > this code should serve as a starting point: Thank you very much! > cell.findAll(text=True) returns a list of all text nodes inside a > cell; I preprocess all \n and   in each text node, and > join them all. lines is a list of lists (each entry one cell), as > expected by the csv module used to write the output file. I have struggled a bit to find the documentation for (text=True). Most of documentation for Beautifulsoup I saw mostly contained some examples without explaining what the options do. Thanks for your explanation. As far as I can see there was no documentation installed with the debian package. Regards Johann -- Johann Spies Telefoon: 021-808 4599 Informasietegnologie, Universiteit van Stellenbosch "But I will hope continually, and will yet praise thee more and more." Psalms 71:14 From tjreedy at udel.edu Mon Dec 14 02:08:08 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 14 Dec 2009 02:08:08 -0500 Subject: Dangerous behavior of list(generator) In-Reply-To: <20091214043304.2667.732037162.divmod.xquotient.91@localhost.localdomain> References: <00aed0c7$0$15654$c3e8da3@news.astraweb.com> <20091214043304.2667.732037162.divmod.xquotient.91@localhost.localdomain> Message-ID: On 12/13/2009 11:33 PM, exarkun at twistedmatrix.com wrote: > But if you mistakenly don't catch it, and you're trying to debug your > code to find this mistake, you probably won't be aided in this pursuit > by the exception-swallowing behavior of generator expressions. As I remember, it was the call to list that swalled the exception, not the generator expression. List() takes an iterable as arg and stopping on StopIteration is what it does and how it knows to stop and return the new list. > The behavior of list comprehensions is pretty good. The behavior of > constructing a list out of a generator expression isn't as good. I think you are confused. A generator expression is a shorthand for a def statement that defines a generator function followed by a call to the generator function to get a generator followed by deletion of the function. When you call list() to make a list, it constructs the list from the generator, not from the expression itself. List has no idea that you used a generator expression or even that it was passed a generator. Leaving error checks out, it operates something like def list(it): res = [] it = iter(it) for item in it: # stops whenever it raises StopIteration res.append(item) return res > The > behavior which is more desirable is for a StopIteration raised out of > the `expression` part of a `generator_expression` to not be treated > identically to the way a StopIteration raised out of the `genexpr_for` > part is. It is not. StopIteration in for part stops the for loop in the generator. StopIteration in the expression part stops the loop in the list() call (sooner than it would have been otherwise). When the generator raises StopIteration, list() has no idea what statement within the body raised it. It MUST stop. > This could provide behavior roughly equivalent to the behavior > of a list comprehension. Impossible. The only serious option for consistency is to special case list comps to also trap StopIteration raised in the expression part, but the devs decided not to do this as doing do is arguably a bug. Terry Jan Reedy From alfps at start.no Mon Dec 14 02:23:00 2009 From: alfps at start.no (Alf P. Steinbach) Date: Mon, 14 Dec 2009 08:23:00 +0100 Subject: More stuff added to ch 2 of my programming intro In-Reply-To: References: Message-ID: * Alf P. Steinbach: > Format: PDF > > > The new stuff, section 2.7, is about programs as simulations and > handling data, focusing on modeling things. It includes some Python GUI > programming. The plan is to discuss containers like lists and > dictionaries in perhaps two more subsections of 2.7, but I'm not quite > sure about how to approach that or exactly how much to cover, since the > intent of ch 2 is to introduce mostly general concepts and enable the > reader to try out (more or less) interesting things. > > > Cheers, > > - Alf > > PS: comments welcome! Well, I posted the current doc. It has a not yet quite complete section 2.7.7 about arrays, and that will be the last subsection of the chapter. I thought using the Josephus circle problem as example was pretty neat... :-) But anyway, comments welcome, even if that last section's not yet finished. Cheers, - Alf PS: Oh, I changed the manuscript title to "Intelligent Person's Intro to Programming" -- is that good? From bruno.42.desthuilliers at websiteburo.invalid Mon Dec 14 04:14:18 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 14 Dec 2009 10:14:18 +0100 Subject: power of explicit self? In-Reply-To: <73d81fbc-95c5-4897-bca1-852471eb7938@q16g2000vbc.googlegroups.com> References: <73d81fbc-95c5-4897-bca1-852471eb7938@q16g2000vbc.googlegroups.com> Message-ID: <4b2601ea$0$30660$426a34cc@news.free.fr> Fire Crow a ?crit : > I'm looking for an explanation of how explicit self is implimented It's not "implemented" - it's just the first argument of the function, and you have to declare it explicitely in the function's args list. If your question is about how "obj.func()" becomes "obj.___class__.func(obj)", then the answer is "protocol deescriptor" + "method type". The function type implements the protocol descriptor so that its __get__ method returns a method instance which wraps around the function, class and instance. Then the method's __call__ method will delegate to the function, injecting the instance as first positional param. > and > what features are only possible because of, or are greatly improved, > because of it. Simplicity (methods are built of the combination of two "general purpose" features - descriptor protocol and callable objects), flexibility (you can use any callable object as a 'method' as long as it correctly implements the descriptor protocol), and of course readability (no special rules wrt/ 'self', it's nothing else than the first argument of the function, period). Oh, and yes - you can use methods as functions too, it's sometimes handy for dispatching purposes !-) From bruno.42.desthuilliers at websiteburo.invalid Mon Dec 14 04:17:20 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 14 Dec 2009 10:17:20 +0100 Subject: Moving from PHP to Python. Is it Possible In-Reply-To: <3c4778e3-e31a-4484-ae9a-f6d5b737fa68@x25g2000prf.googlegroups.com> References: <3c4778e3-e31a-4484-ae9a-f6d5b737fa68@x25g2000prf.googlegroups.com> Message-ID: <4b2602a0$0$30660$426a34cc@news.free.fr> zeph a ?crit : (snip) > 4) It's better to collect all your eventual output into a string that > you print Yuck ! Definitly one of the worst advises you could give. By all mean, *DONT* do that. Use a templating system instead. From deets at nospam.web.de Mon Dec 14 04:20:21 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 14 Dec 2009 10:20:21 +0100 Subject: Moving from PHP to Python. Is it Possible In-Reply-To: References: <7ole38F3qetj5U1@mid.uni-berlin.de> Message-ID: <7omealF3p9jj2U1@mid.uni-berlin.de> > Yes, I understood. And I'm using large Global dictionary (or Array) to > replicate those objects. State of the thing will store in there. But it > wasn't an object. Just Assocative array. Staying in global space, > > Because. > > In web programming we do not store anything except session. Every object we > created was destroyed after execution. Using objects in this conditions was > non sense to me. (of course I'm not very capable programmer probably it was my > fault to take full advantage of oo programming) > > Plus. In php we can store arrays in files very easy. Combining this with any > PHP opcode cache can save those arrays in memory. So we got damn cheap state > saver. This is possible in python, too. But "damn cheap"... well, the cheapest solution in terms of speed is to just keep the things in memory. Which you can't do with PHP, as everything lives just one request, but in Python with certain app-servers, you can do this. > > Of course things may differ in python. > > Anyhow I generate a Registry class to replicate global dictionary. Probably it > much better than my PHP Direct $GLOBAL usage. > > So I have no problem with that. > >>> Anyway, I need to save my lots and lots of config variables in dictionary >>> style global accessible location. >>> >>> Because. >>> >>> In my design We got lots of plugins, and those plugins may show in >>> multiple times and multiple locations in a page. >>> >>> Each plugin may have setup values to affect entire page output. >>> >>> Because of this. I have to put those values in global location for future >>> use. >> No, you don't. Because of this, you can e.g. use ToscaWidgets as a >> framework for creating widgets that encapsulate code, HTML, javascript >> and CSS. And no global state is shared. >> >> Also, I think you should *really* look into one of the available >> web-frameworks such as Django or Turbogears to learn how to write >> webapps in python - instead of shoehorning your tried & trusted PHP >> techniques that don't translate well. >> > > Yes I download the django trying to learn but it was much different. > > My problem is not writing web apps. I'm doing well. > > My design was very good and I'm very proud its abilities. > > My problem is with PHP syntax and performance. > > I'm just trying to replicate my recepies in python... Then the result will be a twice as horrible program in python. Because you work against the language. In the end of course, what matters is what works for you. Diez From bruno.42.desthuilliers at websiteburo.invalid Mon Dec 14 04:22:05 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 14 Dec 2009 10:22:05 +0100 Subject: Moving from PHP to Python. Is it Possible In-Reply-To: References: <7ole38F3qetj5U1@mid.uni-berlin.de> Message-ID: <4b2603bc$0$30660$426a34cc@news.free.fr> Sancar Saran a ?crit : (snip) > My problem is with PHP syntax and performance. > I'm just trying to replicate my recepies in python... Python is not PHP, and trying to write PHP in Python won't buy you much except pain and frustration. From robin at reportlab.com Mon Dec 14 04:56:43 2009 From: robin at reportlab.com (Robin Becker) Date: Mon, 14 Dec 2009 09:56:43 +0000 Subject: eiger replacement? In-Reply-To: References: <00ac5472$0$15654$c3e8da3@news.astraweb.com> Message-ID: <4B260BDB.9000507@chamonix.reportlab.co.uk> On 12/12/2009 05:38, Tim Roberts wrote: > Steven D'Aprano wrote: > >> On Fri, 11 Dec 2009 17:45:24 +0000, Robin Becker wrote: >> >>> The current hardware >>> >>> CPU: Intel(R) Pentium(R) 4 CPU 2.40GHz (2394.01-MHz 686-class CPU) >> [...] >> >> What does this have to do with Python? > > I'm guessing Robin had a slight address book malfunction when he sent this. indeed, an excess of Christmas Spirit as well. Never a doh! moment should be passed by. Sorry for any confusion -- Robin Becker From robin at reportlab.com Mon Dec 14 04:56:43 2009 From: robin at reportlab.com (Robin Becker) Date: Mon, 14 Dec 2009 09:56:43 +0000 Subject: eiger replacement? In-Reply-To: References: <00ac5472$0$15654$c3e8da3@news.astraweb.com> Message-ID: <4B260BDB.9000507@chamonix.reportlab.co.uk> On 12/12/2009 05:38, Tim Roberts wrote: > Steven D'Aprano wrote: > >> On Fri, 11 Dec 2009 17:45:24 +0000, Robin Becker wrote: >> >>> The current hardware >>> >>> CPU: Intel(R) Pentium(R) 4 CPU 2.40GHz (2394.01-MHz 686-class CPU) >> [...] >> >> What does this have to do with Python? > > I'm guessing Robin had a slight address book malfunction when he sent this. indeed, an excess of Christmas Spirit as well. Never a doh! moment should be passed by. Sorry for any confusion -- Robin Becker From aioe.org at technicalbloke.com Mon Dec 14 04:59:43 2009 From: aioe.org at technicalbloke.com (r0g) Date: Mon, 14 Dec 2009 09:59:43 +0000 Subject: Moving from PHP to Python. Is it Possible References: <7ole38F3qetj5U1@mid.uni-berlin.de> <4b2603bc$0$30660$426a34cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > Sancar Saran a ?crit : > (snip) >> My problem is with PHP syntax and performance. I'm just trying to >> replicate my recepies in python... > > Python is not PHP, and trying to write PHP in Python won't buy you much > except pain and frustration. I think people are being a little harsh here. Replicating exactly what PHP code does on a micro level i.e. line by line is probably a bad idea but for all we know a lot of the macro level stuff might be fine, or mostly fine i.e. structures, algorithms, classes and functions etc. If this is the case rewriting the same bits in Python might not be painful and frustrating, indeed seeing how much terser those things can be written in Python would probably be quite satisfying. Of course, some PHP is never going to port well but you can't say for sure without seeing it. Roger. From istvan.szirtes at gmail.com Mon Dec 14 05:25:45 2009 From: istvan.szirtes at gmail.com (W00D00) Date: Mon, 14 Dec 2009 02:25:45 -0800 (PST) Subject: How can I get the target platform info of a dll with Python 3.1.1? References: <01772f90-856c-4723-9f72-366a5d088ed5@k4g2000yqb.googlegroups.com> Message-ID: On dec. 12, 03:18, "Gabriel Genellina" wrote: > En Fri, 11 Dec 2009 16:39:37 -0300, Isti ? > escribi?: > > > I have manydllfiles and I would like to select them into two > > different folders (PC and PPC). For this I need to know the target > > platform of thedllfile or any other details about its platform. > > Look at sys.platform and the platform module. > > -- > Gabriel Genellina Hi, The platform module gives you information about the platform where you are running on with your script and not about the not loaded dll(s). So, thanks but, this does not work in this case. However, I found a solution: def DLLIdentifier( self ): ''' Microsoft Portable Executable and Common Object File Format Specification http://www.microsoft.com/whdc/system/platform/firmware/PECOFF.mspx After the MS DOS stub, at the file offset specified at offset 0x3c, is a 4-byte signature that identifies the file as a PE format image file. This signature is "PE\0\0" (the letters "P" and "E" followed by two null bytes). At the beginning of an object file, or immediately after the signature of an image file, is a standard COFF file header in the following format. Note that the Windows loader limits the number of sections to 96. The Machine field has one of the following values that specifies its CPU type. An image file can be run only on the specified machine or on a system that emulates the specified machine. ''' Platform = 'UNKNOWN' for Row in codecs.open( os.path.join( self.Root, self.File ), 'rb' ): if b'\x00PE\x00\x00' in Row: # IMAGE_FILE_MACHINE_UNKNOWN 0x0 The contents of this field are assumed to be applicable to any machine type if b'\x00PE\x00\x00\x00\x00' in Row: Platform = 'UNKNOWN' break # IMAGE_FILE_MACHINE_AM33 0x1d3 Matsushita AM33 elif b'\x00PE\x00\x00\xD3\x01' in Row: Platform = 'AM33' break # IMAGE_FILE_MACHINE_AMD64 0x8664 x64 elif b'\x00PE\x00\x00\x664\x08' in Row: Platform = 'AMD64' break # IMAGE_FILE_MACHINE_ARM 0x1c0 ARM little endian elif b'\x00PE\x00\x00\xC0\x01' in Row: Platform = 'ARM' break # IMAGE_FILE_MACHINE_EBC 0xebc EFI byte code elif b'\x00PE\x00\x00\xBC\x0E' in Row: Platform = 'EBC' break # IMAGE_FILE_MACHINE_I386 0x14c Intel 386 or later processors and compatible processors elif b'\x00PE\x00\x00\x4C\x01' in Row: Platform = 'I386' break # IMAGE_FILE_MACHINE_IA64 0x200 Intel Itanium processor family elif b'\x00PE\x00\x00\x00\x02' in Row: Platform = 'IA64' break # IMAGE_FILE_MACHINE_M32R 0x9041 Mitsubishi M32R little endian elif b'\x00PE\x00\x00\x041\x09' in Row: Platform = 'M32R' break # IMAGE_FILE_MACHINE_MIPS16 0x266 MIPS16 elif b'\x00PE\x00\x00\x66\x02' in Row: Platform = 'MIPS16' break # IMAGE_FILE_MACHINE_MIPSFPU 0x366 MIPS with FPU elif b'\x00PE\x00\x00\x66\x03' in Row: Platform = 'MIPSFPU' break # IMAGE_FILE_MACHINE_MIPSFPU16 0x466 MIPS16 with FPU elif b'\x00PE\x00\x00\x66\x04' in Row: Platform = 'MIPSFPU16' break # IMAGE_FILE_MACHINE_POWERPC 0x1f0 Power PC little endian elif b'\x00PE\x00\x00\xF0\x01' in Row: Platform = 'POWERPC' break # IMAGE_FILE_MACHINE_POWERPCFP 0x1f1 Power PC with floating point support elif b'\x00PE\x00\x00\xF1\x01' in Row: Platform = 'POWERPCFP' break # IMAGE_FILE_MACHINE_R4000 0x166 MIPS little endian elif b'\x00PE\x00\x00\x66\x01' in Row: Platform = 'R4000' break # IMAGE_FILE_MACHINE_SH3 0x1a2 Hitachi SH3 elif b'\x00PE\x00\x00\xA2\x01' in Row: Platform = 'SH3' break # IMAGE_FILE_MACHINE_SH3DSP 0x1a3 Hitachi SH3 DSP elif b'\x00PE\x00\x00\xA3\x01' in Row: Platform = 'SH3DSP' break # IMAGE_FILE_MACHINE_SH4 0x1a6 Hitachi SH4 elif b'\x00PE\x00\x00\xA6\x01' in Row: Platform = 'SH4' break # IMAGE_FILE_MACHINE_SH5 0x1a8 Hitachi SH5 elif b'\x00PE\x00\x00\xA8\x01' in Row: Platform = 'SH5' break # IMAGE_FILE_MACHINE_THUMB 0x1c2 Thumb elif b'\x00PE\x00\x00\xC2\x01' in Row: Platform = 'THUMB' break # IMAGE_FILE_MACHINE_WCEMIPSV2 0x169 MIPS little - endian WCE v2 elif b'\x00PE\x00\x00\x69\x01' in Row: Platform = 'WCEMIPSV2' break else: StartIndex = Row.find( b'\x00PE\x00\x00' ) EndIndex = StartIndex + 7 PlatformCode = Row[StartIndex:EndIndex] self.ErrorState = False self.oLogger.critical( 'The unknown platform code is "{}".'.format( PlatformCode ) ) assert Platform != 'UNKNOWN', 'Unknown .dll file "{}" at\n {}'.format( self.File, os.path.join( self.Root, self.File ) ) if Platform == 'I386': self.PlatformType = 'PC' elif Platform in ( 'ARM', 'THUMB' ): self.PlatformType = 'PPC' else: self.ErrorState = False self.oLogger.critical( 'The unknown dll file with "{}" platform code.'.format( Platform ) ) From lie.1296 at gmail.com Mon Dec 14 05:26:49 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Mon, 14 Dec 2009 21:26:49 +1100 Subject: Dangerous behavior of list(generator) In-Reply-To: <20091214032938.2667.483968939.divmod.xquotient.25@localhost.localdomain> References: <00aed0c7$0$15654$c3e8da3@news.astraweb.com> <4b25a7ec$1@dnews.tpgi.com.au> <20091214032938.2667.483968939.divmod.xquotient.25@localhost.localdomain> Message-ID: On 12/14/09, exarkun at twistedmatrix.com wrote: > On 02:50 am, lie.1296 at gmail.com wrote: >>On 12/14/2009 9:45 AM, exarkun at twistedmatrix.com wrote: >>>On 08:18 pm, steve at remove-this-cybersource.com.au wrote: >>>>On Sun, 13 Dec 2009 14:35:21 +0000, exarkun wrote: >>>>>>StopIteration is intended to be used only within the .__next__ >>>>>>method of >>>>>>iterators. The devs know that other 'off-label' use results in the >>>>>>inconsistency you noted, but their and my view is 'don't do that'. >>>>> >>>>>Which is unfortunate, because it's not that hard to get >>>>>StopIteration >>>>>without explicitly raising it yourself and this behavior makes it >>>>>difficult to debug such situations. >>>> >>>>I can't think of any way to get StopIteration without explicitly >>>>raising >>>>it yourself. It's not like built-ins or common data structures >>>>routinely >>>>raise StopIteration. I don't think I've *ever* seen a StopIteration >>>>that >>>>I didn't raise myself. >>> >>>Call next on an iterator. For example: iter(()).next() >> >>.next() is not meant to be called directly > > Doesn't matter. Sometimes it makes sense to call it directly. And I > was just giving an example of a way to get StopIteration raised without > doing it yourself - which is what Steve said he couldn't think of. >>> >>>I'm surprised to hear you say that the magical faerie land behavior >>>isn't desirable either, though. I'd love a tool that did what I >>>wanted, >>>not what I asked. The only serious argument against this, I think, is >>>that it is beyond our current ability to create (and so anyone >>>claiming >>>to be able to do it is probably mistaken). >> >>In your world, this is what happens: >> >>> list = [a, b, c] >> >>> # print list >> >>> print list >>["a", "b", "c"] >> >>> # make a copy of list >> >>> alist = list(llst) # oops a mistype >> >>> alist = alist - "]" + ", "d"]" >> >>> print alist >>["a", "b", "c", "d"] >> >>> alist[:6] + "i", + alist[6:] >> >>> print alist >>["a", "i", "b", "c", "d"] >> >>> print alist >> >>> # hearing the sound of my deskjet printer... >> >>> C:\fikle.text.write(alist) >> >>> print open("C:\file.txt").read() >>

      a

      >>
        >>
      • i
      • >>
      • b
      • >>
      • c d
      • >> >>> # great, exactly what I needed > > I don't understand the point of this code listing, sorry. I suspect you > didn't completely understand the magical faerie land I was describing - > where all your programs would work, no matter what mistakes you made > while writing them. Exactly, that's what's happening. It just works. It knows that when I said alist[:6] + "i", + alist[6:] ; I want to insert "i" between the sixth character of the textual representation of the list. It knows to find the correct variable when I made a typo. It correctly guess that I want to print to a paper instead of to screen. It knows that when I wrote to C:\path.write(), it knows I wanted a HTML output in that specific format. It just works (TM), whatever mistakes I made. That's what you wanted, right? From __peter__ at web.de Mon Dec 14 05:35:11 2009 From: __peter__ at web.de (Peter Otten) Date: Mon, 14 Dec 2009 11:35:11 +0100 Subject: Dangerous behavior of list(generator) References: <00aed0c7$0$15654$c3e8da3@news.astraweb.com> <20091214043304.2667.732037162.divmod.xquotient.91@localhost.localdomain> Message-ID: Terry Reedy wrote: > On 12/13/2009 11:33 PM, exarkun at twistedmatrix.com wrote: >> This could provide behavior roughly equivalent to the behavior >> of a list comprehension. > > Impossible. The only serious option for consistency is to special case > list comps to also trap StopIteration raised in the expression part, but > the devs decided not to do this as doing do is arguably a bug. A viable option might be to introduce a different exception type and translate (expr(v) for v in items if cond(v)) into def gen(items, expr, cond): for v in items: try: if cond(v): yield expr(v) except StopIteration: raise TypeError("StopIteration raised in " "'expr' or 'cond' part of " "a generator expression") Peter From yjoshi at starentnetworks.com Mon Dec 14 05:56:15 2009 From: yjoshi at starentnetworks.com (Joshi, Yateen) Date: Mon, 14 Dec 2009 16:26:15 +0530 Subject: Issues with multiprocessing References: Message-ID: <3BD53621E5C8E54594130AF5459379EE13878068@exchindia4.starentnetworks.com> Hi, I am resending this as I am not seeing any response, can anyone help here? Hi, I have an application that uses multiprocessing pools (multiprocessing.Pool(processes=.....)). There are multiple such pools and each pool has configurable number of processes. Once the process is spawned, it keeps on executing and does the needed processing. If there is nothing to process (like ftp'ing files from some source, if the files are not there, the process would sleep for some time, and then again check for files, that way, it is a infinite loop with some sleep), the process 'sleeps' for some time and continues. I am using a T5220, Solaris box with Solaris 10. Problem -there are multiple pools and multiple processes, i am seeing that not all the processes get spawned. They get spawned when the sleep time is increased (say from 0.1 sec to 1 sec). If I further increase the number of processes, again some process do not get spawned. For that, I further need to increase the sleep time (say to 2 sec), then the processes get spawned. Typically, in a multiprocessing I would expect that if a process sleeps for even a small time, other processes should get their chance to execute, but this does not seem to be happening here. Can you please throw some light on it? Thanks and Regards, Yateen V. Joshi This email and any attachments may contain legally privileged and/or confidential information of Starent Networks, Corp. and is intended only for the individual or entity named in the message. The information transmitted may not be used to create or change any contractual obligations of Starent Networks, Corp. Any review, retransmission, dissemination or other use of, or taking of any action in reliance upon this e-mail and its attachments by persons or entities other than the intended recipient is prohibited. If you are not the intended recipient, please notify the sender immediately -- by replying to this message or by sending an email to postmaster at starentnetworks.com -- and destroy all copies of this message and any attachments without reading or disclosing their contents. Thank you. -------------- next part -------------- An HTML attachment was scrubbed... URL: From bruno.42.desthuilliers at websiteburo.invalid Mon Dec 14 06:25:16 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 14 Dec 2009 12:25:16 +0100 Subject: Moving from PHP to Python. Is it Possible In-Reply-To: References: <7ole38F3qetj5U1@mid.uni-berlin.de> <4b2603bc$0$30660$426a34cc@news.free.fr> Message-ID: <4b26209b$0$7608$426a74cc@news.free.fr> r0g a ?crit : > Bruno Desthuilliers wrote: >> Sancar Saran a ?crit : >> (snip) >>> My problem is with PHP syntax and performance. I'm just trying to >>> replicate my recepies in python... >> Python is not PHP, and trying to write PHP in Python won't buy you much >> except pain and frustration. > > > I think people are being a little harsh here. Replicating exactly what > PHP code does on a micro level i.e. line by line is probably a bad idea > but for all we know a lot of the macro level stuff might be fine, or > mostly fine i.e. structures, algorithms, classes and functions etc. I was talking about trying to replicate PHP's execution model and idioms in Python - the "framework" part -, not about application specific algos, data structures etc. From sancar.saran at evodot.com Mon Dec 14 07:55:13 2009 From: sancar.saran at evodot.com (Sancar Saran) Date: Mon, 14 Dec 2009 14:55:13 +0200 Subject: Moving from PHP to Python. Part Two Message-ID: <200912141455.13831.sancar.saran@evodot.com> Hello Again. I hope, I don't bug too much. First of all. I want to Thank to everyone who respond my messages. I was able to do some of my needs and stuck some others. So ? I need help again. And here my progress.. Following was my globalized registry solution # -*- coding: utf-8 -*- class Registry: data = {} def __init__(self,environ): self.data['env'] = environ self.data['init'] = 'hede' def set_entry(self,key,data): self.data[key] = data def get_entry(self,key): return self.data[key] def debug(self): r = '
        '
        		r += repr(self.data)
        		r += '
        ' return r I have some questions about this code. First of all. when execute debug function. It wont work in every request. # -*- coding: utf-8 -*- import os, sys, cgi, pprint import cgitb cgitb.enable() def application(environ, start_response): sys.path.append(environ['DOCUMENT_ROOT']+"core") import registry, k5 # new registry r = registry.Registry(environ) r.set_entry('hede','hodo') #response_headers = [('Content-type',k5.headers['content-type']+'; charset='+k5.headers['charset'])] #start_response(kk5.headers['status'], response_headers) response_body = 'The request method was %s' % environ['REQUEST_METHOD'] response_body += '
        ' response_body += r.debug() status = '200 OK' response_headers = [('Content-Type', 'text/plain'), ('Content-Length', str(len(response_body)))] start_response(status, response_headers) return [response_body] In first request I can see elements of my registry and second request it was shows noting. Then 3rd request I can see my registry elements again. next request was empty too. And it was go like that. I don't understand why ? Second problem is. Formatting. I need to see my dictionary elements like this. [k5req] => Array ( [raw] => heede [post] => Array ( ) [proto] => http:// [base_url] => http://k5.int/? [bend_url] => http://k5.int/?backend/ [ajax_url] => http://k5.int/?ajax/ [domain] => k5.int [path] => Array ( [0] => heede ) [location] => frontend [page] => heede [dom_stat] => 1 ) Is there any available solution (like php's print_r) or have I write to my own ? And If I understood correctly PSP template execution in mod_wsgi is impossible. So I have to look something like cheetah or similar marker based template systems. And If I understood correctly I have to import every module in sub imported module. And I want to make sure to my 5 different base module was available every other sub imported module. Is there any way to this from do and forget from start ? Regards. From pavlovevidence at gmail.com Mon Dec 14 07:56:12 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 14 Dec 2009 04:56:12 -0800 (PST) Subject: power of explicit self? References: <73d81fbc-95c5-4897-bca1-852471eb7938@q16g2000vbc.googlegroups.com> <0e1c9da1-a8e7-486e-aa28-341ef2c8d1bf@2g2000prl.googlegroups.com> Message-ID: On Dec 12, 12:20?pm, Fire Crow wrote: > > It's not implemented in the compiler. There's a place in the runtime > > for invoking a method where the object is inserted at the beginning > > of the parameter list. IIRC, that's done by wrapping the function > > object. > > This is the source of Objects/methodobject.c it look like this is > where > self is added to the argument list, but I'll have to do some more > digging. No, not really. That code sets the self argument only for functions implemented in C. The code that implements self behavior for Python methods is mostly found in the file classobject.c. Basically whenever a method is accessed through an object, the object creates an instancemethod for it. The instancemethod type is defined in classobject.c. Carl Banks From neilc at norwich.edu Mon Dec 14 08:38:29 2009 From: neilc at norwich.edu (Neil Cerutti) Date: 14 Dec 2009 13:38:29 GMT Subject: a list/re problem References: <7ofr58F3q174qU2@mid.individual.net> Message-ID: <7omtelF3qmo35U1@mid.individual.net> On 2009-12-11, Grant Edwards wrote: > On 2009-12-11, Neil Cerutti wrote: >> On 2009-12-11, Grant Edwards wrote: >>> [s[1:-1] for s in l if (s[0] == s[-1] == '*')] >> >> That last bit doesn't work right, does it, since an == expression >> evaluates to True or False, no the true or false value itself? > > It works for me. Doesn't it work for you? > > From the fine manual (section 5.9. Comparisons): > > Comparisons can be chained arbitrarily, e.g., x < y <= z is > equivalent to x < y and y <= z, except that y is evaluated > only once (but in both cases z is not evaluated at all when x > < y is found to be false). I did not know that. Thanks, Grant. -- Neil Cerutti From exarkun at twistedmatrix.com Mon Dec 14 09:31:44 2009 From: exarkun at twistedmatrix.com (exarkun at twistedmatrix.com) Date: Mon, 14 Dec 2009 14:31:44 -0000 Subject: Dangerous behavior of list(generator) Message-ID: <20091214143144.2667.1208567657.divmod.xquotient.95@localhost.localdomain> On 06:46 am, tjreedy at udel.edu wrote: >On 12/13/2009 10:29 PM, exarkun at twistedmatrix.com wrote: >>Doesn't matter. Sometimes it makes sense to call it directly. > >It only makes sense to call next (or .__next__) when you are prepared >to explicitly catch StopIteration within a try..except construct. >You did not catch it, so it stopped execution. > >Let me repeat: StopIteration is intended only for stopping iteration. >Outside that use, it is a normal exception with no special meaning. You cut out the part of my message where I wrote that one might have forgotten the exception handling code that you posit is required, and that the current behavior makes debugging this situation unnecessarily challenging. Jean-Paul From deets at nospam.web.de Mon Dec 14 09:55:04 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 14 Dec 2009 15:55:04 +0100 Subject: Moving from PHP to Python. Part Two References: Message-ID: <7on1u8F3qf5gnU1@mid.uni-berlin.de> Sancar Saran wrote: > Hello Again. > > I hope, I don't bug too much. > > First of all. I want to Thank to everyone who respond my messages. > > I was able to do some of my needs and stuck some others. > > So ? I need help again. > > And here my progress.. > > Following was my globalized registry solution > > # -*- coding: utf-8 -*- > > class Registry: > > data = {} > > def __init__(self,environ): > self.data['env'] = environ > self.data['init'] = 'hede' > > def set_entry(self,key,data): > self.data[key] = data > > def get_entry(self,key): > return self.data[key] > > def debug(self): > > r = '
        '
        > r += repr(self.data)
        > r += '
        ' > > return r > > I have some questions about this code. > > First of all. when execute debug function. It wont work in every request. > > # -*- coding: utf-8 -*- > > import os, sys, cgi, pprint > import cgitb > cgitb.enable() > > > def application(environ, start_response): > sys.path.append(environ['DOCUMENT_ROOT']+"core") > import registry, k5 > # new registry > > r = registry.Registry(environ) > r.set_entry('hede','hodo') > > #response_headers = [('Content-type',k5.headers['content-type']+'; > charset='+k5.headers['charset'])] > #start_response(kk5.headers['status'], response_headers) > > response_body = 'The request method was %s' % environ['REQUEST_METHOD'] > response_body += '
        ' > response_body += r.debug() > > > status = '200 OK' > > response_headers = [('Content-Type', 'text/plain'), > ('Content-Length', str(len(response_body)))] > > start_response(status, response_headers) > > > return [response_body] > > In first request I can see elements of my registry and second request it > was shows noting. Then 3rd request I can see my registry elements again. > next request was empty too. And it was go like that. I don't understand > why ? > > Second problem is. Formatting. > > I need to see my dictionary elements like this. > > [k5req] => Array > ( > [raw] => heede > [post] => Array > ( > ) > > [proto] => http:// > [base_url] => http://k5.int/? > [bend_url] => http://k5.int/?backend/ > [ajax_url] => http://k5.int/?ajax/ > [domain] => k5.int > [path] => Array > ( > [0] => heede > ) > > [location] => frontend > [page] => heede > [dom_stat] => 1 > ) > > Is there any available solution (like php's print_r) or have I write to my > own ? import pprint pprint.pformat({"foo" : 10}) > If I understood correctly I have to import every module in sub imported > module. > > And I want to make sure to my 5 different base module was available every > other sub imported module. > > Is there any way to this from do and forget from start ? Not really. In python, each module must import whatever dependencies it has. You *can* put stuff into the __builtins__-namespace, and this will make them available in each piece of code running. However, I (and any other sane person on this list) will *STRONGLY* advise you against doing that - polluting this global namespace will very likely create collisions which will re-define names and thus introduce nasty bugs. Python has namespaces. Use them. Diez From mal at egenix.com Mon Dec 14 09:58:51 2009 From: mal at egenix.com (M.-A. Lemburg) Date: Mon, 14 Dec 2009 15:58:51 +0100 Subject: Dangerous behavior of list(generator) In-Reply-To: <20091213143521.2549.845539319.divmod.xquotient.731@localhost.localdomain> References: <20091213143521.2549.845539319.divmod.xquotient.731@localhost.localdomain> Message-ID: <4B2652AB.7080501@egenix.com> exarkun at twistedmatrix.com wrote: > On 08:45 am, tjreedy at udel.edu wrote: >> Tom Machinski wrote: >>> In most cases, `list(generator)` works as expected. Thus, >>> `list()` is generally equivalent to `[>> expression>]`. >>> >>> Here's a minimal case where this equivalence breaks, causing a serious >>> and hard-to-detect bug in a program: >>> >>> >>> def sit(): raise StopIteration() >> >> StopIteration is intended to be used only within the .__next__ method >> of iterators. The devs know that other 'off-label' use results in the >> inconsistency you noted, but their and my view is 'don't do that'. > > Which is unfortunate, because it's not that hard to get StopIteration > without explicitly raising it yourself and this behavior makes it > difficult to debug such situations. > > What's with this view, exactly? Is it just that it's hard to implement > the more desirable behavior? I'm not exactly sure what you're asking for. The StopIteration exception originated as part of the for-loop protocol. Later on it was generalized to apply to generators as well. The reason for using an exception is simple: raising and catching exceptions is fast at C level and since the machinery for communicating exceptions up the call stack was already there (and doesn't interfere with the regular return values), this was a convenient method to let the upper call levels know that an iteration has ended (e.g. a for-loop 4 levels up the stack). I'm not sure whether that answers your question, but it's the reason for things being as they are :-) -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Dec 14 2009) >>> 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 our new mxODBC.Connect Python Database Interface 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 http://www.egenix.com/company/contact/ From iwaki at iwakihidekazu.net Mon Dec 14 10:02:09 2009 From: iwaki at iwakihidekazu.net (Hidekazu IWAKI) Date: Tue, 15 Dec 2009 00:02:09 +0900 Subject: What is the differences between tkinter in windows and Tkinter in the other platform? Message-ID: <76820091214150209iwaki@iwakihidekazu.net> Hi, I'm hidekazu. I'm making a Tk application with python. In the below code, the class App was inherited from Tkinter.Tk and the __init__ method calls Tk's constructor with `super` method. In windows, this code is valid (but, Tkinter -> tkinter). Why does this code happen a type error in not windows platform? thank you. #-------------------------------------------------------- from Tkinter import * class App(Tk): def __init__(self): super(Tk,self).__init__() App().mainloop() #Traceback (most recent call last): # File "./app.py", line 16, in # App().mainloop() # File "./app.py", line 7, in __init__ # super(Tk,self).__init__() #TypeError: super() argument 1 must be type, not classobj ///////////////////////////////////////////////// ??????????????? e-mail: iwaki at iwakihidekazu.net ///////////////////////////////////////////////// From exarkun at twistedmatrix.com Mon Dec 14 10:21:09 2009 From: exarkun at twistedmatrix.com (exarkun at twistedmatrix.com) Date: Mon, 14 Dec 2009 15:21:09 -0000 Subject: Dangerous behavior of list(generator) In-Reply-To: <4B2652AB.7080501@egenix.com> References: <20091213143521.2549.845539319.divmod.xquotient.731@localhost.localdomain> <4B2652AB.7080501@egenix.com> Message-ID: <20091214152109.2667.401778734.divmod.xquotient.105@localhost.localdomain> On 02:58 pm, mal at egenix.com wrote: >exarkun at twistedmatrix.com wrote: >>On 08:45 am, tjreedy at udel.edu wrote: >>>Tom Machinski wrote: >>>>In most cases, `list(generator)` works as expected. Thus, >>>>`list()` is generally equivalent to >>>>`[>>>expression>]`. >>>> >>>>Here's a minimal case where this equivalence breaks, causing a >>>>serious >>>>and hard-to-detect bug in a program: >>>> >>>> >>> def sit(): raise StopIteration() >>> >>>StopIteration is intended to be used only within the .__next__ method >>>of iterators. The devs know that other 'off-label' use results in the >>>inconsistency you noted, but their and my view is 'don't do that'. >> >>Which is unfortunate, because it's not that hard to get StopIteration >>without explicitly raising it yourself and this behavior makes it >>difficult to debug such situations. >> >>What's with this view, exactly? Is it just that it's hard to >>implement >>the more desirable behavior? > >I'm not exactly sure what you're asking for. > >The StopIteration exception originated as part of the for-loop >protocol. Later on it was generalized to apply to generators >as well. > >The reason for using an exception is simple: raising and catching >exceptions is fast at C level and since the machinery for >communicating exceptions up the call stack was already there >(and doesn't interfere with the regular return values), this >was a convenient method to let the upper call levels know >that an iteration has ended (e.g. a for-loop 4 levels up the >stack). > >I'm not sure whether that answers your question, but it's the >reason for things being as they are :-) I'm asking about why the behavior of a StopIteration exception being handled from the `expression` of a generator expression to mean "stop the loop" is accepted by "the devs" as acceptable. To continue your comparison to for loops, it's as if a loop like this: for a in b: c actually meant this: for a in b: try: c except StopIteration: break Note, I know *why* the implementation leads to this behavior. I'm asking why "the devs" *accept* this. Jean-Paul From __peter__ at web.de Mon Dec 14 10:44:19 2009 From: __peter__ at web.de (Peter Otten) Date: Mon, 14 Dec 2009 16:44:19 +0100 Subject: What is the differences between tkinter in windows and Tkinter in the other platform? References: Message-ID: Hidekazu IWAKI wrote: > Hi, I'm hidekazu. > > I'm making a Tk application with python. > In the below code, the class App was inherited from Tkinter.Tk and the > __init__ method calls Tk's constructor with `super` method. In windows, > this code is valid (but, Tkinter -> tkinter). > > Why does this code happen a type error in not windows platform? > > thank you. > > #-------------------------------------------------------- > from Tkinter import * > > class App(Tk): > def __init__(self): > super(Tk,self).__init__() > > App().mainloop() > > #Traceback (most recent call last): > # File "./app.py", line 16, in > # App().mainloop() > # File "./app.py", line 7, in __init__ > # super(Tk,self).__init__() > #TypeError: super() argument 1 must be type, not classobj In Python 2.x Tkinter uses classic classes (classes that do not inherit from object), and super() can't handle these. In 3.x classic classes are gone, and tkinter uses newstyle classes. So the behaviour changes from 2.x to 3.x, but should be the same on all platforms. Peter From mwilson at the-wire.com Mon Dec 14 11:09:19 2009 From: mwilson at the-wire.com (Mel) Date: Mon, 14 Dec 2009 11:09:19 -0500 Subject: Dangerous behavior of list(generator) References: <20091213143521.2549.845539319.divmod.xquotient.731@localhost.localdomain> <4B2652AB.7080501@egenix.com> Message-ID: exarkun at twistedmatrix.com wrote: [ ... ] it's as if a loop like this: > > for a in b: > c > > actually meant this: > > for a in b: > try: > c > except StopIteration: > break > > Note, I know *why* the implementation leads to this behavior. I'm > asking why "the devs" *accept* this. It's part of the price Python pays for letting people get their hands on the controls. Consider also: Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41) [GCC 4.3.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> class dict2(dict): ... def __getitem__ (self, key): ... if key == 'fatal': ... raise KeyError ... >>> d = dict2() >>> d['fatal'] = 'Hello, world!' >>> print d['fatal'] Traceback (most recent call last): File "", line 1, in File "", line 4, in __getitem__ KeyError >>> "KeyError when we just put the item into the dict?" "Yep." Mel. > > Jean-Paul From ethan at stoneleaf.us Mon Dec 14 12:04:35 2009 From: ethan at stoneleaf.us (Ethan Furman) Date: Mon, 14 Dec 2009 09:04:35 -0800 Subject: setup.py and PyPI Message-ID: <4B267023.60300@stoneleaf.us> Greetings! I'm using Python 2.5 on Windows XP, and trying to get the upload portion of setup.py to work. According to what I have found, I can put my info into a .pypirc file to have the process pick up my username/password and upload the files. I have tried putting this file into the same folder I'm running setup.py from, into my home folder (USERPROFILE, I think) -- and the really frustrating part is that it worked a couple times (but maybe that was from my home computer) but mostly it does not. Any and all pointers gratefully accepted! ~Ethan~ From gervaz at gmail.com Mon Dec 14 12:13:24 2009 From: gervaz at gmail.com (mattia) Date: 14 Dec 2009 17:13:24 GMT Subject: insert unique data in a list References: <4b251840$0$30959$4fafbaef@reader3.news.tin.it> <4b252b1b$0$644$4fafbaef@reader4.news.tin.it> <07c342ef-fd02-4d6e-ab23-6effdd0598fc@b36g2000prf.googlegroups.com> Message-ID: <4b267234$0$8867$4fafbaef@reader5.news.tin.it> Il Sun, 13 Dec 2009 21:17:28 -0800, knifenomad ha scritto: > On 12?14?, ??12?42?, Steven D'Aprano > wrote: >> On Sun, 13 Dec 2009 17:19:17 -0800, knifenomad wrote: >> > this makes the set type hashable. >> >> > class Set(set): >> > ? ? __hash__ = lambda self: id(self) >> >> That's a *seriously* broken hash function. >> >> >>> key = "voila" >> >>> d = { Set(key): 1 } >> >>> d >> >> {Set(['i', 'a', 'l', 'o', 'v']): 1}>>> d[ Set(key) ] >> >> Traceback (most recent call last): >> ? File "", line 1, in >> KeyError: Set(['i', 'a', 'l', 'o', 'v']) >> >> -- >> Steven > > of course it is broken as long as it uses it's instance id. i added this > to notify that unhashable can become hashable implementing __hash__ > inside the class. which probably set to None by default. Ok, nice example, but I believe that using id() as the hash function can lead to unexpected collisions. From philip at semanchuk.com Mon Dec 14 12:17:19 2009 From: philip at semanchuk.com (Philip Semanchuk) Date: Mon, 14 Dec 2009 12:17:19 -0500 Subject: setup.py and PyPI In-Reply-To: <4B267023.60300@stoneleaf.us> References: <4B267023.60300@stoneleaf.us> Message-ID: <84964F02-513C-4D40-826B-67B66E9EAF79@semanchuk.com> On Dec 14, 2009, at 12:04 PM, Ethan Furman wrote: > Greetings! > > I'm using Python 2.5 on Windows XP, and trying to get the upload > portion of setup.py to work. According to what I have found, I can > put my info into a .pypirc file to have the process pick up my > username/password and upload the files. > > I have tried putting this file into the same folder I'm running > setup.py from, into my home folder (USERPROFILE, I think) -- and the > really frustrating part is that it worked a couple times (but maybe > that was from my home computer) but mostly it does not. When it fails, how does it fail? From catalinfest at gmail.com Mon Dec 14 12:33:14 2009 From: catalinfest at gmail.com (catalinfest at gmail.com) Date: Mon, 14 Dec 2009 09:33:14 -0800 (PST) Subject: md5 strange error References: <315a7350-2af6-49d6-887f-10b8017f4d39@r31g2000vbi.googlegroups.com> Message-ID: now i have Fedora 12 Now when i try to use md5 , python say : python Python 2.6.2 (r262:71600, Aug 21 2009, 12:22:21) [GCC 4.4.1 20090818 (Red Hat 4.4.1-6)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import md5 __main__:1: DeprecationWarning: the md5 module is deprecated; use hashlib instead >>> import md5 >>> Why ? From rami.chowdhury at gmail.com Mon Dec 14 12:45:38 2009 From: rami.chowdhury at gmail.com (Rami Chowdhury) Date: Mon, 14 Dec 2009 09:45:38 -0800 Subject: md5 strange error In-Reply-To: References: <315a7350-2af6-49d6-887f-10b8017f4d39@r31g2000vbi.googlegroups.com> Message-ID: <2f79f590912140945o36655bc9s79908afd43a51f53@mail.gmail.com> On Mon, Dec 14, 2009 at 09:33, catalinfest at gmail.com wrote: > now i have Fedora 12 > Now when i try to use md5 , python say : > ?python > Python 2.6.2 (r262:71600, Aug 21 2009, 12:22:21) > [GCC 4.4.1 20090818 (Red Hat 4.4.1-6)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> import md5 > __main__:1: DeprecationWarning: the md5 module is deprecated; use > hashlib instead >>>> import md5 >>>> > > Why ? As the message says: the md5 module is deprecated, and you should use the hashlib module instead. I believe md5 is deprecated from Python 2.6 onwards, which may be why you have not seen this message before (Fedora 12 is the first Fedora to ship with Python 2.6). -------- Rami Chowdhury "Never assume malice when stupidity will suffice." -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) From tjreedy at udel.edu Mon Dec 14 13:00:07 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 14 Dec 2009 13:00:07 -0500 Subject: Dangerous behavior of list(generator) In-Reply-To: <20091214152109.2667.401778734.divmod.xquotient.105@localhost.localdomain> References: <20091213143521.2549.845539319.divmod.xquotient.731@localhost.localdomain> <4B2652AB.7080501@egenix.com> <20091214152109.2667.401778734.divmod.xquotient.105@localhost.localdomain> Message-ID: On 12/14/2009 10:21 AM, exarkun at twistedmatrix.com wrote: > I'm asking about why the behavior of a StopIteration exception being > handled from the `expression` of a generator expression to mean "stop > the loop" is accepted by "the devs" as acceptable. Any unhandled exception within a loop stops the loop, and the exception is passed to the surrounding code. > To continue your > comparison to for loops, it's as if a loop like this: > > for a in b: > c > > actually meant this: > > for a in b: > try: > c > except StopIteration: > break No it does not. If c raises any exception, the loop stops *and* the exception is passed up to the surrounding code. > Note, I know *why* the implementation leads to this behavior. You do not seem to know what the behavior is. Read what I wrote last night. Terry Jan Reedy From ethan at stoneleaf.us Mon Dec 14 13:00:40 2009 From: ethan at stoneleaf.us (Ethan Furman) Date: Mon, 14 Dec 2009 10:00:40 -0800 Subject: setup.py and PyPI In-Reply-To: <84964F02-513C-4D40-826B-67B66E9EAF79@semanchuk.com> References: <4B267023.60300@stoneleaf.us> <84964F02-513C-4D40-826B-67B66E9EAF79@semanchuk.com> Message-ID: <4B267D48.4010501@stoneleaf.us> Philip Semanchuk wrote: > > On Dec 14, 2009, at 12:04 PM, Ethan Furman wrote: > >> Greetings! >> >> I'm using Python 2.5 on Windows XP, and trying to get the upload >> portion of setup.py to work. According to what I have found, I can >> put my info into a .pypirc file to have the process pick up my >> username/password and upload the files. >> >> I have tried putting this file into the same folder I'm running >> setup.py from, into my home folder (USERPROFILE, I think) -- and the >> really frustrating part is that it worked a couple times (but maybe >> that was from my home computer) but mostly it does not. > > > When it fails, how does it fail? > > python setup.py sdist bdist --format wininst upload [snip] running upload Submitting dist\dbf-0.87.7.zip to http://pypi.python.org/pypi Upload failed (401): You must be identified to edit package information From b49P23TIvg at stny.rr.com Mon Dec 14 13:03:16 2009 From: b49P23TIvg at stny.rr.com (Dave) Date: Mon, 14 Dec 2009 10:03:16 -0800 (PST) Subject: Seek support for new slice syntax PEP. Message-ID: <8e5054b1-8424-4633-a52e-1d9dcd1637b6@c34g2000yqn.googlegroups.com> Just as sets may now be written as {3,'hi'}, I propose that slices should be available using [start:end] syntax. Following example comes from projecteuler.net problem 166. The Numeric community would also like this, as would the general python user. The slice notation would require one ":" between the brackets to differentiate it from a list, which is similar to the set notation requirement that disambiguates it from a dictionary. Several times now I've wanted python slice notation. Perhaps I'll write a Python Enhancement Proposal. I stored slices of vector array entries to add edge = 4 indexes = [] n = edge nn = n**2 for i in range(edge): indexes.extend([ slice(i*n,(i+1)*n,1), # rows slice(i,nn,n), # cols ]) row_slices = indexes[0::2] col_slices = indexes[1::2] slash = slice(n-1,n*(n-1)+1,n-1) backslash = slice(0,nn,n+1) Which could have been written in a manner completely consistent with other python shorthand notations and for which python "cannot possibly" use the notation for some other purpose, edge = 4 indexes = [] n = edge nn = n**2 for i in range(edge): indexes.extend([ [i*n: (i+1)*n] # rows [i: nn: n], # cols ]) row_slices = indexes[0::2] col_slices = indexes[1::2] slash = [n-1: n*(n-1)+1: n-1] backslash = [0: nn: n+1] From mehmetf at gmail.com Mon Dec 14 13:05:35 2009 From: mehmetf at gmail.com (gizli) Date: Mon, 14 Dec 2009 10:05:35 -0800 (PST) Subject: str and unicode proper usage Message-ID: <193927e7-964d-4a6a-b59f-ccc49907f791@m33g2000pri.googlegroups.com> Hi all, If an entire application operates on Unicode strings from UI to database, is there a use case for str() and unicode() functions? The application should be able to read/write files, open sockets and execute external processes and parse their output. From my own experiments, the open() command for files accepts unicode strings. I am just wondering if there is a place where str() would have to be used, other than the usual use case of converting a non-string python construct (such as an integer) into a string. The reason I am asking is, I work on a project with several other developers and our NLS testing is not going so well. Major reason is (I think) that there is a lot of str() functions interspersed everywhere. So whenever a unicode character is used in those variables, the application breaks. My recommendation to the team was to remove these functions and only leave the necessary ones. However, I do not have a generic answer on when a str() function is necessary. Thanks! From debatem1 at gmail.com Mon Dec 14 13:10:16 2009 From: debatem1 at gmail.com (geremy condra) Date: Mon, 14 Dec 2009 13:10:16 -0500 Subject: Seek support for new slice syntax PEP. In-Reply-To: <8e5054b1-8424-4633-a52e-1d9dcd1637b6@c34g2000yqn.googlegroups.com> References: <8e5054b1-8424-4633-a52e-1d9dcd1637b6@c34g2000yqn.googlegroups.com> Message-ID: http://www.python.org/dev/peps/pep-3003/ Geremy Condra From tjreedy at udel.edu Mon Dec 14 13:19:18 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 14 Dec 2009 13:19:18 -0500 Subject: What is the differences between tkinter in windows and Tkinter in the other platform? In-Reply-To: <76820091214150209iwaki@iwakihidekazu.net> References: <76820091214150209iwaki@iwakihidekazu.net> Message-ID: On 12/14/2009 10:02 AM, Hidekazu IWAKI wrote: > Hi, I'm hidekazu. > > I'm making a Tk application with python. > In the below code, the class App was inherited from Tkinter.Tk and the > __init__ method calls Tk's constructor with `super` method. In windows, > this code is valid (but, Tkinter -> tkinter). > > Why does this code happen a type error in not windows platform? You question is not clear. Specify system and Python version is both cases. Note that Tkinter in 2.x was renamed tkinter in 3.x. This difference has nothing to do with the platform. tjr > > thank you. > > #-------------------------------------------------------- > from Tkinter import * > > class App(Tk): > def __init__(self): > super(Tk,self).__init__() > > App().mainloop() > > #Traceback (most recent call last): > # File "./app.py", line 16, in > # App().mainloop() > # File "./app.py", line 7, in __init__ > # super(Tk,self).__init__() > #TypeError: super() argument 1 must be type, not classobj > > ///////////////////////////////////////////////// > ??????????????? > e-mail: iwaki at iwakihidekazu.net > ///////////////////////////////////////////////// From philip at semanchuk.com Mon Dec 14 13:39:37 2009 From: philip at semanchuk.com (Philip Semanchuk) Date: Mon, 14 Dec 2009 13:39:37 -0500 Subject: setup.py and PyPI In-Reply-To: <4B267D48.4010501@stoneleaf.us> References: <4B267023.60300@stoneleaf.us> <84964F02-513C-4D40-826B-67B66E9EAF79@semanchuk.com> <4B267D48.4010501@stoneleaf.us> Message-ID: <31B30751-788A-429F-96C1-9FBA21242CE9@semanchuk.com> On Dec 14, 2009, at 1:00 PM, Ethan Furman wrote: > Philip Semanchuk wrote: >> On Dec 14, 2009, at 12:04 PM, Ethan Furman wrote: >>> Greetings! >>> >>> I'm using Python 2.5 on Windows XP, and trying to get the upload >>> portion of setup.py to work. According to what I have found, I >>> can put my info into a .pypirc file to have the process pick up >>> my username/password and upload the files. >>> >>> I have tried putting this file into the same folder I'm running >>> setup.py from, into my home folder (USERPROFILE, I think) -- and >>> the really frustrating part is that it worked a couple times (but >>> maybe that was from my home computer) but mostly it does not. >> When it fails, how does it fail? > > python setup.py sdist bdist --format wininst upload > > [snip] > > running upload > Submitting dist\dbf-0.87.7.zip to http://pypi.python.org/pypi > Upload failed (401): You must be identified to edit package > information Looks like there's known problems with this under Windows that might affect your version of Python, depending on which version you have. http://bugs.python.org/issue1741 Setting a HOME environment variable to point to wherever you have your .pypirc file might help. Hope this helps P From cjwilliams43 at gmail.com Mon Dec 14 13:40:38 2009 From: cjwilliams43 at gmail.com (Colin W.) Date: Mon, 14 Dec 2009 13:40:38 -0500 Subject: Seek support for new slice syntax PEP. In-Reply-To: <8e5054b1-8424-4633-a52e-1d9dcd1637b6@c34g2000yqn.googlegroups.com> References: <8e5054b1-8424-4633-a52e-1d9dcd1637b6@c34g2000yqn.googlegroups.com> Message-ID: On 14-Dec-09 13:03 PM, Dave wrote: > Just as sets may now be written as {3,'hi'}, I propose that slices > should be available using [start:end] syntax. Following example comes > from projecteuler.net problem 166. The Numeric community would also > like this, as would the general python user. The slice notation would > require one ":" between the brackets to differentiate it from a list, > which is similar to the set notation requirement that disambiguates it > from a dictionary. > > Several times now I've wanted python slice notation. Perhaps I'll > write a Python Enhancement Proposal. I stored slices of vector array > entries to add > > > edge = 4 > indexes = [] > n = edge > nn = n**2 > for i in range(edge): > indexes.extend([ > slice(i*n,(i+1)*n,1), # rows > slice(i,nn,n), # cols > ]) > > row_slices = indexes[0::2] > col_slices = indexes[1::2] > slash = slice(n-1,n*(n-1)+1,n-1) > backslash = slice(0,nn,n+1) > > > Which could have been written in a manner completely consistent with > other python shorthand notations and for which python "cannot > possibly" use the notation for some other purpose, > > > edge = 4 > indexes = [] > n = edge > nn = n**2 > for i in range(edge): > indexes.extend([ > [i*n: (i+1)*n] # rows > [i: nn: n], # cols > ]) > > row_slices = indexes[0::2] > col_slices = indexes[1::2] > slash = [n-1: n*(n-1)+1: n-1] > backslash = [0: nn: n+1] Yes, we know that PEP 3003 applies but I see no harm in discussing possible enhancements. The existing slice seems a little different from what you are proposing: An object usually containing a portion of a sequence. A slice is created using the subscript notation, [] with colons between numbers when several are given, such as in variable_name[1:3:5]. or: Slice objects Slice objects are used to represent slices when extended slice syntax is used. This is a slice using two colons, or multiple slices or ellipses separated by commas, e.g., a[i:j:step], a[i:j, k:l], or a[..., i:j]. They are also created by the built-in slice() function. If your scheme flies, would it be practicable to use the same syntax as a range generator? range(i, j, k) => i:j:k so range(10, 2) => :10:2 i.e. we could write for i in :10:2: or the more common: range(10) => :10 Colin W. From debatem1 at gmail.com Mon Dec 14 13:56:45 2009 From: debatem1 at gmail.com (geremy condra) Date: Mon, 14 Dec 2009 13:56:45 -0500 Subject: Seek support for new slice syntax PEP. In-Reply-To: References: <8e5054b1-8424-4633-a52e-1d9dcd1637b6@c34g2000yqn.googlegroups.com> Message-ID: > Yes, we know that PEP 3003 applies but I see no harm in discussing possible > enhancements. I don't think the OP knew that the moratorium was in effect. That's why I brought it up. Geremy Condra From donn.ingle at gmail.com Mon Dec 14 14:02:30 2009 From: donn.ingle at gmail.com (Donn) Date: Mon, 14 Dec 2009 21:02:30 +0200 Subject: pyZui - anyone know about this? In-Reply-To: References: Message-ID: <200912142102.30457.donn.ingle@gmail.com> On Monday 14 December 2009 00:10:52 David Boddie wrote: > Doesn't the author give his e-mail address at the end of the video? > (Maybe I'm thinking of a different video.) > Yes, in a quick and garbled way :) I have yet to try to contact the author or the youtube poster -- been too busy. I was hoping someone on the list may recognize what tools he was using, or have some insight into how they would attack the problem. I have pondered it from a wxPython pov, that being all I am experienced with and I would have no chance of recreating that demo. Is it using some kind of built-in QT/KDE voodoo? \d -- \/\/ave: donn.ingle at googlewave.com home: http://otherwise.relics.co.za/ 2D vector animation : https://savannah.nongnu.org/projects/things/ Font manager : https://savannah.nongnu.org/projects/fontypython/ From exarkun at twistedmatrix.com Mon Dec 14 14:05:29 2009 From: exarkun at twistedmatrix.com (exarkun at twistedmatrix.com) Date: Mon, 14 Dec 2009 19:05:29 -0000 Subject: Dangerous behavior of list(generator) In-Reply-To: References: <20091213143521.2549.845539319.divmod.xquotient.731@localhost.localdomain> <4B2652AB.7080501@egenix.com> <20091214152109.2667.401778734.divmod.xquotient.105@localhost.localdomain> Message-ID: <20091214190529.2667.248590783.divmod.xquotient.236@localhost.localdomain> On 06:00 pm, tjreedy at udel.edu wrote: >On 12/14/2009 10:21 AM, exarkun at twistedmatrix.com wrote: >>I'm asking about why the behavior of a StopIteration exception being >>handled from the `expression` of a generator expression to mean "stop >>the loop" is accepted by "the devs" as acceptable. > >Any unhandled exception within a loop stops the loop, >and the exception is passed to the surrounding code. >>To continue your >>comparison to for loops, it's as if a loop like this: >> >>for a in b: >>c >> >>actually meant this: >> >>for a in b: >>try: >>c >>except StopIteration: >>break > >No it does not. No what does not? I said "It is as if". This is a hypothetical. I'm not claiming this is the actual behavior of anything. >>Note, I know *why* the implementation leads to this behavior. > >You do not seem to know what the behavior is. >Read what I wrote last night. Well, I'm a bit tired of this thread. Please disregard my question above. I'm done here. Sorry for the confusion. Have a nice day. Jean-Paul From debatem1 at gmail.com Mon Dec 14 14:08:20 2009 From: debatem1 at gmail.com (geremy condra) Date: Mon, 14 Dec 2009 14:08:20 -0500 Subject: pyZui - anyone know about this? In-Reply-To: <200912142102.30457.donn.ingle@gmail.com> References: <200912142102.30457.donn.ingle@gmail.com> Message-ID: might be related to this: http://code.google.com/p/rchi-zui/ geremy condra From brendandetracey at yahoo.com Mon Dec 14 14:08:36 2009 From: brendandetracey at yahoo.com (Brendan) Date: Mon, 14 Dec 2009 11:08:36 -0800 (PST) Subject: Python 2.6 ftplib has timeout parameter, but how to detect a timeout Message-ID: I was quite happy to see that ftplib in Python 2.6 now has a timeout parameter. With large file downloads my script would often hang, presumably from timing out. Now that there is a timeout parameter, how would I detect when a timeout occurs? From python at bdurham.com Mon Dec 14 14:14:05 2009 From: python at bdurham.com (python at bdurham.com) Date: Mon, 14 Dec 2009 14:14:05 -0500 Subject: OS independent way to check if a python app is running? Message-ID: <1260818045.9273.1350060453@webmail.messagingengine.com> Is there an os independent way to check if a python app is running? Goal: I have a server program based on cherrypy that I only want to have running once. If a system administrator accidentally attempts to run this program more than once, I would like the 2nd instance of the program to detect that its already running and exit. Thank you, Malcolm -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Mon Dec 14 14:18:49 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 14 Dec 2009 14:18:49 -0500 Subject: Seek support for new slice syntax PEP. In-Reply-To: <8e5054b1-8424-4633-a52e-1d9dcd1637b6@c34g2000yqn.googlegroups.com> References: <8e5054b1-8424-4633-a52e-1d9dcd1637b6@c34g2000yqn.googlegroups.com> Message-ID: On 12/14/2009 1:03 PM, Dave wrote: > Just as sets may now be written as {3,'hi'}, I propose that slices > should be available using [start:end] syntax. I believe this has been proposed and rejected on one of the py-dev, py-ideas, or py-3k lists, but I would have to check to be sure. Extended slices would also have to be allowed. > The Numeric community would also like this, Evidence? Are you one of the leaders thereof? > as would the general python user. A few might but most would find it useless since they never write explicit slice objects and would have to learning something new to read code like the below. Many more people uses range objects (xrange in 2.x). A range object has the same info as a slice object *plus* it is iterable. So it would be MUCH more useful if that notation created a range object. for i in [1:n]: ... So I would oppose the slice proposal in favor of a range proposal. However, his has also, I believe, been rejected, as an abbreviation too far. > Several times now I've wanted python slice notation. Perhaps I'll > write a Python Enhancement Proposal. That could be useful, even if it gets rejected. Or perhaps this should be added to 3099. > edge = 4 > indexes = [] > n = edge > nn = n**2 > for i in range(edge): > indexes.extend([ > slice(i*n,(i+1)*n,1), # rows > slice(i,nn,n), # cols > ]) > > row_slices = indexes[0::2] > col_slices = indexes[1::2] > slash = slice(n-1,n*(n-1)+1,n-1) > backslash = slice(0,nn,n+1) > > Which could have been written in a manner completely consistent with > other python shorthand notations Python avoids getting to chicken-scratchy. There was even a proposal (rejected, see 3099) to deprecate [1,2,3], etc, in favor of list(1,2,3), etc. > and for which python "cannot possibly" use the notation for some other purpose, But it could, see above. > edge = 4 > indexes = [] > n = edge > nn = n**2 > for i in range(edge): > indexes.extend([ > [i*n: (i+1)*n] # rows > [i: nn: n], # cols > ]) > > row_slices = indexes[0::2] > col_slices = indexes[1::2] > slash = [n-1: n*(n-1)+1: n-1] > backslash = [0: nn: n+1] I find this currently to be less readable. Terry Jan Reedy From davea at ieee.org Mon Dec 14 14:19:26 2009 From: davea at ieee.org (Dave Angel) Date: Mon, 14 Dec 2009 14:19:26 -0500 Subject: str and unicode proper usage In-Reply-To: <193927e7-964d-4a6a-b59f-ccc49907f791@m33g2000pri.googlegroups.com> References: <193927e7-964d-4a6a-b59f-ccc49907f791@m33g2000pri.googlegroups.com> Message-ID: <4B268FBE.60505@ieee.org> gizli wrote: > Hi all, > > If an entire application operates on Unicode strings from UI to > database, is there a use case for str() and unicode() functions? The > application should be able to read/write files, open sockets and > execute external processes and parse their output. From my own > experiments, the open() command for files accepts unicode strings. I > am just wondering if there is a place where str() would have to be > used, other than the usual use case of converting a non-string python > construct (such as an integer) into a string. > > The reason I am asking is, I work on a project with several other > developers and our NLS testing is not going so well. Major reason is > (I think) that there is a lot of str() functions interspersed > everywhere. So whenever a unicode character is used in those > variables, the application breaks. My recommendation to the team was > to remove these functions and only leave the necessary ones. However, > I do not have a generic answer on when a str() function is necessary. > > Thanks! > > Consider switching to Python 3.x, if you aren't using any incompatible 3rd party libraries. There, the str type is always Unicode, and literals are interpreted as Unicode. But if 3.x isn't an option, I'd say you only need 8bit strings when doing I/O to 8 bit devices and files. You might also need them when talking to a program not under your own control. But if it's feasible, convert input data immediately to Unicode, do all your processing (including all literal strings) in Unicode, and convert back on output. You may also need 8bit strings for some OS calls, but if you're writing portable code, those should be minimized. DaveA From tjreedy at udel.edu Mon Dec 14 14:24:11 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 14 Dec 2009 14:24:11 -0500 Subject: Seek support for new slice syntax PEP. In-Reply-To: References: <8e5054b1-8424-4633-a52e-1d9dcd1637b6@c34g2000yqn.googlegroups.com> Message-ID: On 12/14/2009 1:10 PM, geremy condra wrote: > http://www.python.org/dev/peps/pep-3003/ The moratorium does not stop proposals for things to be added after the moratorium ends. But it does show that Guido and the devs are reluctant to make *any* change to the core syntax of 3.x without really good reason. Absent that, I would not mind if the syntax remains frozen for the rest of 3.x. A minor abbreviation that makes the language look more like Perl will not cut it. Terry Jan Reedy From lie.1296 at gmail.com Mon Dec 14 14:34:57 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Tue, 15 Dec 2009 06:34:57 +1100 Subject: insert unique data in a list In-Reply-To: <4b267234$0$8867$4fafbaef@reader5.news.tin.it> References: <4b251840$0$30959$4fafbaef@reader3.news.tin.it> <4b252b1b$0$644$4fafbaef@reader4.news.tin.it> <07c342ef-fd02-4d6e-ab23-6effdd0598fc@b36g2000prf.googlegroups.com> <4b267234$0$8867$4fafbaef@reader5.news.tin.it> Message-ID: <4b26936d$1@dnews.tpgi.com.au> On 12/15/2009 4:13 AM, mattia wrote: >> > >> > of course it is broken as long as it uses it's instance id. i added this >> > to notify that unhashable can become hashable implementing __hash__ >> > inside the class. which probably set to None by default. > Ok, nice example, but I believe that using id() as the hash function can > lead to unexpected collisions. For dict and set to work correctly, the hash function must conform to the contract that: - if A == B then hash(A) == hash(B) If the id() of two objects differ but their content equal (i.e. they are two equivalent, but distinct object), they should have the same hash. If id() is used for the hash of an arbitrary object, the contract will be broken unless you define A == B in terms of id(A) == id(B). From joncle at googlemail.com Mon Dec 14 14:35:46 2009 From: joncle at googlemail.com (Jon Clements) Date: Mon, 14 Dec 2009 11:35:46 -0800 (PST) Subject: Moving from PHP to Python. Part Two References: Message-ID: <880d32c3-67c8-4ea8-9e63-aba65777acc5@k17g2000yqh.googlegroups.com> On Dec 14, 12:55?pm, Sancar Saran wrote: > Hello Again. > > I hope, I don't bug too much. > > First of all. I want to Thank to everyone who respond my messages. > > I was able to do some of my needs and stuck some others. > > So ? I need help again. > > And here my progress.. > > Following was my globalized registry solution > > # -*- coding: utf-8 -*- > > class Registry: > > ? ? ? ? data = {} > > ? ? ? ? def __init__(self,environ): > ? ? ? ? ? ? ? ? self.data['env'] = environ > ? ? ? ? ? ? ? ? self.data['init'] = 'hede' > > ? ? ? ? def set_entry(self,key,data): > ? ? ? ? ? ? ? ? self.data[key] = data > > ? ? ? ? def get_entry(self,key): > ? ? ? ? ? ? ? ? return self.data[key] > > ? ? ? ? def debug(self): > > ? ? ? ? ? ? ? ? r = '
        '
        > ? ? ? ? ? ? ? ? r += repr(self.data)
        > ? ? ? ? ? ? ? ? r += '
        ' > > ? ? ? ? ? ? ? ? return r > > I have some questions about this code. [snip] On a side note -- data will be a class level attribute, rather than I'm guessing a desired instance level one. >>> class Blah: data = {} def __init__(self, whatever): self.data[whatever] = 'asfasdf' >>> x = Blah(3) >>> y = Blah(4) >>> Blah.data {3: 'asfasdf', 4: 'asfasdf'} >>> x.data {3: 'asfasdf', 4: 'asfasdf'} >>> y.data {3: 'asfasdf', 4: 'asfasdf'} As opposed to: >>> class Blah: def __init__(self, whatever): self.data = {} self.data[whatever] = 'asfasdf' >>> x = Blah(3) >>> y = Blah(4) >>> x.data {3: 'asfasdf'} >>> y.data {4: 'asfasdf'} >>> Blah.data Traceback (most recent call last): File "", line 1, in Blah.data AttributeError: class Blah has no attribute 'data' Jon. From seb.binet at gmail.com Mon Dec 14 14:35:56 2009 From: seb.binet at gmail.com (Sebastien Binet) Date: Mon, 14 Dec 2009 11:35:56 -0800 (PST) Subject: race/deadlock when creating a multiprocessing.manager instance while importing a module ? Message-ID: <52ce8fe6-7b3a-43dd-94bb-5a57ee7ad9b4@c34g2000yqn.googlegroups.com> hi there, say I have this module ## farnsworth ## __all__ = [ 'mgr', 'maths', ] from multiprocessing.managers import BaseManager class MathsClass(object): def add(self, x, y): return x + y def mul(self, x, y): return x * y class MyManager(BaseManager): pass MyManager.register('Maths', MathsClass) def _setup(): print "creating a manager..." mgr = MyManager() print "starting the manager..." mgr.start() print "sciencing faster..." maths = mgr.Maths() print maths.add(4,3) print maths.mul(7,8) print "done with sciencing." return (mgr, maths) # exec at module import mgr, maths = _setup() # prevent hysteresis + clean-up del _setup ## EOF ## if I use it like so: $ python -m farnsworth creating a manager... starting the manager... sciencing faster... 7 56 done with sciencing. all is fine, but if I try to use it thru an import: $ python py> import farnsworth.mgr as mgr creating a manager... starting the manager... sciencing faster... [stuck for some time... hitting ^C] Traceback (most recent call last): File "", line 1, in File "farnsworth.py", line 32, in mgr, maths = _setup() File "farnsworth.py", line 25, in _setup maths = mgr.Maths() File "/usr/lib/python2.6/multiprocessing/managers.py", line 634, in temp token, exp = self._create(typeid, *args, **kwds) File "/usr/lib/python2.6/multiprocessing/managers.py", line 532, in _create conn = self._Client(self._address, authkey=self._authkey) File "/usr/lib/python2.6/multiprocessing/connection.py", line 140, in Client answer_challenge(c, authkey) File "/usr/lib/python2.6/multiprocessing/connection.py", line 372, in answer_challenge message = connection.recv_bytes(256) # reject large message KeyboardInterrupt is this a known limitation/feature of the multiprocessing module ? is there a workaround (acquiring some import lock maybe) ? cheers, sebastien. PS: $ python Python 2.6.4 (r264:75706, Oct 27 2009, 06:25:13) [GCC 4.4.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. $ python -c 'import sys; print sys.version_info' (2, 6, 4, 'final', 0) $ uname -a Linux farnsworth 2.6.31-ARCH #1 SMP PREEMPT Tue Nov 10 19:01:40 CET 2009 x86_64 Intel(R) Core(TM)2 Duo CPU T9400 @ 2.53GHz GenuineIntel GNU/Linux From simon at brunningonline.net Mon Dec 14 14:36:42 2009 From: simon at brunningonline.net (Simon Brunning) Date: Mon, 14 Dec 2009 19:36:42 +0000 Subject: OS independent way to check if a python app is running? In-Reply-To: <1260818045.9273.1350060453@webmail.messagingengine.com> References: <1260818045.9273.1350060453@webmail.messagingengine.com> Message-ID: <8c7f10c60912141136g658caf6vad0ee55d03bcbeb3@mail.gmail.com> 2009/12/14 : > Is there an os independent way to check if a python app is running? if True: print "I'm running." ;-) -- Cheers, Simon B. From lie.1296 at gmail.com Mon Dec 14 14:41:15 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Tue, 15 Dec 2009 06:41:15 +1100 Subject: Seek support for new slice syntax PEP. In-Reply-To: <8e5054b1-8424-4633-a52e-1d9dcd1637b6@c34g2000yqn.googlegroups.com> References: <8e5054b1-8424-4633-a52e-1d9dcd1637b6@c34g2000yqn.googlegroups.com> Message-ID: <4b2694e8$1@dnews.tpgi.com.au> On 12/15/2009 5:03 AM, Dave wrote: > Just as sets may now be written as {3,'hi'}, I propose that slices > should be available using [start:end] syntax. Following example comes > from projecteuler.net problem 166. The Numeric community would also > like this, as would the general python user. The slice notation would > require one ":" between the brackets to differentiate it from a list, > which is similar to the set notation requirement that disambiguates it > from a dictionary. I would prefer [a: b, ...] syntax to become an ordered dictionary literal (if it would ever gain traction). From lie.1296 at gmail.com Mon Dec 14 14:47:02 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Tue, 15 Dec 2009 06:47:02 +1100 Subject: str and unicode proper usage In-Reply-To: <193927e7-964d-4a6a-b59f-ccc49907f791@m33g2000pri.googlegroups.com> References: <193927e7-964d-4a6a-b59f-ccc49907f791@m33g2000pri.googlegroups.com> Message-ID: <4b269642$1@dnews.tpgi.com.au> On 12/15/2009 5:05 AM, gizli wrote: > Hi all, > > If an entire application operates on Unicode strings from UI to > database, is there a use case for str() and unicode() functions? The > application should be able to read/write files, open sockets and > execute external processes and parse their output. From my own > experiments, the open() command for files accepts unicode strings. I > am just wondering if there is a place where str() would have to be > used, other than the usual use case of converting a non-string python > construct (such as an integer) into a string. > > The reason I am asking is, I work on a project with several other > developers and our NLS testing is not going so well. Major reason is > (I think) that there is a lot of str() functions interspersed > everywhere. So whenever a unicode character is used in those > variables, the application breaks. My recommendation to the team was > to remove these functions and only leave the necessary ones. However, > I do not have a generic answer on when a str() function is necessary. > > Thanks! str() is rightly renamed byte() in python 3. The new name reflects its real role: as generic binary string. Use str()/byte() to represent non-textual stream of binary data (e.g. audio/video stream, .doc file, or cipher-text). From joncle at googlemail.com Mon Dec 14 14:49:40 2009 From: joncle at googlemail.com (Jon Clements) Date: Mon, 14 Dec 2009 11:49:40 -0800 (PST) Subject: Moving from PHP to Python. Part Two References: Message-ID: <3510d1f6-9a88-47f5-8ffe-6895363ea845@g26g2000yqe.googlegroups.com> > > class Registry: > > ? ? ? ? data = {} > > ? ? ? ? def __init__(self,environ): > ? ? ? ? ? ? ? ? self.data['env'] = environ > ? ? ? ? ? ? ? ? self.data['init'] = 'hede' > > ? ? ? ? def set_entry(self,key,data): > ? ? ? ? ? ? ? ? self.data[key] = data > > ? ? ? ? def get_entry(self,key): > ? ? ? ? ? ? ? ? return self.data[key] > > ? ? ? ? def debug(self): > > ? ? ? ? ? ? ? ? r = '
        '
        > ? ? ? ? ? ? ? ? r += repr(self.data)
        > ? ? ? ? ? ? ? ? r += '
        ' > > ? ? ? ? ? ? ? ? return r > Just thought of something else: set_entry and get_entry are probably (in your example) better written as: def __getitem__(self, key): return self.data[key] def __setitem__(self, key, val): self.data[key] = val Assuming the syntax makes sense for the object. Then just use object[4] = 'adsfasfd' and object[4] syntax... Or as a getter/setter as per http://docs.python.org/library/functions.html#property Or depending on the use case for your class, just inherit from the built-in dict and get its functionality. >>> class Test(dict): def debug(self, whatever): print whatever >>> x = Test() >>> x[3] ='adfadsf' >>> x[3] 'adfadsf' >>> x.debug('test') test hth Jon. From rami.chowdhury at gmail.com Mon Dec 14 14:51:08 2009 From: rami.chowdhury at gmail.com (Rami Chowdhury) Date: Mon, 14 Dec 2009 11:51:08 -0800 Subject: pyZui - anyone know about this? In-Reply-To: <200912142102.30457.donn.ingle@gmail.com> References: <200912142102.30457.donn.ingle@gmail.com> Message-ID: <2f79f590912141151o7d8f1c19mb9b70a7428c3ef01@mail.gmail.com> On Mon, Dec 14, 2009 at 11:02, Donn wrote: > On Monday 14 December 2009 00:10:52 David Boddie wrote: >> Doesn't the author give his e-mail address at the end of the video? >> (Maybe I'm thinking of a different video.) >> > Yes, in a quick and garbled way :) I have yet to try to contact the author or > the youtube poster -- been too busy. > > I was hoping someone on the list may recognize what tools he was using, or > have some insight into how they would attack the problem. > I have pondered it from a wxPython pov, that being all I am experienced with > and I would have no chance of recreating that demo. Is it using some kind of > built-in QT/KDE voodoo? > Doesn't look like he's using KDE -- the filemanager he's using to choose images looks rather like Nautilus. I know KDE 4's Plasma framework has a ZUI and pretty good Python bindings, but I know very little about them other than that they exist. -------- Rami Chowdhury "Never assume malice when stupidity will suffice." -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) From nopsidy at gmail.com Mon Dec 14 14:58:26 2009 From: nopsidy at gmail.com (nopsidy) Date: Mon, 14 Dec 2009 13:58:26 -0600 Subject: OS independent way to check if a python app is running? In-Reply-To: <8c7f10c60912141136g658caf6vad0ee55d03bcbeb3@mail.gmail.com> References: <1260818045.9273.1350060453@webmail.messagingengine.com> <8c7f10c60912141136g658caf6vad0ee55d03bcbeb3@mail.gmail.com> Message-ID: one way is you can create a lock file, then when the program start you check to see if this lock file exists. -Alex Goretoy -------------- next part -------------- An HTML attachment was scrubbed... URL: From mwilson at the-wire.com Mon Dec 14 15:04:59 2009 From: mwilson at the-wire.com (Mel) Date: Mon, 14 Dec 2009 15:04:59 -0500 Subject: md5 strange error References: <315a7350-2af6-49d6-887f-10b8017f4d39@r31g2000vbi.googlegroups.com> Message-ID: Rami Chowdhury wrote: > On Mon, Dec 14, 2009 at 09:33, catalinfest at gmail.com > wrote: >> now i have Fedora 12 >> Now when i try to use md5 , python say : >> python >> Python 2.6.2 (r262:71600, Aug 21 2009, 12:22:21) >> [GCC 4.4.1 20090818 (Red Hat 4.4.1-6)] on linux2 >> Type "help", "copyright", "credits" or "license" for more information. >>>>> import md5 >> __main__:1: DeprecationWarning: the md5 module is deprecated; use >> hashlib instead >>>>> import md5 >> Why ? > As the message says: the md5 module is deprecated, and you should use > the hashlib module instead. I believe md5 is deprecated from Python > 2.6 onwards, which may be why you have not seen this message before > (Fedora 12 is the first Fedora to ship with Python 2.6). When this gets in the way (package builds, etc.,) you can get rid of it by invoking Python with a command line argument: python -Wignore::DeprecationWarning Mel. From sjdevnull at yahoo.com Mon Dec 14 15:06:15 2009 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: Mon, 14 Dec 2009 12:06:15 -0800 (PST) Subject: read text file byte by byte References: <4519638f-c62b-46f6-ba1e-619035d48036@j14g2000yqm.googlegroups.com> <00ae1204$0$15654$c3e8da3@news.astraweb.com> Message-ID: <2d2452b3-e2cf-4579-bea3-72a408d105f4@j19g2000yqk.googlegroups.com> On Dec 14, 1:57?pm, Dennis Lee Bieber wrote: > On Sun, 13 Dec 2009 22:56:55 -0800 (PST), "sjdevn... at yahoo.com" > declaimed the following in > gmane.comp.python.general: > > > > > > > > > The 3.1 documentation specifies that file.read returns bytes: > > > file.read([size]) > > ? ? Read at most size bytes from the file (less if the read hits EOF > > before obtaining size bytes). If the size argument is negative or > > omitted, read all data until EOF is reached. The bytes are returned as > > a string object. An empty string is returned when EOF is encountered > > immediately. (For certain files, like ttys, it makes sense to continue > > reading after an EOF is hit.) Note that this method may call the > > underlying C function fread() more than once in an effort to acquire > > as close to size bytes as possible. Also note that when in non- > > blocking mode, less data than was requested may be returned, even if > > no size parameter was given. > > > Does it need fixing? > > ? ? ? ? I'm still running 2.5 (Maybe next spring I'll see if all the third > party libraries I have exist in 2.6 versions)... BUT... > > ? ? ? ? "... are returned as a string object..." Aren't "strings" in 3.x now > unicode? Which would imply, to me, that the interpretation of the > contents will not be plain bytes. I'm not even concerned (yet) about how the data is interpreted after it's read. First I'm trying to clarify what exactly gets read. The post I was replying to said "In Python 3.x, f.read(1) will read one character, which may be more than one byte depending on the encoding." That seems at odds with the documentation saying "Read at most size bytes from the file"--the fact that it's documented to read "size" bytes rather than "size" (possibly multibyte) characters is emphasized by the later language saying that the underlying C fread() call may be called enough times to read as close to size bytes as possible. If the poster I was replying to is correct, it seems like a documentation update is in order. As a long-time programmer, I would be very surprised to make a call to f.read(X) and have it return more than X bytes if I hadn't read this here. From klaussfreire at gmail.com Mon Dec 14 15:12:11 2009 From: klaussfreire at gmail.com (Klauss) Date: Mon, 14 Dec 2009 12:12:11 -0800 (PST) Subject: a huge shared read-only data in parallel accesses -- How? multithreading? multiprocessing? References: Message-ID: <6fdd9088-7418-488a-9868-abe6446cb388@r5g2000yqb.googlegroups.com> On Dec 11, 11:00?am, Antoine Pitrou wrote: > I was going to suggest memcached but it probably serializes non-atomic > types. Atomic as well. memcached communicates through sockets[3] (albeit possibly unix sockets, which are faster than TCP ones). multiprocessing has shared memory schemes, but does a lot of internal copying (uses ctypes)... and are particularly unhelpful when your shared data is highly structured, since you can't share objects, only primitive types. I finished a patch that pushes reference counters into packed pools. It has lots of drawbacks, but manages to solve this particular problem, if the data is prominently non-numeric (ie: lists and dicts, as mentioned before). Of the drawbacks, perhaps the bigger is a bigger memory footprint - yep... I don't believe there's anything that can be done to change that. It can be optimized, to make the overhead a little less though. This test code[1] consumes roughly 2G of RAM on an x86_64 with python 2.6.1, with the patch, it *should* use 2.3G of RAM (as specified by its output), so you can see the footprint overhead... but better page sharing makes it consume about 6 times less - roughly 400M... which is the size of the dataset. Ie: near-optimal data sharing. This patch[2] has other optimizations intermingled - if there's interest in the patch without those (which are both unproven and nonportable) I could try to separate them. I will have to, anyway, to upload for inclusion into CPython (if I manage to fix the shortcomings, and if it gets approved). The most important shortcomings of the refcount patch are: 1) Tripled memory overhead of reference counting. Before, it was a single Py_ssize_t per object. Now, it's two pointers plus the Py_ssize_t. This could perhaps be optimized (by getting rid of the arena pointer, for instance). 2) Increased code output for Py_INCREF/DECREF. It's small, but it adds up to a lot. Timings on test_decimal.py (a small numeric benchmark I use, which might not be representative at all) shows a 10% performance loss in CPU time. Again, this might be optimized with a lot of work and creativity. 3) Breaks binary compatibility, and in weird cases source compatibility with extension modules. PyObject layout is different, so statically-initialized variables need to stick to using CPython's macros (I've seen cases when they don't), and code should use Py_REFCNT () for accessing the refcount, but many just do ob->ob_refcnt, which will break with the patch. 4) I'm also not really sure (haven't tested) what happens when CPython runs out of memory - I tried real hard not to segfault, even recover nicely, but you know how hard that is... [3] http://code.google.com/p/memcached/wiki/FAQ#How_does_it_compare_to_a_server_local_cache?_(PHP%27s_APC,_mm [2] http://www.deeplayer.com/claudio/misc/Python-2.6.1-refcount.patch [1] test code below import time from multiprocessing import Pool def usoMemoria(): import os import subprocess pid = os.getpid() cmd = "ps -o vsz=,rss=,share= -p %s --ppid %s" % (pid,pid) p = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE) info = p.stdout.readlines() s = sum( int(r) for v,r,s in map(str.split,map(str.strip, info)) ) return s def f(_): return sum(int(x) for d in huge_global_data for x in d if x != "state") # my sofisticated formula goes here if __name__ == '__main__': huge_global_data = [] for i in xrange(500000): d = {} d[str(i)] = str(i*10) d[str(i+1)] = str(i) d["state"] = 3 huge_global_data.append(d) p = Pool(7) res= list(p.map(f, xrange(20))) print "%.2fM" % (usoMemoria() / 1024.0) From python at bdurham.com Mon Dec 14 15:32:16 2009 From: python at bdurham.com (python at bdurham.com) Date: Mon, 14 Dec 2009 15:32:16 -0500 Subject: OS independent way to check if a python app is (already) running? In-Reply-To: References: <1260818045.9273.1350060453@webmail.messagingengine.com> <8c7f10c60912141136g658caf6vad0ee55d03bcbeb3@mail.gmail.com> Message-ID: <1260822736.22419.1350074313@webmail.messagingengine.com> Alex, > one way is you can create a lock file, then when the program start you check to see if this lock file exists. Makes sense - thanks! Regards, Malcolm -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at mrabarnett.plus.com Mon Dec 14 15:35:07 2009 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 14 Dec 2009 20:35:07 +0000 Subject: OS independent way to check if a python app is running? In-Reply-To: <1260818045.9273.1350060453@webmail.messagingengine.com> References: <1260818045.9273.1350060453@webmail.messagingengine.com> Message-ID: <4B26A17B.3000004@mrabarnett.plus.com> python at bdurham.com wrote: > Is there an os independent way to check if a python app is running? > > Goal: I have a server program based on cherrypy that I only want to have > running once. If a system administrator accidentally attempts to run > this program more than once, I would like the 2nd instance of the > program to detect that its already running and exit. > You could use lockfile: http://pypi.python.org/pypi/lockfile/0.7 If a certain file exists and is locked, then the app is already running. From python at bdurham.com Mon Dec 14 15:35:58 2009 From: python at bdurham.com (python at bdurham.com) Date: Mon, 14 Dec 2009 15:35:58 -0500 Subject: OS independent way to check if a python app is running? In-Reply-To: <8c7f10c60912141136g658caf6vad0ee55d03bcbeb3@mail.gmail.com> References: <1260818045.9273.1350060453@webmail.messagingengine.com> <8c7f10c60912141136g658caf6vad0ee55d03bcbeb3@mail.gmail.com> Message-ID: <1260822958.23051.1350074671@webmail.messagingengine.com> Simon, > if True: > print "I'm running." > > ;-) LOL! Yes, I should of worded my original post better (meant to say "... if a python app is already running". Enjoyed your post anyway - I'm still laughing :) Cheers, Malcolm From python at bdurham.com Mon Dec 14 15:39:55 2009 From: python at bdurham.com (python at bdurham.com) Date: Mon, 14 Dec 2009 15:39:55 -0500 Subject: What type of info do you capture about a user's environment for debugging? Message-ID: <1260823195.23583.1350075123@webmail.messagingengine.com> We're preparing to release a commercial software product based on Python. When a customer reports problems with our software, we would like to capture as much information about their environment as possible while being respectful of privacy concerns. The info we capture will be displayed to the user for review and optional submission to our support team. Here's what we've come up with so far: - platform module info - locale module info - os.environ (selected info) - sys.argv (application path and command line arguements) Free disk space and write status for the following paths: - application folder - startup folder (which may be different than application folder) - temp path - user path ("My Documents", "Home") Information captured via our browser interface - display resolution - browser version Anyone have any additional suggestions or feedback? Thanks! Malcolm -------------- next part -------------- An HTML attachment was scrubbed... URL: From deets at nospam.web.de Mon Dec 14 15:48:44 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 14 Dec 2009 21:48:44 +0100 Subject: OS independent way to check if a python app is running? In-Reply-To: References: <1260818045.9273.1350060453@webmail.messagingengine.com> Message-ID: <7onmlcF3qrvc3U1@mid.uni-berlin.de> MRAB schrieb: > python at bdurham.com wrote: >> Is there an os independent way to check if a python app is running? >> >> Goal: I have a server program based on cherrypy that I only want to >> have running once. If a system administrator accidentally attempts to >> run this program more than once, I would like the 2nd instance of the >> program to detect that its already running and exit. >> > You could use lockfile: http://pypi.python.org/pypi/lockfile/0.7 > > If a certain file exists and is locked, then the app is already running. Not only exists, he should also use the OS' locking mechanisms. The file could otherwise be stale. We use this: import platform is_windows = False if platform.system() == 'Windows': is_windows = True import os class LockFileCreationException(Exception): pass class LockFile(object): def __init__(self, name, fail_on_lock=False, cleanup=True): self.name = name self.cleanup = cleanup try: self.fd = os.open(name, os.O_WRONLY | os.O_CREAT | os.O_APPEND) except OSError, e: if e[0] == 2: raise LockFileCreationException() self.file = os.fdopen(self.fd, "w") if is_windows: lock_flags = msvcrt.LK_LOCK else: lock_flags = fcntl.LOCK_EX if fail_on_lock: if is_windows: lock_flags = msvcrt.LK_NBLCK else: lock_flags |= fcntl.LOCK_NB try: if is_windows: msvcrt.locking(self.file.fileno(), lock_flags, 1) else: fcntl.flock(self.file, lock_flags) except IOError, e: if e[0] == 11: raise LockObtainException() raise def __enter__(self): return self.file def __exit__(self, unused_exc_type, unused_exc_val, unused_exc_tb): self.file.close() # we are told to cleanup after ourselves, # however it might be that another process # has done so - so we don't fail in that # case. if self.cleanup: try: os.remove(self.name) except OSError, e: if not e[0] == 2: raise Diez From tjreedy at udel.edu Mon Dec 14 15:51:42 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 14 Dec 2009 15:51:42 -0500 Subject: Moving from PHP to Python. Part Two In-Reply-To: <3510d1f6-9a88-47f5-8ffe-6895363ea845@g26g2000yqe.googlegroups.com> References: <3510d1f6-9a88-47f5-8ffe-6895363ea845@g26g2000yqe.googlegroups.com> Message-ID: On 12/14/2009 2:49 PM, Jon Clements wrote: >> >> class Registry: >> >> data = {} >> >> def __init__(self,environ): >> self.data['env'] = environ >> self.data['init'] = 'hede' >> >> def set_entry(self,key,data): >> self.data[key] = data >> >> def get_entry(self,key): >> return self.data[key] >> >> def debug(self): >> >> r = '
        '
        >>                  r += repr(self.data)
        >>                  r += '
        ' >> >> return r Since this would be a singleton, skip it and just make a module 'registry'__ that you import everywhere Include the following function: def _debug(): r = ['
        ']
           d = {k:v for k,v in globals().items() if not k.startswith('_')}
           r += repr(d)
           r += '
        ' return ' '.join(r) Then a = 3 b = 'ab' print(_debug()) prints
         { ' a ' :   3 ,   ' b ' :   ' a b ' } < / p r e >
        
         From outside the module, registry._debug() will produce the string.
        
        Terry Jan Reedy
        
        
        
        
        From nobody at nowhere.com  Mon Dec 14 16:09:52 2009
        From: nobody at nowhere.com (Nobody)
        Date: Mon, 14 Dec 2009 21:09:52 +0000
        Subject: read text file byte by byte
        References: 
        	
        	
        	<4519638f-c62b-46f6-ba1e-619035d48036@j14g2000yqm.googlegroups.com>
        	<00ae1204$0$15654$c3e8da3@news.astraweb.com>
        	
        	
        Message-ID: 
        
        On Sun, 13 Dec 2009 22:56:55 -0800, sjdevnull at yahoo.com wrote:
        
        > The 3.1 documentation specifies that file.read returns bytes:
        
        > Does it need fixing?
        
        There are no file objects in 3.x. The file() function no longer
        exists. The return value from open(), will be an instance of
        _io. depending upon the mode, e.g. _io.TextIOWrapper for 'r',
        _io.BufferedReader for 'rb', _io.BufferedRandom for 'w+b', etc.
        
        	http://docs.python.org/3.1/library/io.html
        
        io.IOBase.read() doesn't exist, io.RawIOBase.read(n) reads n bytes,
        io.TextIOBase.read(n) reads n characters.
        
        
        
        
        From philip at semanchuk.com  Mon Dec 14 16:11:40 2009
        From: philip at semanchuk.com (Philip Semanchuk)
        Date: Mon, 14 Dec 2009 16:11:40 -0500
        Subject: What type of info do you capture about a user's environment for
        	debugging? 
        In-Reply-To: <1260823195.23583.1350075123@webmail.messagingengine.com>
        References: <1260823195.23583.1350075123@webmail.messagingengine.com>
        Message-ID: 
        
        
        On Dec 14, 2009, at 3:39 PM, python at bdurham.com wrote:
        
        > We're preparing to release a commercial software product based on
        > Python. When a customer reports problems with our software, we
        > would like to capture as much information about their environment
        > as possible while being respectful of privacy concerns. The info
        > we capture will be displayed to the user for review and optional
        > submission to our support team.
        > Here's what we've come up with so far:
        > - platform module info
        > - locale module info
        > - os.environ (selected info)
        > - sys.argv (application path and command line arguements)
        > Free disk space and write status for the following paths:
        > - application folder
        > - startup folder (which may be different than application folder)
        > - temp path
        > - user path ("My Documents", "Home")
        > Information captured via our browser interface
        > - display resolution
        > - browser version
        > Anyone have any additional suggestions or feedback?
        
        Python version? =)
        
        Also the contents of site-packages might be useful if you can get that.
        
        
        
        
        
        From steve at REMOVE-THIS-cybersource.com.au  Mon Dec 14 16:22:06 2009
        From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
        Date: 14 Dec 2009 21:22:06 GMT
        Subject: Seek support for new slice syntax PEP.
        References: <8e5054b1-8424-4633-a52e-1d9dcd1637b6@c34g2000yqn.googlegroups.com>
        	
        Message-ID: <00b03121$0$15654$c3e8da3@news.astraweb.com>
        
        On Mon, 14 Dec 2009 13:40:38 -0500, Colin W. wrote:
        
        > Yes, we know that PEP 3003 applies but I see no harm in discussing
        > possible enhancements.
        
        You bored? Looking for something to do? 
        
        I've lost all enthusiasm for discussing language enhancements, regardless 
        of whether I'm for or against the change, knowing that there's no way it 
        could be added to the language, and when the Python moratorium ends the 
        discussion will just happen all over again.
        
        
        -- 
        Steven
        
        
        From pavlovevidence at gmail.com  Mon Dec 14 16:23:06 2009
        From: pavlovevidence at gmail.com (Carl Banks)
        Date: Mon, 14 Dec 2009 13:23:06 -0800 (PST)
        Subject: Seek support for new slice syntax PEP.
        References: <8e5054b1-8424-4633-a52e-1d9dcd1637b6@c34g2000yqn.googlegroups.com>
        Message-ID: 
        
        On Dec 14, 10:03?am, Dave  wrote:
        > Just as sets may now be written as {3,'hi'}, I propose that slices
        > should be available using [start:end] syntax. ?Following example comes
        > from projecteuler.net problem 166. ?The Numeric community would also
        > like this, as would the general python user. ?The slice notation would
        > require one ":" between the brackets to differentiate it from a list,
        > which is similar to the set notation requirement that disambiguates it
        > from a dictionary.
        >
        > Several times now I've wanted python slice notation. ?Perhaps I'll
        > write a Python Enhancement Proposal. ?I stored slices of vector array
        > entries to add
        >
        > edge = 4
        > indexes = []
        > n = edge
        > nn = n**2
        > for i in range(edge):
        > ? ? indexes.extend([
        > ? ? ? ? slice(i*n,(i+1)*n,1), ? ? ? # rows
        > ? ? ? ? slice(i,nn,n), ? ? ? ? ? ? ?# cols
        > ? ? ? ? ])
        >
        > row_slices = indexes[0::2]
        > col_slices = indexes[1::2]
        > slash = slice(n-1,n*(n-1)+1,n-1)
        > backslash = slice(0,nn,n+1)
        >
        > Which could have been written in a manner completely consistent with
        > other python shorthand notations and for which python "cannot
        > possibly" use the notation for some other purpose,
        >
        > edge = 4
        > indexes = []
        > n = edge
        > nn = n**2
        > for i in range(edge):
        > ? ? indexes.extend([
        > ? ? ? ? [i*n: (i+1)*n] ? ? ? ? ? ? ? ? ?# rows
        > ? ? ? ? [i: nn: n], ? ? ? ? ? ? ? ? ? ? ?# cols
        > ? ? ? ? ])
        >
        > row_slices = indexes[0::2]
        > col_slices = indexes[1::2]
        > slash = [n-1: n*(n-1)+1: n-1]
        > backslash = [0: nn: n+1]
        
        -1
        
        Explicit creation of slice objects is an uncommon need and there is no
        reason to support it with its own syntax.
        
        I'd agree with Terry Reedy that range/xrange is far more commonly used
        than slice objects, and if a floating slice syntax were ever added to
        Python it ought to be used for range.
        
        
        If you need to use a lot of slice objects you can lower your code
        footprint by defining a helper class like this (adapt as needed):
        
        class SliceCreator(object):
            def __getitem__(self,loc):
                if not isinstance(loc,slice):
                    raise TypeError
                return loc
        slc = SliceCreator()
        
        slash = slc[n-1: n*(n-1)+1: n-1]
        
        
        It might have been a reasonable idea for slice (and, perhaps, range)
        to use slice notation rather than a function call, on the thinking
        that the notational convenience outweighs the fact that you're not
        actually getting an item, but it's too late for that.
        
        
        Carl Banks
        
        
        From nobody at nowhere.com  Mon Dec 14 16:27:45 2009
        From: nobody at nowhere.com (Nobody)
        Date: Mon, 14 Dec 2009 21:27:45 +0000
        Subject: read text file byte by byte
        References: 
        	
        	
        	<4519638f-c62b-46f6-ba1e-619035d48036@j14g2000yqm.googlegroups.com>
        	
        	
        	
        Message-ID: 
        
        On Mon, 14 Dec 2009 03:14:11 +0000, MRAB wrote:
        
        >>> 	You originally stated that you want to "scramble" the bytes -- if
        >>> you mean to implement some sort of encryption algorithm you should know
        >>> that most of them work in blocks as the "key" is longer than one byte.
        >> 
        >> Block ciphers work in blocks. Stream ciphers work on bytes, regardless of
        >> the length of the key.
        >> 
        > It's still more efficient to read in blocks, even if you're going to
        > process the bytes one at a time.
        
        That's fine for a file. If you're reading from a pipe, socket, etc, you
        typically want to take what you can get when you can get it (although this
        is easier said than done in Python), rather than waiting for a complete
        "block". This is often a primary reason for choosing a stream cipher over
        a block cipher, as it eliminates the need to add and remove padding for
        intermittent data flows.
        
        
        
        From solipsis at pitrou.net  Mon Dec 14 16:30:00 2009
        From: solipsis at pitrou.net (Antoine Pitrou)
        Date: Mon, 14 Dec 2009 21:30:00 +0000 (UTC)
        Subject: Dangerous behavior of list(generator)
        References: 
        	
        	<20091213143521.2549.845539319.divmod.xquotient.731@localhost.localdomain>
        	<4B2652AB.7080501@egenix.com>
        	<20091214152109.2667.401778734.divmod.xquotient.105@localhost.localdomain>
        Message-ID: 
        
        Le Mon, 14 Dec 2009 15:21:09 +0000, exarkun a ?crit?:
        > 
        > I'm asking about why the behavior of a StopIteration exception being
        > handled from the `expression` of a generator expression to mean "stop
        > the loop" is accepted by "the devs" as acceptable.
        
        It's not "accepted as acceptable", it's just a side effect of how various 
        means of iterating (including for loops and generators) are implemented 
        in CPython.
        Seeing how it doesn't seem to prevent or promote any useful programming 
        idiom, there was no incentive to either 1) codify it as official spec or 
        2) change it.
        
        In other words, it should be considered undefined behaviour, and perhaps 
        other Python implementations behave differently.
        
        Regards
        
        Antoine.
        
        
        
        From phlip2005 at gmail.com  Mon Dec 14 16:31:26 2009
        From: phlip2005 at gmail.com (Phlip)
        Date: Mon, 14 Dec 2009 13:31:26 -0800 (PST)
        Subject: mock any instance
        Message-ID: <3c195903-108d-4780-892e-366f422f014c@v30g2000yqm.googlegroups.com>
        
        Pythonistas:
        
        One important design principle is "construction encapsulation". That's
        where nobody creates anything, they always use things passed to them.
        
        Without this principle, when I need to mock the encapsulated item,
        some mock libraries provide an "any instance" facility.
        
        For example, here's a mock on one method of only one object:
        
           object = Thang()
           object.method = Mock()
           object.method()  #  <--  calls the mock, not the real method
        
        I need to mock the method on any instance spawned by a given class:
        
           Thang.method = MockAnyInstance()
           object = Thang()
           object.method()  #  <--  calls the mock, not the real method
        
        That will avoid "cutting a hole in the bulkhead" just to get to the
        'object = Thang()' line, to let me spoof out the Thang.
        
        Does anyone have any idea how to do that with the good-old Mocker
        here?
        
          http://python-mock.sourceforge.net/
        
        if I should use a different mocker, I would prefer it behave like that
        mock, for aesthetic reasons, and also to avoid the need to replace all
        our existing Mocks with a new one, following the rule that we should
        not use too many classes to do the same thing (DRY).
        
        --
          Phlip
          http://c2.com/cgi/wiki?ZeekLand
        
        
        From nobody at nowhere.com  Mon Dec 14 16:45:33 2009
        From: nobody at nowhere.com (Nobody)
        Date: Mon, 14 Dec 2009 21:45:33 +0000
        Subject: Seek support for new slice syntax PEP.
        References: <8e5054b1-8424-4633-a52e-1d9dcd1637b6@c34g2000yqn.googlegroups.com>
        Message-ID: 
        
        On Mon, 14 Dec 2009 10:03:16 -0800, Dave wrote:
        
        > Just as sets may now be written as {3,'hi'}, I propose that slices
        > should be available using [start:end] syntax.  Following example comes
        > from projecteuler.net problem 166.  The Numeric community would also
        > like this, as would the general python user.  The slice notation would
        > require one ":" between the brackets to differentiate it from a list,
        > which is similar to the set notation requirement that disambiguates it
        > from a dictionary.
        > 
        > Several times now I've wanted python slice notation.  Perhaps I'll
        > write a Python Enhancement Proposal.
        
        Would it suffice to add the equivalent of numpy.s_ as a builtin?
        
        	> from numpy import s_
        	> s_[1:2:3]
        	slice(1, 2, 3)
        	> s_[1:2:3, ..., 4:5]
        	(slice(1, 2, 3), Ellipsis, slice(4, 5, None))
        
        Or would it be possible to define "slice" itself so that it implements
        __getitem__ and __getslice__?
        
        
        
        From steve at REMOVE-THIS-cybersource.com.au  Mon Dec 14 16:53:38 2009
        From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
        Date: 14 Dec 2009 21:53:38 GMT
        Subject: insert unique data in a list
        References: <4b251840$0$30959$4fafbaef@reader3.news.tin.it>
        	<4b252b1b$0$644$4fafbaef@reader4.news.tin.it>
        	
        	
        	<07c342ef-fd02-4d6e-ab23-6effdd0598fc@b36g2000prf.googlegroups.com>
        	<4b267234$0$8867$4fafbaef@reader5.news.tin.it>
        Message-ID: <00b03884$0$15654$c3e8da3@news.astraweb.com>
        
        On Mon, 14 Dec 2009 17:13:24 +0000, mattia wrote:
        
        > Il Sun, 13 Dec 2009 21:17:28 -0800, knifenomad ha scritto:
        > 
        >> On 12?14?, ??12?42?, Steven D'Aprano
        >>  wrote:
        >>> On Sun, 13 Dec 2009 17:19:17 -0800, knifenomad wrote:
        >>> > this makes the set type hashable.
        >>>
        >>> > class Set(set):
        >>> > ? ? __hash__ = lambda self: id(self)
        >>>
        >>> That's a *seriously* broken hash function.
        >>>
        >>> >>> key = "voila"
        >>> >>> d = { Set(key): 1 }
        >>> >>> d
        >>>
        >>> {Set(['i', 'a', 'l', 'o', 'v']): 1}>>> d[ Set(key) ]
        >>>
        >>> Traceback (most recent call last):
        >>> ? File "", line 1, in 
        >>> KeyError: Set(['i', 'a', 'l', 'o', 'v'])
        >>>
        >>> --
        >>> Steven
        >> 
        >> of course it is broken as long as it uses it's instance id. i added
        >> this to notify that unhashable can become hashable implementing
        >> __hash__ inside the class. which probably set to None by default.
        > 
        > Ok, nice example, but I believe that using id() as the hash function can
        > lead to unexpected collisions.
        
        No, you have that backwards. Using id() as the hash function means that 
        equal keys will hash unequal -- rather than unexpected collisions, it 
        leads to unexpected failure-to-collide-when-it-should-collide.
        
        And it isn't a "nice example", it is a terrible example. 
        
        Firstly, the example fails to behave correctly. It simply doesn't work as 
        advertised.
        
        Secondly, and much worse, it encourages people to do something dangerous 
        without thinking about the consequences. If it is so easy to hash mutable 
        objects, why don't built-in lists and sets don't have a __hash__ method? 
        Do you think that the Python developers merely forgot?
        
        No, there is good reason why mutable items shouldn't be used as keys in 
        dicts or in sets, and this example simply papers over the reasons why and 
        gives the impression that using mutable objects as keys is easy and safe 
        when it is neither.
        
        Using mutable objects as keys or set elements leads to surprising, 
        unexpected behaviour and hard-to-find bugs. Consider the following set 
        with lists as elements:
        
        L = [1, 2]
        s = Set()  # set that allows mutable elements
        s.add(L)
        s.add([1, 2, 3])
        
        So far so good. But what should happen now?
        
        L.append(3)
        
        The set now has two equal elements, which breaks the set invariant that 
        it has no duplicates.
        
        Putting the problem of duplicates aside, there is another problem:
        
        L = [1, 2]
        s = Set([L])
        L.append(3)
        
        There are two possibilities: either the hash function of L changes when 
        the object changes, or it doesn't. Suppose it changes. Then the hash of L 
        after the append will be different from the hash of L before the append, 
        and so membership testing (L in s) will fail.
        
        Okay, suppose we somehow arrange matters so that the hash of the object 
        doesn't change as the object mutates. This will solve the problem above: 
        we can mutate L as often as we like, and L in s will continue to work 
        correctly. But now the hash of an object doesn't just depend on it's 
        value, but on its history. That means that two objects which are 
        identical can hash differently, and we've already seen this is a problem.
        
        There is one final approach which could work: we give the object a 
        constant hash function, so that all objects of that type hash 
        identically. This means that the performance of searches and lookups in 
        sets and dicts will fall to that of lists. There is no point in paying 
        all the extra overhead of a dict to get behaviour as slow, or slower, 
        than a list.
        
        In other words, no matter what you do, using mutable objects as keys or 
        set elements leads to serious problems that need to be dealt with. It 
        simply isn't true that all you need to do to make mutable objects usable 
        in dicts or sets is to add a hash function. That part is trivial.
        
        
        
        -- 
        Steven
        
        
        From pavlovevidence at gmail.com  Mon Dec 14 17:05:24 2009
        From: pavlovevidence at gmail.com (Carl Banks)
        Date: Mon, 14 Dec 2009 14:05:24 -0800 (PST)
        Subject: Dangerous behavior of list(generator)
        References:  
        	
        	<20091213143521.2549.845539319.divmod.xquotient.731@localhost.localdomain>
        	<4B2652AB.7080501@egenix.com>
        	
        Message-ID: <07356731-e5be-43cd-8328-6ef6dc84f155@p23g2000vbl.googlegroups.com>
        
        On Dec 14, 7:21?am, exar... at twistedmatrix.com wrote:
        > Note, I know *why* the implementation leads to this behavior. ?I'm
        > asking why "the devs" *accept* this.
        
        As noted, the problem isn't with generators but with iteration
        protocol.  The devs "allowed" this because it was a necessary evil for
        correct functionality.  As the system is set up it can't discriminate
        between a legitimate and a spurrious StopIteration.  (Which is why
        Steven and others called you out for suggesting that the compiler has
        to read your mind.)
        
        However, as far as I'm concerned there is no reasonable argument that
        this behavior is good.  So how, hypothetically, would one go about
        fixing it, short of ripping out and replacing the existing machinery?
        
        The first argument is that StopIteration has no place within a
        generator expression.  Therefore a generator expression (but not a
        generator function) could deliberately catch StopIteration and raise a
        different exception.
        
        I don't like it, though: who says that StopIteration has no place
        within a generator expression?  Currently it's possible to do
        something like this to terminate a genexp early, and I won't the one
        saying you shouldn't do it.
        
        def stop(): raise StopIteration
        
        list(x or stop() for x in stream)
        
        (Though personally I'd bite the bullet and write it as a generator
        function).
        
        What else?  The way I see it, when you throw StopIteration you are
        trying to stop a specific generator.  Therefore StopIteration should
        (somehow) contain a reference to the generator that it's being applied
        to.  Perhaps it can be obtained by crawling ths stack, which shouldn't
        be a significant penalty (it'd be only called once per iteration, and
        most of the time it'd be only one or two frames up).  The looping
        logic within Python should check whether the reference matches the
        object it's iterating over; if not it raises a LeakyLoopException or
        something like that.
        
        I haven't thought this out though, I'm just kind of throwing this out
        there.  Any issues?
        
        
        But to answer your question, I think "simple is better than complex"
        rules the day.  Right now StopIteration stops an iteration, simple as
        that.  Any fix would add complexity.
        
        
        Carl Banks
        
        
        From ethan at stoneleaf.us  Mon Dec 14 17:25:31 2009
        From: ethan at stoneleaf.us (Ethan Furman)
        Date: Mon, 14 Dec 2009 14:25:31 -0800
        Subject: setup.py and PyPI
        In-Reply-To: <31B30751-788A-429F-96C1-9FBA21242CE9@semanchuk.com>
        References: <4B267023.60300@stoneleaf.us>	<84964F02-513C-4D40-826B-67B66E9EAF79@semanchuk.com>	<4B267D48.4010501@stoneleaf.us>
        	<31B30751-788A-429F-96C1-9FBA21242CE9@semanchuk.com>
        Message-ID: <4B26BB5B.6070707@stoneleaf.us>
        
        Philip Semanchuk wrote:
        > 
        > On Dec 14, 2009, at 1:00 PM, Ethan Furman wrote:
        > 
        >> Philip Semanchuk wrote:
        >>
        >>> On Dec 14, 2009, at 12:04 PM, Ethan Furman wrote:
        >>>
        >>>> Greetings!
        >>>>
        >>>> I'm using Python 2.5 on Windows XP, and trying to get the upload   
        >>>> portion of setup.py to work.  According to what I have found, I  
        >>>> can  put my info into a .pypirc file to have the process pick up  
        >>>> my  username/password and upload the files.
        >>>>
        >>>> I have tried putting this file into the same folder I'm running   
        >>>> setup.py from, into my home folder (USERPROFILE, I think) -- and  
        >>>> the  really frustrating part is that it worked a couple times (but  
        >>>> maybe  that was from my home computer) but mostly it does not.
        >>>
        >>> When it fails, how does it fail?
        >>
        >>
        >> python setup.py sdist bdist --format wininst upload
        >>
        >> [snip]
        >>
        >> running upload
        >> Submitting dist\dbf-0.87.7.zip to http://pypi.python.org/pypi
        >> Upload failed (401): You must be identified to edit package  information
        > 
        > 
        > Looks like there's known problems with this under Windows that might  
        > affect your version of Python, depending on which version you have.
        > http://bugs.python.org/issue1741
        > 
        > Setting a HOME environment variable to point to wherever you have  your 
        > .pypirc file might help.
        > 
        > Hope this helps
        > P
        
        The HOME variable did it!
        
        Many, many thanks!!
        
        ~Ethan~
        
        
        From gagsl-py2 at yahoo.com.ar  Mon Dec 14 17:39:35 2009
        From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina)
        Date: Mon, 14 Dec 2009 19:39:35 -0300
        Subject: Parsing html with Beautifulsoup
        References: <20091210091519.GA14175@sun.ac.za>
        	
        	<4B21EF06.1040505@sun.ac.za>
        	
        	<20091214065834.GA18269@sun.ac.za>
        Message-ID: 
        
        En Mon, 14 Dec 2009 03:58:34 -0300, Johann Spies 
        escribi?:
        > On Sun, Dec 13, 2009 at 07:58:55AM -0300, Gabriel Genellina wrote:
        
        >> cell.findAll(text=True) returns a list of all text nodes inside a
        >>  cell; I preprocess all \n and   in each text node, and
        >> join them all. lines is a list of lists (each entry one cell), as
        >> expected by the csv module used to write the output file.
        >
        > I have struggled a bit to find the documentation for (text=True).
        > Most of documentation for Beautifulsoup I saw mostly contained some
        > examples without explaining what the options do.  Thanks for your
        > explanation.
        
        See  
        http://www.crummy.com/software/BeautifulSoup/documentation.html#arg-text
        
        > As far as I can see there was no documentation installed with the
        > debian package.
        
        BeautifulSoup is very small - a single .py file, no dependencies. The  
        whole documentation is contained in the above linked page.
        
        -- 
        Gabriel Genellina
        
        
        
        From steve at REMOVE-THIS-cybersource.com.au  Mon Dec 14 17:48:34 2009
        From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
        Date: 14 Dec 2009 22:48:34 GMT
        Subject: Dangerous behavior of list(generator)
        References: 
        Message-ID: <00b04565$0$15654$c3e8da3@news.astraweb.com>
        
        On Mon, 14 Dec 2009 14:31:44 +0000, exarkun wrote:
        
        > On 06:46 am, tjreedy at udel.edu wrote:
        >>On 12/13/2009 10:29 PM, exarkun at twistedmatrix.com wrote:
        >>>Doesn't matter. Sometimes it makes sense to call it directly.
        >>
        >>It only makes sense to call next (or .__next__) when you are prepared to
        >>explicitly catch StopIteration within a try..except construct. You did
        >>not catch it, so it stopped execution.
        >>
        >>Let me repeat: StopIteration is intended only for stopping iteration.
        >>Outside that use, it is a normal exception with no special meaning.
        > 
        > You cut out the part of my message where I wrote that one might have
        > forgotten the exception handling code that you posit is required, and
        > that the current behavior makes debugging this situation unnecessarily
        > challenging.
        
        I don't see why you think this is any more challenging to debug than any 
        other equivalent bug. If anything I would think it was easier to debug: 
        if the problem is that you get a StopIteration traceback, well that's 
        easy and straightforward, and if the problem is that you don't (and 
        consequently you end up with fewer items in the list than you expect), 
        the obvious debugging technique is to build the list by hand and inspect 
        each item before adding it to the list:
        
        L = []
        for i, item in enumerate(iterable):
            print i, item, 
            value = item()  # raises StopIteration
            print value
            L.append(value)
        
        That will expose the StopIteration exception and reveal the problem.
        
        But even if I have missed something, and it is a challenging problem to 
        debug, oh well. It should be a quite unusual situation to come across.
        
        
        -- 
        Steven
        
        
        From gervaz at gmail.com  Mon Dec 14 17:52:31 2009
        From: gervaz at gmail.com (mattia)
        Date: 14 Dec 2009 22:52:31 GMT
        Subject: print format
        Message-ID: <4b26c1af$0$8863$4fafbaef@reader5.news.tin.it>
        
        Hi all, I wanto to print just the first 5 characters of a string, why 
        this doesn't work (py3.1)?
        >>> print("{0:5}".format("123456789"))
        123456789
        I know I could use print("123456789"[:5]), yeah it's a stupid example, 
        but isn't format for string formatting?
        
        Thanks, Mattia
        
        
        From rhodri at wildebst.demon.co.uk  Mon Dec 14 18:11:27 2009
        From: rhodri at wildebst.demon.co.uk (Rhodri James)
        Date: Mon, 14 Dec 2009 23:11:27 -0000
        Subject: Seek support for new slice syntax PEP.
        In-Reply-To: 
        References: <8e5054b1-8424-4633-a52e-1d9dcd1637b6@c34g2000yqn.googlegroups.com>
        	
        Message-ID: 
        
        On Mon, 14 Dec 2009 18:40:38 -0000, Colin W.   
        wrote:
        
        > If your scheme flies, would it be practicable to use the same syntax
        > as a range generator?
        >
        > range(i, j, k)  => i:j:k
        >
        > so range(10, 2) => :10:2
        >
        > i.e. we could write for i in :10:2:
        >
        > or the more common:
        > range(10)  => :10
        
        Ugh.  Magic characters.  Let's not.
        
        -- 
        Rhodri James *-* Wildebeest Herder to the Masses
        
        
        From phlip2005 at gmail.com  Mon Dec 14 18:14:49 2009
        From: phlip2005 at gmail.com (Phlip)
        Date: Mon, 14 Dec 2009 15:14:49 -0800 (PST)
        Subject: mock any instance
        References: <3c195903-108d-4780-892e-366f422f014c@v30g2000yqm.googlegroups.com>
        Message-ID: <759e7608-070e-4823-8954-c932f9a6f56b@g4g2000pri.googlegroups.com>
        
        > ? ?Thang.method = MockAnyInstance()
        > ? ?object = Thang()
        > ? ?object.method() ?# ?<-- ?calls the mock, not the real method
        
        The mocker here...
        
          http://www.voidspace.org.uk/python/mock/
        
        ...has @patch and @patch_object directives that might do it.
        
        (Luv it when you skate off the end of a language's original
        definition, huh?)
        
        > --
        > ? Phlip
        > ?http://c2.com/cgi/wiki?ZeekLand
        
        
        
        From gervaz at gmail.com  Mon Dec 14 18:24:31 2009
        From: gervaz at gmail.com (mattia)
        Date: 14 Dec 2009 23:24:31 GMT
        Subject: insert unique data in a list
        References: <4b251840$0$30959$4fafbaef@reader3.news.tin.it>
        	<4b252b1b$0$644$4fafbaef@reader4.news.tin.it>
        	
        	
        	<07c342ef-fd02-4d6e-ab23-6effdd0598fc@b36g2000prf.googlegroups.com>
        	<4b267234$0$8867$4fafbaef@reader5.news.tin.it>
        	<00b03884$0$15654$c3e8da3@news.astraweb.com>
        Message-ID: <4b26c92e$0$8863$4fafbaef@reader5.news.tin.it>
        
        Il Mon, 14 Dec 2009 21:53:38 +0000, Steven D'Aprano ha scritto:
        
        > On Mon, 14 Dec 2009 17:13:24 +0000, mattia wrote:
        > 
        >> Il Sun, 13 Dec 2009 21:17:28 -0800, knifenomad ha scritto:
        >> 
        >>> On 12?14?, ??12?42?, Steven D'Aprano
        >>>  wrote:
        >>>> On Sun, 13 Dec 2009 17:19:17 -0800, knifenomad wrote:
        >>>> > this makes the set type hashable.
        >>>>
        >>>> > class Set(set):
        >>>> > ? ? __hash__ = lambda self: id(self)
        >>>>
        >>>> That's a *seriously* broken hash function.
        >>>>
        >>>> >>> key = "voila"
        >>>> >>> d = { Set(key): 1 }
        >>>> >>> d
        >>>>
        >>>> {Set(['i', 'a', 'l', 'o', 'v']): 1}>>> d[ Set(key) ]
        >>>>
        >>>> Traceback (most recent call last):
        >>>> ? File "", line 1, in 
        >>>> KeyError: Set(['i', 'a', 'l', 'o', 'v'])
        >>>>
        >>>> --
        >>>> Steven
        >>> 
        >>> of course it is broken as long as it uses it's instance id. i added
        >>> this to notify that unhashable can become hashable implementing
        >>> __hash__ inside the class. which probably set to None by default.
        >> 
        >> Ok, nice example, but I believe that using id() as the hash function
        >> can lead to unexpected collisions.
        > 
        > No, you have that backwards. Using id() as the hash function means that
        > equal keys will hash unequal -- rather than unexpected collisions, it
        > leads to unexpected failure-to-collide-when-it-should-collide.
        > 
        > And it isn't a "nice example", it is a terrible example.
        > 
        > Firstly, the example fails to behave correctly. It simply doesn't work
        > as advertised.
        > 
        > Secondly, and much worse, it encourages people to do something dangerous
        > without thinking about the consequences. If it is so easy to hash
        > mutable objects, why don't built-in lists and sets don't have a __hash__
        > method? Do you think that the Python developers merely forgot?
        > 
        > No, there is good reason why mutable items shouldn't be used as keys in
        > dicts or in sets, and this example simply papers over the reasons why
        > and gives the impression that using mutable objects as keys is easy and
        > safe when it is neither.
        > 
        > Using mutable objects as keys or set elements leads to surprising,
        > unexpected behaviour and hard-to-find bugs. Consider the following set
        > with lists as elements:
        > 
        > L = [1, 2]
        > s = Set()  # set that allows mutable elements s.add(L)
        > s.add([1, 2, 3])
        > 
        > So far so good. But what should happen now?
        > 
        > L.append(3)
        > 
        > The set now has two equal elements, which breaks the set invariant that
        > it has no duplicates.
        > 
        > Putting the problem of duplicates aside, there is another problem:
        > 
        > L = [1, 2]
        > s = Set([L])
        > L.append(3)
        > 
        > There are two possibilities: either the hash function of L changes when
        > the object changes, or it doesn't. Suppose it changes. Then the hash of
        > L after the append will be different from the hash of L before the
        > append, and so membership testing (L in s) will fail.
        > 
        > Okay, suppose we somehow arrange matters so that the hash of the object
        > doesn't change as the object mutates. This will solve the problem above:
        > we can mutate L as often as we like, and L in s will continue to work
        > correctly. But now the hash of an object doesn't just depend on it's
        > value, but on its history. That means that two objects which are
        > identical can hash differently, and we've already seen this is a
        > problem.
        > 
        > There is one final approach which could work: we give the object a
        > constant hash function, so that all objects of that type hash
        > identically. This means that the performance of searches and lookups in
        > sets and dicts will fall to that of lists. There is no point in paying
        > all the extra overhead of a dict to get behaviour as slow, or slower,
        > than a list.
        > 
        > In other words, no matter what you do, using mutable objects as keys or
        > set elements leads to serious problems that need to be dealt with. It
        > simply isn't true that all you need to do to make mutable objects usable
        > in dicts or sets is to add a hash function. That part is trivial.
        
        I agree with you, and in fact I'm inserting tuples in my set. All the 
        workaroun to use somehow mutable object are poor attemps to solve in a 
        quick-and-dirty way a difficult problem like hashing. But I think that 
        during the discussion we have slowly forgot the main topic of my 
        question, that was insert unique objects in a container. Hash are good to 
        retrieve items in constant time, and when we are dealing with collisions 
        we have to provide some solutions, like chaining or open addressing. Note 
        also that in hash collisions happen and the hash function is used to 
        retrieve items, not to insert unique items.
        
        
        From pavlovevidence at gmail.com  Mon Dec 14 18:26:25 2009
        From: pavlovevidence at gmail.com (Carl Banks)
        Date: Mon, 14 Dec 2009 15:26:25 -0800 (PST)
        Subject: Dangerous behavior of list(generator)
        References:  
        	<00b04565$0$15654$c3e8da3@news.astraweb.com>
        Message-ID: 
        
        On Dec 14, 2:48?pm, Steven D'Aprano  wrote:
        > On Mon, 14 Dec 2009 14:31:44 +0000, exarkun wrote:
        > > On 06:46 am, tjre... at udel.edu wrote:
        > >>On 12/13/2009 10:29 PM, exar... at twistedmatrix.com wrote:
        > >>>Doesn't matter. Sometimes it makes sense to call it directly.
        >
        > >>It only makes sense to call next (or .__next__) when you are prepared to
        > >>explicitly catch StopIteration within a try..except construct. You did
        > >>not catch it, so it stopped execution.
        >
        > >>Let me repeat: StopIteration is intended only for stopping iteration.
        > >>Outside that use, it is a normal exception with no special meaning.
        >
        > > You cut out the part of my message where I wrote that one might have
        > > forgotten the exception handling code that you posit is required, and
        > > that the current behavior makes debugging this situation unnecessarily
        > > challenging.
        >
        > I don't see why you think this is any more challenging to debug than any
        > other equivalent bug.
        
        "Errors should never pass silently."
        
        I'm not saying it's necessarily difficult to debug--although building
        a list by hand to test it is a lot more work than reading an exception
        traceback--but it'a stark violation of a Zen and common sense, so it
        is more serious than other sorts of errors.
        
        
        Carl Banks
        
        
        From david at boddie.org.uk  Mon Dec 14 18:43:52 2009
        From: david at boddie.org.uk (David Boddie)
        Date: Tue, 15 Dec 2009 00:43:52 +0100
        Subject: pyZui - anyone know about this?
        References: 
        	
        	
        Message-ID: 
        
        On Monday 14 December 2009 20:02, Donn wrote:
        
        > On Monday 14 December 2009 00:10:52 David Boddie wrote:
        >> Doesn't the author give his e-mail address at the end of the video?
        >> (Maybe I'm thinking of a different video.)
        >> 
        > Yes, in a quick and garbled way :) I have yet to try to contact the author
        > or the youtube poster -- been too busy.
        
        I managed to catch his address and sent him a message saying that people
        were discussing PyZUI in this thread.
        
        David
        
        
        From python at bdurham.com  Mon Dec 14 18:46:46 2009
        From: python at bdurham.com (python at bdurham.com)
        Date: Mon, 14 Dec 2009 18:46:46 -0500
        Subject: OS independent way to check if a python app is running?
        In-Reply-To: <7onmlcF3qrvc3U1@mid.uni-berlin.de>
        References: <1260818045.9273.1350060453@webmail.messagingengine.com>
        	<7onmlcF3qrvc3U1@mid.uni-berlin.de>
        Message-ID: <1260834406.21468.1350106615@webmail.messagingengine.com>
        
        Diez,
        
        Thank you for your sample code. That was just what we were looking for.
        
        Regards,
        Malcolm
        
        
        From gagsl-py2 at yahoo.com.ar  Mon Dec 14 19:23:38 2009
        From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina)
        Date: Mon, 14 Dec 2009 21:23:38 -0300
        Subject: parse a string of parameters and values
        References: <57a39e82-08e3-406a-9483-7fa28b180f82@w19g2000pre.googlegroups.com>
        	
        Message-ID: 
        
        En Sun, 13 Dec 2009 07:28:24 -0300, Peter Otten <__peter__ at web.de>  
        escribi?:
        > bsneddon wrote:
        
        >> I am going to read a text file that is an export from a control
        >> system.
        >> It has lines with information like
        >>
        >> base=1 name="first one" color=blue
        >>
        >> I would like to put this info into a dictionary for processing.
        >
        >>>> import shlex
        >>>> s = 'base=1 name="first one" color=blue equal="alpha=beta" empty'
        >>>> dict(t.partition("=")[::2] for t in shlex.split(s))
        > {'color': 'blue', 'base': '1', 'name': 'first one', 'empty': '', 'equal':
        > 'alpha=beta'}
        
        Brilliant!
        
        -- 
        Gabriel Genellina
        
        
        
        From donn.ingle at gmail.com  Mon Dec 14 19:33:29 2009
        From: donn.ingle at gmail.com (Donn)
        Date: Tue, 15 Dec 2009 02:33:29 +0200
        Subject: pyZui - anyone know about this?
        In-Reply-To: 
        References: 
        	
        	
        Message-ID: <200912150233.29622.donn.ingle@gmail.com>
        
        On Tuesday 15 December 2009 01:43:52 David Boddie wrote:
        > I managed to catch his address and sent him a message saying that people
        > were discussing PyZUI in this thread.
        > 
        Oooh. Sits,fidgets and waits. I want my socks back! (OP) :D
        
        \d
        -- 
        \/\/ave: donn.ingle at googlewave.com
        home: http://otherwise.relics.co.za/
        2D vector animation : https://savannah.nongnu.org/projects/things/
        Font manager : https://savannah.nongnu.org/projects/fontypython/
        
        
        From gagsl-py2 at yahoo.com.ar  Mon Dec 14 19:37:33 2009
        From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina)
        Date: Mon, 14 Dec 2009 21:37:33 -0300
        Subject: read text file byte by byte
        References: 
        	
        	
        	<4519638f-c62b-46f6-ba1e-619035d48036@j14g2000yqm.googlegroups.com>
        	<00ae1204$0$15654$c3e8da3@news.astraweb.com>
        	
        	
        	
        Message-ID: 
        
        En Mon, 14 Dec 2009 18:09:52 -0300, Nobody  escribi?:
        > On Sun, 13 Dec 2009 22:56:55 -0800, sjdevnull at yahoo.com wrote:
        >
        >> The 3.1 documentation specifies that file.read returns bytes:
        >
        >> Does it need fixing?
        >
        > There are no file objects in 3.x. The file() function no longer
        > exists. The return value from open(), will be an instance of
        > _io. depending upon the mode, e.g. _io.TextIOWrapper for 'r',
        > _io.BufferedReader for 'rb', _io.BufferedRandom for 'w+b', etc.
        >
        > 	http://docs.python.org/3.1/library/io.html
        >
        > io.IOBase.read() doesn't exist, io.RawIOBase.read(n) reads n bytes,
        > io.TextIOBase.read(n) reads n characters.
        
        So basically this section [1] should not exist, or be completely rewritten?
        At least the references to C stdio library seem wrong to me.
        
        [1] http://docs.python.org/3.1/library/stdtypes.html#file-objects
        
        -- 
        Gabriel Genellina
        
        
        
        From floydophone at gmail.com  Mon Dec 14 19:37:37 2009
        From: floydophone at gmail.com (Pete Hunt)
        Date: Mon, 14 Dec 2009 16:37:37 -0800 (PST)
        Subject: multiprocessing callbacks?
        Message-ID: <2ca39486-bc9c-4041-b53c-41c9a245cbcc@3g2000vbp.googlegroups.com>
        
        Hey, everyone -
        
        I'm trying to use multiprocessing to create a process pool similar to
        multiprocessing.Pool, except that it works across multiple hosts. For
        various reasons, I would like the result of async_apply() to return a
        Twisted Deferred object.
        
        My first attempt at the implementation is:
        
        class DeferredProxy(managers.BaseProxy):
            _exposed_ = ("callback","errback","addCallback","addErrback")
            def callback(self, v):
                return self._callmethod("callback",(v,))
        
            def errback(self, v):
                return self._callmethod("errback",(v,))
        
            def addCallback(self, cb):
                return self._callmethod("addCallback",(cb,))
        
            def addErrback(self, eb):
                return self.__callmethod("adderrback",(eb,))
        
        class DispatchManager(managers.BaseManager):
            pass
        DispatchManager.register("Deferred", defer.Deferred, DeferredProxy)
        
        This, however, fails, because "cb" and "eb" cannot be pickled. I don't
        actually need to pickle them, though, because I want them to run on
        the machine on which they were created. Is there a way, in
        multiprocessing, that I can pass some sort of "callback" around that
        serves as a proxy to a remote function?
        
        Thanks in advance,
        
        Pete
        
        
        From python.list at tim.thechases.com  Mon Dec 14 19:51:06 2009
        From: python.list at tim.thechases.com (Tim Chase)
        Date: Mon, 14 Dec 2009 18:51:06 -0600
        Subject: parse a string of parameters and values
        In-Reply-To: 
        References: <57a39e82-08e3-406a-9483-7fa28b180f82@w19g2000pre.googlegroups.com>	
        	
        Message-ID: <4B26DD7A.9060104@tim.thechases.com>
        
        Gabriel Genellina wrote:
        > Peter Otten escribi?:
        >> bsneddon wrote:
        >>> I am going to read a text file that is an export from a control
        >>> system.
        >>> It has lines with information like
        >>>
        >>> base=1 name="first one" color=blue
        >>>
        >>> I would like to put this info into a dictionary for processing.
        >>>>> import shlex
        >>>>> s = 'base=1 name="first one" color=blue equal="alpha=beta" empty'
        >>>>> dict(t.partition("=")[::2] for t in shlex.split(s))
        >> {'color': 'blue', 'base': '1', 'name': 'first one', 'empty': '', 'equal':
        >> 'alpha=beta'}
        > 
        > Brilliant!
        
        The thing I appreciated about Peter's solution was learning a 
        purpose for .partition() as I've always just used .split(), so I 
        would have done something like
        
         >>> dict('=' in s and s.split('=', 1) or (s, '') for s in 
        shlex.split(s))
        {'color': 'blue', 'base': '1', 'name': 'first one', 'empty': '', 
        'equal': 'alpha=beta'}
        
        Using .partition() makes that a lot cleaner.  However, it looks 
        like .partition() was added in 2.5, so for my code stuck in 2.4 
        deployments, I'll stick with the uglier .split()
        
        -tkc
        
        
        
        
        From python at mrabarnett.plus.com  Mon Dec 14 20:21:13 2009
        From: python at mrabarnett.plus.com (MRAB)
        Date: Tue, 15 Dec 2009 01:21:13 +0000
        Subject: print format
        In-Reply-To: <4b26c1af$0$8863$4fafbaef@reader5.news.tin.it>
        References: <4b26c1af$0$8863$4fafbaef@reader5.news.tin.it>
        Message-ID: <4B26E489.8020106@mrabarnett.plus.com>
        
        mattia wrote:
        > Hi all, I wanto to print just the first 5 characters of a string, why 
        > this doesn't work (py3.1)?
        >>>> print("{0:5}".format("123456789"))
        > 123456789
        > I know I could use print("123456789"[:5]), yeah it's a stupid example, 
        > but isn't format for string formatting?
        > 
        That's because it's the _minimum_ width.
        
        
        From davea at ieee.org  Mon Dec 14 20:49:00 2009
        From: davea at ieee.org (Dave Angel)
        Date: Mon, 14 Dec 2009 20:49:00 -0500
        Subject: race/deadlock when creating a multiprocessing.manager instance
        	while 	importing a module ?
        In-Reply-To: <52ce8fe6-7b3a-43dd-94bb-5a57ee7ad9b4@c34g2000yqn.googlegroups.com>
        References: <52ce8fe6-7b3a-43dd-94bb-5a57ee7ad9b4@c34g2000yqn.googlegroups.com>
        Message-ID: <4B26EB0C.9060600@ieee.org>
        
        
        
        Sebastien Binet wrote:
        > hi there,
        >
        > say I have this module
        >
        > ## farnsworth ##
        > __all__ = [
        >     'mgr',
        >     'maths',
        >     ]
        >
        > from multiprocessing.managers import BaseManager
        >
        > class MathsClass(object):
        >     def add(self, x, y):
        >         return x + y
        >     def mul(self, x, y):
        >         return x * y
        >
        > class MyManager(BaseManager):
        >     pass
        >
        > MyManager.register('Maths', MathsClass)
        >
        > def _setup():
        >     print "creating a manager..."
        >     mgr = MyManager()
        >     print "starting the manager..."
        >     mgr.start()
        >     print "sciencing faster..."
        >     maths = mgr.Maths()
        >     print maths.add(4,3)
        >     print maths.mul(7,8)
        >     print "done with sciencing."
        >     return (mgr, maths)
        >
        > # exec at module import
        > mgr, maths = _setup()
        >
        > # prevent hysteresis + clean-up
        > del _setup
        > ## EOF ##
        >
        > if I use it like so:
        >
        > $ python -m farnsworth
        > creating a manager...
        > starting the manager...
        > sciencing faster...
        > 7
        > 56
        > done with sciencing.
        >
        > all is fine, but if I try to use it thru an import:
        > $ python
        > py> import farnsworth.mgr as mgr
        > creating a manager...
        > starting the manager...
        > sciencing faster...
        >
        > [stuck for some time... hitting ^C]
        > Traceback (most recent call last):
        >   File "", line 1, in 
        >   File "farnsworth.py", line 32, in 
        >     mgr, maths = _setup()
        >   File "farnsworth.py", line 25, in _setup
        >     maths = mgr.Maths()
        >   File "/usr/lib/python2.6/multiprocessing/managers.py", line 634, in
        > temp
        >     token, exp = self._create(typeid, *args, **kwds)
        >   File "/usr/lib/python2.6/multiprocessing/managers.py", line 532, in
        > _create
        >     conn = self._Client(self._address, authkey=self._authkey)
        >   File "/usr/lib/python2.6/multiprocessing/connection.py", line 140,
        > in Client
        >     answer_challenge(c, authkey)
        >   File "/usr/lib/python2.6/multiprocessing/connection.py", line 372,
        > in answer_challenge
        >     message = connection.recv_bytes(256)         # reject large
        > message
        > KeyboardInterrupt
        >
        > is this a known limitation/feature of the multiprocessing module ?
        > is there a workaround (acquiring some import lock maybe) ?
        >
        > cheers,
        > sebastien.
        >
        > PS:
        > $ python
        > Python 2.6.4 (r264:75706, Oct 27 2009, 06:25:13)
        > [GCC 4.4.1] on linux2
        > Type "help", "copyright", "credits" or "license" for more information.
        >
        > $ python -c 'import sys; print sys.version_info'
        > (2, 6, 4, 'final', 0)
        >
        > $ uname -a
        > Linux farnsworth 2.6.31-ARCH #1 SMP PREEMPT Tue Nov 10 19:01:40 CET
        > 2009 x86_64 Intel(R) Core(TM)2 Duo CPU T9400 @ 2.53GHz GenuineIntel
        > GNU/Linux
        >
        >   
        Since I don't see any other responses, I'll give my guess, even though 
        I'm not very experienced with the multiprocessing module.
        
        It's my understanding that threads may not be created or destroyed 
        during an import.  So you need to find a way to defer the creation till 
        the imports are done.
        
        DaveA
        
        
        From wolftracks at invalid.com  Mon Dec 14 21:14:31 2009
        From: wolftracks at invalid.com (W. eWatson)
        Date: Mon, 14 Dec 2009 18:14:31 -0800
        Subject: Using Python to Execute a C or FORTRAN Program (Windows)
        Message-ID: 
        
        I think Python is capable of executing a compiled C or FORTRAN program, 
        and maybe even getting some parameters passed back. Does anyone have a 
        example of how this might be done? I'm running under Win XP Pro.
        
        
        From d at vidr.cc  Mon Dec 14 21:29:39 2009
        From: d at vidr.cc (David Roberts)
        Date: Mon, 14 Dec 2009 18:29:39 -0800 (PST)
        Subject: pyZui - anyone know about this?
        References:  
        	
        	 
        	
        Message-ID: <948af6e4-ab38-4d6d-a296-40bccffa7083@2g2000prl.googlegroups.com>
        
        Hi,
        
        Yes, the toolkit used is PyQt. The ZUI is implemented using a simple
        QPainter, and employs pyramidal tiling for efficiency (I haven't used
        any Qt/KDE voodoo in this regard). I'm using Gnome at the moment, but
        it should work just as well on KDE. Web pages are rendered using
        QtWebKit, and PDF with the pdftoppm utility.
        
        The project is opensource (GPLv2), but just hasn't been published
        yet :) . I'll try to make a release over the next few days, and I'll
        post a link here when I do.
        
        --
        David Roberts
        http://da.vidr.cc/
        
        On Dec 15, 10:33?am, Donn  wrote:
        > On Tuesday 15 December 2009 01:43:52 David Boddie wrote:> I managed to catch his address and sent him a message saying that people
        > > were discussing PyZUI in this thread.
        >
        > Oooh. Sits,fidgets and waits. I want my socks back! (OP) :D
        >
        > \d
        > --
        > \/\/ave: donn.in... at googlewave.com
        > home:http://otherwise.relics.co.za/
        > 2D vector animation :https://savannah.nongnu.org/projects/things/
        > Font manager :https://savannah.nongnu.org/projects/fontypython/
        
        
        
        From apt.shansen at gmail.com  Mon Dec 14 21:58:48 2009
        From: apt.shansen at gmail.com (Stephen Hansen)
        Date: Mon, 14 Dec 2009 18:58:48 -0800
        Subject: Using Python to Execute a C or FORTRAN Program (Windows)
        In-Reply-To: 
        References: 
        Message-ID: <7a9c25c20912141858s6bdbc3e2x52933b79d9749b7b@mail.gmail.com>
        
        On Mon, Dec 14, 2009 at 6:14 PM, W. eWatson  wrote:
        
        > I think Python is capable of executing a compiled C or FORTRAN program, and
        > maybe even getting some parameters passed back. Does anyone have a example
        > of how this might be done? I'm running under Win XP Pro.
        >
        
        import subprocess
        proc = subprocess.Popen(r"C:\mydir\myprog.exe", stdin=subprocess.PIPE,
        stdout=subprocess.PIPE)
        out, err = proc.communicate()
        
        print "Command returned", out
        
        See the subprocess module documentation for details.
        
        --S
        -------------- next part --------------
        An HTML attachment was scrubbed...
        URL: 
        
        From somm1105 at bellsouth.net  Mon Dec 14 22:07:04 2009
        From: somm1105 at bellsouth.net (Dan Sommers)
        Date: Tue, 15 Dec 2009 03:07:04 +0000 (UTC)
        Subject: OS independent way to check if a python app is running?
        References: <1260818045.9273.1350060453@webmail.messagingengine.com>
        Message-ID: 
        
        On Mon, 14 Dec 2009 14:14:05 -0500, python wrote:
        
        > Is there an os independent way to check if a python app is running?
        > 
        > Goal: I have a server program based on cherrypy that I only want to have
        > running once. If a system administrator accidentally attempts to run
        > this program more than once, I would like the 2nd instance of the
        > program to detect that its already running and exit.
        
        Maybe I'm missing something, but the locking mechanism already exists:  
        at some point, your server program has to bind to an IP port to listen 
        for incoming request, and any respectable OS won't let two programs bind 
        to the same port at the same time.  So if binding to the input port 
        works, then there *can't* be another instance of the program running 
        (multiple configuration files notwithstanding, but then you'd need a 
        second process anyway).
        
        I guess I am assuming that "a server program based on cherrypy" takes its 
        input from an IP port, but that seems safe enough given the nature of 
        cherrypy.
        
        Dan
        
        
        
        From davea at ieee.org  Mon Dec 14 22:28:11 2009
        From: davea at ieee.org (Dave Angel)
        Date: Mon, 14 Dec 2009 22:28:11 -0500
        Subject: print format
        In-Reply-To: <4b26c1af$0$8863$4fafbaef@reader5.news.tin.it>
        References: <4b26c1af$0$8863$4fafbaef@reader5.news.tin.it>
        Message-ID: <4B27024B.3060902@ieee.org>
        
        mattia wrote:
        > Hi all, I wanto to print just the first 5 characters of a string, why 
        > this doesn't work (py3.1)?
        >   
        >>>> print("{0:5}".format("123456789"))
        >>>>         
        > 123456789
        > I know I could use print("123456789"[:5]), yeah it's a stupid example, 
        > but isn't format for string formatting?
        >
        > Thanks, Mattia
        >
        >   
        I tested following statement in 2.6, not 3.1, but I think it's the same.
        
        The width field of the format is a *minimum* width.  So you can use it 
        to force padding, but not truncation.  If you need the string truncated, 
        just use slicing, as you already showed.
        
        DaveA
        
        
        
        From sjdevnull at yahoo.com  Mon Dec 14 23:30:34 2009
        From: sjdevnull at yahoo.com (sjdevnull at yahoo.com)
        Date: Mon, 14 Dec 2009 20:30:34 -0800 (PST)
        Subject: read text file byte by byte
        References: 
        	
        	 
        	<4519638f-c62b-46f6-ba1e-619035d48036@j14g2000yqm.googlegroups.com> 
        	<00ae1204$0$15654$c3e8da3@news.astraweb.com>
        	 
        	 
        	
        Message-ID: <7fc0b44e-0467-4a37-a7b7-5a85d1532397@21g2000yqj.googlegroups.com>
        
        On Dec 14, 4:09?pm, Nobody  wrote:
        > On Sun, 13 Dec 2009 22:56:55 -0800, sjdevn... at yahoo.com wrote:
        > > The 3.1 documentation specifies that file.read returns bytes:
        > > Does it need fixing?
        >
        > There are no file objects in 3.x.
        
        Then the documentation definitely needs fixing; the excerpt I posted
        earlier is from the 3.1 documentation's section about file objects:
        http://docs.python.org/3.1/library/stdtypes.html#file-objects
        
        Which begins:
        
        "5.9  File Objects
        
        File objects are implemented using C?s stdio package and can be
        created with the built-in open() function. File objects are also
        returned by some other built-in functions and methods, such as os.popen
        () and os.fdopen() and the makefile() method of socket objects."
        
        (It goes on to describe the read method's operation on bytes that I
        quoted upthread.)
        
        Sadly I'm not familiar enough with 3.x to suggest an appropriate edit.
        
        
        From tjreedy at udel.edu  Mon Dec 14 23:44:22 2009
        From: tjreedy at udel.edu (Terry Reedy)
        Date: Mon, 14 Dec 2009 23:44:22 -0500
        Subject: read text file byte by byte
        In-Reply-To: 
        References: 			<4519638f-c62b-46f6-ba1e-619035d48036@j14g2000yqm.googlegroups.com>	<00ae1204$0$15654$c3e8da3@news.astraweb.com>			
        	
        Message-ID: 
        
        On 12/14/2009 7:37 PM, Gabriel Genellina wrote:
        > En Mon, 14 Dec 2009 18:09:52 -0300, Nobody  escribi?:
        >> On Sun, 13 Dec 2009 22:56:55 -0800, sjdevnull at yahoo.com wrote:
        >>
        >>> The 3.1 documentation specifies that file.read returns bytes:
        >>
        >>> Does it need fixing?
        >>
        >> There are no file objects in 3.x. The file() function no longer
        >> exists. The return value from open(), will be an instance of
        >> _io. depending upon the mode, e.g. _io.TextIOWrapper for 'r',
        >> _io.BufferedReader for 'rb', _io.BufferedRandom for 'w+b', etc.
        >>
        >> http://docs.python.org/3.1/library/io.html
        >>
        >> io.IOBase.read() doesn't exist, io.RawIOBase.read(n) reads n bytes,
        >> io.TextIOBase.read(n) reads n characters.
        >
        > So basically this section [1] should not exist, or be completely rewritten?
        > At least the references to C stdio library seem wrong to me.
        >
        > [1] http://docs.python.org/3.1/library/stdtypes.html#file-objects
        
        I agree.
        http://bugs.python.org/issue7508
        
        Terry Jan Reedy
        
        
        
        
        
        
        From drsalists at gmail.com  Mon Dec 14 23:49:43 2009
        From: drsalists at gmail.com (Dan Stromberg)
        Date: Mon, 14 Dec 2009 20:49:43 -0800
        Subject: treaps in python
        Message-ID: <4B271567.4070604@gmail.com>
        
        
        I've just released my treap.py module:
        
        http://stromberg.dnsalias.org/~dstromberg/treap/
        
        It's code that implements a datastructure that is a hybrid of a binary 
        tree and a binary heap, having some of the advantages of each.  The URL 
        has a table comparing the asymptotic performance of treaps against some 
        other common python datastructures.
        
        This particular implementation is pretty dicitionary-like, but you can 
        also get the smallest value or the largest value in O(log2(n)) time, or 
        get a forward or reverse ordered list of values in O(n) time.  The price 
        of course is that adding and deleting things is O(log2(n)) time.
        
        It's currently GPLv3-licensed, but I'd like to dual license it in such a 
        way that it could eventually be included in the standard library.  How 
        would I go about this?
        
        Also, what's the best way to package something like this for consumption 
        by python-folk?  There seem to be so many ways of packaging things 
        anymore.  Are dist utils, a .deb and a .rpm the way to go?  Right now, 
        it's just using make to stuff things in /usr/local.
        
        There are two versions: One that is pure python, and one that is part 
        python and part cython.  They're automatically generated from a common 
        m4 template.
        
        There are rather plentiful unit tests included in the tar archive.
        
        I hope someone besides me finds it useful.
        
        
        
        From pavlovevidence at gmail.com  Tue Dec 15 00:14:45 2009
        From: pavlovevidence at gmail.com (Carl Banks)
        Date: Mon, 14 Dec 2009 21:14:45 -0800 (PST)
        Subject: treaps in python
        References: 
        Message-ID: <26fc1974-c6a8-4cbe-a04d-09381e1e9ecc@x15g2000vbr.googlegroups.com>
        
        On Dec 14, 8:49?pm, Dan Stromberg  wrote:
        > It's currently GPLv3-licensed, but I'd like to dual license it in such a
        > way that it could eventually be included in the standard library. ?How
        > would I go about this?
        
        I'm not going to try to talk you out of dual licensing it as something
        other than GPL, but you should note that we just had a thread
        discussing a proposal to include a data structure I consider more
        generally useful (graph), and that ended up pretty much dead.
        
        
        Carl Banks
        
        
        From gagsl-py2 at yahoo.com.ar  Tue Dec 15 00:33:39 2009
        From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina)
        Date: Tue, 15 Dec 2009 02:33:39 -0300
        Subject: print format
        References: <4b26c1af$0$8863$4fafbaef@reader5.news.tin.it>
        	<4B27024B.3060902@ieee.org>
        Message-ID: 
        
        En Tue, 15 Dec 2009 00:28:11 -0300, Dave Angel  escribi?:
        > mattia wrote:
        
        >> Hi all, I wanto to print just the first 5 characters of a string, why  
        >> this doesn't work (py3.1)?
        >>
        >>>>> print("{0:5}".format("123456789"))
        >>>>>
        >> 123456789
        >> I know I could use print("123456789"[:5]), yeah it's a stupid example,  
        >> but isn't format for string formatting?
        >>
        > The width field of the format is a *minimum* width.  So you can use it  
        > to force padding, but not truncation.  If you need the string truncated,  
        > just use slicing, as you already showed.
        
        Or use the .precision specifier:
        
        py> "{0:.5}".format("123412341234")
        '12341'
        
        {0:5.5} has the same effect. See  
        http://docs.python.org/library/string.html#format-string-syntax
        
        -- 
        Gabriel Genellina
        
        
        
        From your.master at gmail.com  Tue Dec 15 00:49:36 2009
        From: your.master at gmail.com (Brandon Devine)
        Date: Mon, 14 Dec 2009 21:49:36 -0800 (PST)
        Subject: dictionary with tuple keys
        Message-ID: <6cbdfcfd-8731-4538-aeba-db771794a5bb@u25g2000prh.googlegroups.com>
        
        Hi all,
        
        I am probably not thinking straight anymore about this problem.  I
        have a dictionary with tuple keys in the format (a, b, A, B) and float
        values.  I want to collect all the keys with identical (a, b...),
        disregarding whatever (... A, B) might be.  Specifically, I want to
        sum the float values once I've collected these keys.  I am staring at
        my screen, pondering ugly things, and I just know I must be missing a
        Pythonic solution.  Any suggestions?
        
        Thanks for any help,
        
        Brandon
        
        
        From iwaki at iwakihidekazu.net  Tue Dec 15 00:58:50 2009
        From: iwaki at iwakihidekazu.net (Hidekazu IWAKI)
        Date: Tue, 15 Dec 2009 14:58:50 +0900
        Subject: What is the differences between tkinter in windows and Tkinter in
        	the other platform?
        In-Reply-To: 
        References: <76820091214150209iwaki@iwakihidekazu.net>
        	
        Message-ID: <36820091215055850iwaki@iwakihidekazu.net>
        
        Thank you for your point.
        Python versions were difficult. And I didn't know that Tkinter was renamed.
        
        
        
        To make sure, I specify their systems.
        The system which `tkinter` module has is python 3.11 in Windows XP SP3.
        And the other system, which `Tkinter` module has is python 2.51 in Ubuntu
        8.04.
        
        I've solved the mistake that even I don't believe.
        Thank you very much!
        
        At 14 Dec 2009 13:19:18 -0500 Terry Reedy wrote:
        > On 12/14/2009 10:02 AM, Hidekazu IWAKI wrote:
        > > Hi, I'm hidekazu.
        > > 
        > > I'm making a Tk application with python.
        > > In the below code, the class App was inherited from Tkinter.Tk and the
        > > __init__ method calls Tk's constructor with `super` method. In windows,
        
        
        > > this code is valid (but, Tkinter ->  tkinter).
        > > 
        > > Why does this code happen a type error in not windows platform?
        > 
        > You question is not clear.
        > Specify system and Python version is both cases.
        > Note that Tkinter in 2.x was renamed tkinter in 3.x.
        > This difference has nothing to do with the platform.
        > 
        > tjr
        > 
        > > 
        > > thank you.
        > > 
        > > #--------------------------------------------------------
        > > from Tkinter import *
        > > 
        > > class App(Tk):
        > >      def __init__(self):
        > >          super(Tk,self).__init__()
        > > 
        > > App().mainloop()
        > > 
        > > #Traceback (most recent call last):
        > > #  File "./app.py", line 16, in
        > > #    App().mainloop()
        > > #  File "./app.py", line 7, in __init__
        > > #    super(Tk,self).__init__()
        > > #TypeError: super() argument 1 must be type, not classobj
        > > 
        > > /////////////////////////////////////////////////
        > > ???????????????
        > > e-mail: iwaki at iwakihidekazu.net
        > > /////////////////////////////////////////////////
        > 
        > 
        > -- 
        > http://mail.python.org/mailman/listinfo/python-list
        > 
        > ******************************
        >  XREA.COM -Free Web Hosting-
        >  http://www.xrea.com/
        > ******************************
        > 
        
        
        
        /////////////////////////////////////////////////
        ???????????????
        e-mail: i.hidekazu at gmail.com
        /////////////////////////////////////////////////
        
        
        From clp2 at rebertia.com  Tue Dec 15 00:59:35 2009
        From: clp2 at rebertia.com (Chris Rebert)
        Date: Mon, 14 Dec 2009 21:59:35 -0800
        Subject: dictionary with tuple keys
        In-Reply-To: <6cbdfcfd-8731-4538-aeba-db771794a5bb@u25g2000prh.googlegroups.com>
        References: <6cbdfcfd-8731-4538-aeba-db771794a5bb@u25g2000prh.googlegroups.com>
        Message-ID: <50697b2c0912142159w598b886p6198e3bef78ea84e@mail.gmail.com>
        
        On Mon, Dec 14, 2009 at 9:49 PM, Brandon Devine  wrote:
        > Hi all,
        >
        > I am probably not thinking straight anymore about this problem. ?I
        > have a dictionary with tuple keys in the format (a, b, A, B) and float
        > values. ?I want to collect all the keys with identical (a, b...),
        > disregarding whatever (... A, B) might be. ?Specifically, I want to
        > sum the float values once I've collected these keys. ?I am staring at
        > my screen, pondering ugly things, and I just know I must be missing a
        > Pythonic solution. ?Any suggestions?
        
        from collections import defaultdict
        
        new_dict = defaultdict(int)
        for tupkey in your_dict:
            new_key = tupkey[:2]
            new_dict[new_key] += your_dict[tupkey]
        
        Cheers,
        Chris
        --
        http://blog.rebertia.com
        
        
        From mensanator at aol.com  Tue Dec 15 01:09:36 2009
        From: mensanator at aol.com (Mensanator)
        Date: Mon, 14 Dec 2009 22:09:36 -0800 (PST)
        Subject: Using Python to Execute a C or FORTRAN Program (Windows)
        References: 
        Message-ID: 
        
        On Dec 14, 8:14?pm, "W. eWatson"  wrote:
        > I think Python is capable of executing a compiled C or FORTRAN program,
        
        Sure, if it was compiled to an .exe file.
        
        > and maybe even getting some parameters passed back.
        
        Sure, if the program prints to stdout.
        
        > Does anyone have a
        > example of how this might be done? I'm running under Win XP Pro.
        
        Here's one. The test program is factor.exe (included in
        the MIRACL library). I recompiled it (factor!.exe) to
        produce consitent output.
        
        Instead of stupidly saying
        
         C:\factor!\miracl\source>factor 31
         31
         this number is prime!
        
        I now have it print
        
         C:\factor!\miracl\source>factor! 31
         PRIME_FACTOR     31
        
        I now call it from Python and have Python fix its mistakes.
        
        ##    Mistakes? - numbers reported as COMPOSITE may still
        ##    be factorable. Composites are not returned to the
        ##    start of the algorithm for re-factoring. But that's ok,
        ##    if I don't like it, I'm free to fix it myself since
        ##    I have the source code (so says the author).
        ##
        ##    Hey, I won't look a gift horse in the mouth, but you
        ##    are advised that when you see...
        ##
        ##    C:\factor!\miracl\source>factor! 5081842980034330599
        ##    30221143303110332712493139579190463526792062
        ##    62204589342623811236647989889145173098650749
        ##
        ##    PRIME_FACTOR     37
        ##    PRIME_FACTOR     43
        ##    PRIME_FACTOR     167
        ##    COMPOSITE_FACTOR 507787751
        ##    PRIME_FACTOR     69847
        ##    PRIME_FACTOR     30697
        ##    PRIME_FACTOR     89017
        ##    PRIME_FACTOR     3478697
        ##    PRIME_FACTOR     434593
        ##    PRIME_FACTOR     49998841
        ##    PRIME_FACTOR     161610704597143
        ##    PRIME_FACTOR     14064370273
        ##    COMPOSITE_FACTOR 963039394703598565337297
        ##    PRIME_FACTOR     11927295803
        ##
        ##    ...you should follow that with...
        ##
        ##    C:\factor!\miracl\source>factor! 507787751
        ##    PRIME_FACTOR     29819
        ##    PRIME_FACTOR     17029
        ##
        ##    C:\factor!\miracl\source>factor! 963039394703598565337297
        ##    PRIME_FACTOR     518069464441
        ##    PRIME_FACTOR     1858900129817
        
        
        
        import os
        import random
        import time
        
        factor_program = 'factor! -d200 '
        
        the_composites =
        [['COMPOSITE_FACTOR','50818429800343305993022114330311033271249313957919046352679206262204589342623811236647989889145173098650749']]
        
        ##random_digits = [str(random.randint(0,9)) for d in range(30)]
        ##test_number = ''.join(random_digits)
        ##the_composites = [['COMPOSITE_FACTOR',test_number]]
        
        the_primes = []
        the_intractables = []
        
        phase = 1
        the_times = []
        while the_composites:
          print "="*40
          print 'Phase',phase
          the_comp = the_composites.pop(0)
          print the_comp
          print
          the_times.append(time.time())  # time how long it takes to run
        factor!.exe
          the_output = os.popen(factor_program+the_comp[1]).readlines()
          the_times.append(time.time())
          new_factors = [i.split() for i in the_output]
          for i in new_factors: print i
          print
          if len(new_factors) == 1:
            # it's prime or intractable
            if new_factors[0][0] == 'PRIME_FACTOR':
              the_primes.append([new_factors[0][0],long(new_factors[0][1])])
            else:
              the_intractables.append([new_factors[0][0],long(new_factors[0]
        [1])])
            new_factors.pop()
          while new_factors:
            j = new_factors.pop(0)
            if j[0] == 'PRIME_FACTOR':
              the_primes.append([j[0],long(j[1])])
            else:
              the_composites.append(j)
          print the_times[phase] - the_times[phase-1],'seconds'
          phase += 1
        
        print "="*40
        print
        print 'Factoring complete'
        print
        
        the_primes.sort()
        the_intractables.sort()
        the_primes.extend(the_intractables)
        
        for i in the_primes:
          print i[0],i[1]
        print
        print "="*40
        
        ##    ========================================
        ##    Phase 1
        ##    ['COMPOSITE_FACTOR',
        '50818429800343305993022114330311033271249313957919046352679206262204589342623811236647989889145173098650749']
        ##
        ##    ['PRIME_FACTOR', '37']
        ##    ['PRIME_FACTOR', '43']
        ##    ['PRIME_FACTOR', '167']
        ##    ['COMPOSITE_FACTOR', '507787751']
        ##    ['PRIME_FACTOR', '69847']
        ##    ['PRIME_FACTOR', '30697']
        ##    ['PRIME_FACTOR', '89017']
        ##    ['PRIME_FACTOR', '3478697']
        ##    ['PRIME_FACTOR', '434593']
        ##    ['PRIME_FACTOR', '49998841']
        ##    ['PRIME_FACTOR', '161610704597143']
        ##    ['PRIME_FACTOR', '14064370273']
        ##    ['COMPOSITE_FACTOR', '963039394703598565337297']
        ##    ['PRIME_FACTOR', '11927295803']
        ##
        ##    ========================================
        ##    Phase 2
        ##    ['COMPOSITE_FACTOR', '507787751']
        ##
        ##    ['PRIME_FACTOR', '29819']
        ##    ['PRIME_FACTOR', '17029']
        ##
        ##    ========================================
        ##    Phase 3
        ##    ['COMPOSITE_FACTOR', '963039394703598565337297']
        ##
        ##    ['PRIME_FACTOR', '518069464441']
        ##    ['PRIME_FACTOR', '1858900129817']
        ##
        ##    ========================================
        ##
        ##    Factoring complete
        ##
        ##    PRIME_FACTOR 37
        ##    PRIME_FACTOR 43
        ##    PRIME_FACTOR 167
        ##    PRIME_FACTOR 17029
        ##    PRIME_FACTOR 29819
        ##    PRIME_FACTOR 30697
        ##    PRIME_FACTOR 69847
        ##    PRIME_FACTOR 89017
        ##    PRIME_FACTOR 434593
        ##    PRIME_FACTOR 3478697
        ##    PRIME_FACTOR 49998841
        ##    PRIME_FACTOR 11927295803
        ##    PRIME_FACTOR 14064370273
        ##    PRIME_FACTOR 518069464441
        ##    PRIME_FACTOR 1858900129817
        ##    PRIME_FACTOR 161610704597143
        ##
        ##    ========================================
        
        
        
        From steven at REMOVE.THIS.cybersource.com.au  Tue Dec 15 01:26:52 2009
        From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano)
        Date: 15 Dec 2009 06:26:52 GMT
        Subject: Dangerous behavior of list(generator)
        References: 
        	<00b04565$0$15654$c3e8da3@news.astraweb.com>
        	
        Message-ID: 
        
        On Mon, 14 Dec 2009 15:26:25 -0800, Carl Banks wrote:
        
        > On Dec 14, 2:48?pm, Steven D'Aprano  cybersource.com.au> wrote:
        >> On Mon, 14 Dec 2009 14:31:44 +0000, exarkun wrote:
        >> > On 06:46 am, tjre... at udel.edu wrote:
        >> >>On 12/13/2009 10:29 PM, exar... at twistedmatrix.com wrote:
        >> >>>Doesn't matter. Sometimes it makes sense to call it directly.
        >>
        >> >>It only makes sense to call next (or .__next__) when you are prepared
        >> >>to explicitly catch StopIteration within a try..except construct. You
        >> >>did not catch it, so it stopped execution.
        >>
        >> >>Let me repeat: StopIteration is intended only for stopping iteration.
        >> >>Outside that use, it is a normal exception with no special meaning.
        >>
        >> > You cut out the part of my message where I wrote that one might have
        >> > forgotten the exception handling code that you posit is required, and
        >> > that the current behavior makes debugging this situation
        >> > unnecessarily challenging.
        >>
        >> I don't see why you think this is any more challenging to debug than
        >> any other equivalent bug.
        > 
        > "Errors should never pass silently."
        
        StopIteration isn't an error, it's a signal. The error is *misusing* 
        StopIteration, and the above Zen no more applies than it would if I did 
        x-y instead of y-x and complained that I got no traceback. Some errors 
        are programming mistakes, and they are the deadliest error because they 
        can and do pass silently. There's nothing you can do about that except 
        Don't Make Mistakes.
        
         
        > I'm not saying it's necessarily difficult to debug--although building a
        > list by hand to test it is a lot more work than reading an exception
        > traceback
        
        Of course. Nobody said the life of a programmer was all beer and 
        skittles :)
        
        
        > --but it'a stark violation of a Zen and common sense, so it is
        > more serious than other sorts of errors.
        
        I'm happy to accept it is a Gotcha, but a bug? I'm not convinced.
        
        
        
        -- 
        Steven
        
        
        From arts.martijn at gmail.com  Tue Dec 15 02:09:55 2009
        From: arts.martijn at gmail.com (Martijn Arts)
        Date: Tue, 15 Dec 2009 08:09:55 +0100
        Subject: What type of info do you capture about a user's environment for 
        	debugging?
        In-Reply-To: 
        References: <1260823195.23583.1350075123@webmail.messagingengine.com> 
        	
        Message-ID: <23739e0a0912142309r1c24b6aw5583adc7e1354a01@mail.gmail.com>
        
        On Mon, Dec 14, 2009 at 10:11 PM, Philip Semanchuk wrote:
        
        >
        > On Dec 14, 2009, at 3:39 PM, python at bdurham.com wrote:
        >
        >  We're preparing to release a commercial software product based on
        >> Python. When a customer reports problems with our software, we
        >> would like to capture as much information about their environment
        >> as possible while being respectful of privacy concerns. The info
        >> we capture will be displayed to the user for review and optional
        >> submission to our support team.
        >> Here's what we've come up with so far:
        >> - platform module info
        >> - locale module info
        >> - os.environ (selected info)
        >> - sys.argv (application path and command line arguements)
        >> Free disk space and write status for the following paths:
        >> - application folder
        >> - startup folder (which may be different than application folder)
        >> - temp path
        >> - user path ("My Documents", "Home")
        >> Information captured via our browser interface
        >> - display resolution
        >> - browser version
        >> Anyone have any additional suggestions or feedback?
        >>
        >
        > Python version? =)
        >
        > I think he'll use py2exe or something like that to "compile" the python
        files into an exe.
        
        Martijn
        -------------- next part --------------
        An HTML attachment was scrubbed...
        URL: 
        
        From ben+python at benfinney.id.au  Tue Dec 15 02:25:38 2009
        From: ben+python at benfinney.id.au (Ben Finney)
        Date: Tue, 15 Dec 2009 18:25:38 +1100
        Subject: dictionary with tuple keys
        References: <6cbdfcfd-8731-4538-aeba-db771794a5bb@u25g2000prh.googlegroups.com>
        Message-ID: <87vdg83dhp.fsf@benfinney.id.au>
        
        Brandon Devine  writes:
        
        > I am probably not thinking straight anymore about this problem. I have
        > a dictionary with tuple keys in the format (a, b, A, B) and float
        > values. I want to collect all the keys with identical (a, b...),
        > disregarding whatever (... A, B) might be. Specifically, I want to sum
        > the float values once I've collected these keys. I am staring at my
        > screen, pondering ugly things, and I just know I must be missing a
        > Pythonic solution. Any suggestions?
        
        The Schwartzian transform, though primarily designed for unusual sorting
        requirements, seems applicable here. It's a good tool to reach for in
        many situations.
        
        In other words: make a new dictionary, based on the key function you are
        interested in.
        
        In this case, I'll use ?itertools.groupby? to make a new sequence of
        keys and values, and then extract the keys and values actually wanted.
        
            >>> import pprint
            >>> pprint.pprint(foo)
            {('a', 'b', 'A', 'B'): 1.1000000000000001,
             ('a', 'b', 'X', 'Y'): 2.2000000000000002,
             ('c', 'd', 'A', 'B'): 3.2999999999999998,
             ('e', 'f', 'P', 'Q'): 4.4000000000000004,
             ('e', 'f', 'R', 'S'): 5.5,
             ('e', 'f', 'T', 'U'): 6.5999999999999996}
        
            >>> import itertools
            >>> pprint.pprint(
            ...     dict(
            ...         (key, list(
            ...             x[1] for x in items))
            ...         for (key, items) in
            ...             itertools.groupby(
            ...                 sorted([
            ...                     (k[0:2], value)
            ...                     for (k, value) in foo.items()
            ...                     ]),
            ...                 lambda v: v[0]
            ...                 )
            ...         )
            ...     )
            {('a', 'b'): [1.1000000000000001, 2.2000000000000002],
             ('c', 'd'): [3.2999999999999998],
             ('e', 'f'): [4.4000000000000004, 5.5, 6.5999999999999996]}
        
        
        Possibly someone could remove some of the processing in the middle
        there, but I couldn't quickly see a way.
        
        Certainly it might be clearer if written as one or more loops, instead
        of iterators. But I find the above relatively clear, and using the
        built-in iterator objects will likely make for a less buggy
        implementation.
        
        -- 
         \            ?The whole area of [treating source code as intellectual |
          `\    property] is almost assuring a customer that you are not going |
        _o__)               to do any innovation in the future.? ?Gary Barnett |
        Ben Finney
        
        
        From no.email at nospam.invalid  Tue Dec 15 02:36:17 2009
        From: no.email at nospam.invalid (Paul Rubin)
        Date: Mon, 14 Dec 2009 23:36:17 -0800
        Subject: dictionary with tuple keys
        References: <6cbdfcfd-8731-4538-aeba-db771794a5bb@u25g2000prh.googlegroups.com>
        Message-ID: <7xaaxky9hq.fsf@ruckus.brouhaha.com>
        
        Brandon Devine  writes:
        > I am probably not thinking straight anymore about this problem.  I
        > have a dictionary with tuple keys in the format (a, b, A, B) and float
        > values.  I want to collect all the keys with identical (a, b...),
        > disregarding whatever (... A, B) might be.  Specifically, I want to
        > sum the float values once I've collected these keys.  I am staring at
        > my screen, pondering ugly things, and I just know I must be missing a
        > Pythonic solution.  Any suggestions?
        
        a,b are the first two elments of the tuple and d is the dict?  I.e. 
        I think you want
        
            interesting_keys = [k for k in d.keys() if k[:2] == (a,b)]
            sum_of_values = sum(d[k] for k in interesting_keys)
        
        You could write it a little differently to make fewer intermediate
        results and so forth, but the above shows the idea.
        
        
        From daniel at stutzbachenterprises.com  Tue Dec 15 02:38:35 2009
        From: daniel at stutzbachenterprises.com (Daniel Stutzbach)
        Date: Tue, 15 Dec 2009 01:38:35 -0600
        Subject: treaps in python
        In-Reply-To: <4B271567.4070604@gmail.com>
        References: <4B271567.4070604@gmail.com>
        Message-ID: 
        
        On Mon, Dec 14, 2009 at 10:49 PM, Dan Stromberg  wrote:
        
        > Also, what's the best way to package something like this for consumption by
        > python-folk?  There seem to be so many ways of packaging things anymore.
        >  Are dist utils, a .deb and a .rpm the way to go?  Right now, it's just
        > using make to stuff things in /usr/local.
        >
        
        Put a source .tar.gz on PyPi that includes a setup.py, optionally using
        distribute_setup.py to augment distutils.
        
        http://docs.python.org/distutils/
        
        http://packages.python.org/distribute/using.html
        http://pypi.python.org/pypi/distribute#distribute-setup-py
        
        --
        Daniel Stutzbach, Ph.D.
        President, Stutzbach Enterprises, LLC 
        -------------- next part --------------
        An HTML attachment was scrubbed...
        URL: 
        
        From python at bdurham.com  Tue Dec 15 02:52:51 2009
        From: python at bdurham.com (python at bdurham.com)
        Date: Tue, 15 Dec 2009 02:52:51 -0500
        Subject: OS independent way to check if a python app is running?
        In-Reply-To: 
        References: <1260818045.9273.1350060453@webmail.messagingengine.com>
        	
        Message-ID: <1260863571.18524.1350158823@webmail.messagingengine.com>
        
        Hi Dan,
        
        > Maybe I'm missing something, but the locking mechanism already exists:  
        at some point, your server program has to bind to an IP port to listen 
        for incoming request, and any respectable OS won't let two programs bind 
        to the same port at the same time.  So if binding to the input port 
        works, then there *can't* be another instance of the program running 
        (multiple configuration files notwithstanding, but then you'd need a 
        second process anyway).
        
        We actually have a suite of server products which use ports in a
        flexible way so your idea - although accurate - won't work in our
        specific case.
        
        MRAB and Diez posted some excellent, cross platform approaches to
        locking a resource.
        
        Thanks for your feedback.
        
        Regards,
        Malcolm
        
        
        From daved170 at gmail.com  Tue Dec 15 03:25:05 2009
        From: daved170 at gmail.com (daved170)
        Date: Tue, 15 Dec 2009 00:25:05 -0800 (PST)
        Subject: read text file byte by byte
        References: 
        	
        	 
        	<4519638f-c62b-46f6-ba1e-619035d48036@j14g2000yqm.googlegroups.com> 
        	
        Message-ID: <10066771-d496-4f2a-8ca0-33360fe54a3c@j4g2000yqe.googlegroups.com>
        
        On 13 ?????, 22:39, Dennis Lee Bieber  wrote:
        > On Sat, 12 Dec 2009 22:15:50 -0800 (PST), daved170 
        > declaimed the following in gmane.comp.python.general:
        >
        > > Thank you all.
        > > Dennis I really liked you solution for the issue but I have two
        > > question about it:
        > > 1) My origin file is Text file and not binary
        >
        > ? ? ? ? Do you need to process the bytes in the file as they are? Or do you
        > accept changes in line-endings (M$ Windows "text" files use  as
        > line ending, but if you read it in Python as "text"  is
        > converted to a single .
        >
        > > 2) I need to read each time 1 byte. I didn't see that on your example
        > > code.
        >
        > ? ? ? ? You've never explained why you need to READ 1 byte at a time, vs
        > reading a block (I chose 1KB) and processing each byte IN THE BLOCK.
        > After all, if you do use 1 byte I/O, your program is going to be very
        > slow, as each read is blocking (suspends) while asking the O/S for the
        > next character in the file (this depends upon the underlying I/O library
        > implementation -- I suspect any modern I/O system is still reading some
        > block size [256 to 4K] and then returning parts of that block as
        > needed). OTOH, reading a block at a time makes for one suspension and
        > then a lot of data to be processed however you want.
        >
        > ? ? ? ? You originally stated that you want to "scramble" the bytes -- if
        > you mean to implement some sort of encryption algorithm you should know
        > that most of them work in blocks as the "key" is longer than one byte.
        >
        > ? ? ? ? My sample reads in chunks, then the scramble function XORs each byte
        > with the corresponding byte in the supplied key string, finally
        > rejoining all the now individual bytes into a single chunk for
        > subsequent output.
        > --
        > ? ? ? ? Wulfraed ? ? ? ? Dennis Lee Bieber ? ? ? ? ? ? ? KD6MOG
        > ? ? ? ? wlfr... at ix.netcom.com ? ? ?HTTP://wlfraed.home.netcom.com/
        
        Hi All,
        As I read again your comments and the codes you posted I realize that
        I was mistaken.
        I don't need to read the file byte by byte. you all right. I do need
        to scramble each byte. So I'll do as you said - I'll read blocks and
        scramble each byte in the block.
        And now for my last question in this subject.
        Lets say that my file contains the following line: "Hello World".
        I read it using the read(1024) as you suggested in your sample.
        Now, how can I XOR it with 0xFF for example?
        Thanks again
        Dave
        
        
        From donn.ingle at gmail.com  Tue Dec 15 03:28:41 2009
        From: donn.ingle at gmail.com (Donn)
        Date: Tue, 15 Dec 2009 10:28:41 +0200
        Subject: pyZui - anyone know about this?
        In-Reply-To: <948af6e4-ab38-4d6d-a296-40bccffa7083@2g2000prl.googlegroups.com>
        References: 
        	
        	<948af6e4-ab38-4d6d-a296-40bccffa7083@2g2000prl.googlegroups.com>
        Message-ID: <200912151028.41350.donn.ingle@gmail.com>
        
        On Tuesday 15 December 2009 04:29:39 David Roberts wrote:
        > Yes, the toolkit used is PyQt.
        \me makes note to start learning PyQt asap.
        
        > and employs pyramidal tiling for efficiency 
        \me ... time to hit Wikipedia :)
        
        > (I haven't used any Qt/KDE voodoo in this regard).
        Imho, your code should *become* that voodoo -- from what I saw in that vid 
        it's unique and has such promise.
        
        > QtWebKit, and PDF with the pdftoppm utility.
        Ah, thanks.
         
        > The project is opensource (GPLv2), but just hasn't been published
        > yet :) . I'll try to make a release over the next few days, and I'll
        > post a link here when I do.
        Can't wait.
        
        David, thanks for replying here on the list. Well done on your pyZui and I 
        hope it catches fire in people's imaginations. I think that fire may explain why 
        my socks are missing! :D
        
        \d
        -- 
        \/\/ave: donn.ingle at googlewave.com
        home: http://otherwise.relics.co.za/
        2D vector animation : https://savannah.nongnu.org/projects/things/
        Font manager : https://savannah.nongnu.org/projects/fontypython/
        
        
        From sjmachin at lexicon.net  Tue Dec 15 03:33:22 2009
        From: sjmachin at lexicon.net (John Machin)
        Date: Tue, 15 Dec 2009 08:33:22 +0000 (UTC)
        Subject: dictionary with tuple keys
        References: <6cbdfcfd-8731-4538-aeba-db771794a5bb@u25g2000prh.googlegroups.com>
        	<87vdg83dhp.fsf@benfinney.id.au>
        Message-ID: 
        
        Ben Finney  benfinney.id.au> writes:
         
        > In this case, I'll use ?itertools.groupby? to make a new sequence of
        > keys and values, and then extract the keys and values actually wanted.
        
        Ah, yes, Zawinski revisited ... itertools.groupby is the new regex :-)
         
        > Certainly it might be clearer if written as one or more loops, instead
        > of iterators. But I find the above relatively clear, and using the
        > built-in iterator objects will likely make for a less buggy
        > implementation.
        
        Relative clarity like relative beauty is in the eye of the beholder,
        and few parents have ugly children :-)
        
        The problem with itertools.groupby is that unlike SQL's "GROUP BY"
        it needs sorted input. The OP's requirement (however interpreted)
        can be met without sorting.
        
        Your interpretation can be implemented simply:
        
        from collections import defaultdict
        result = defaultdict(list)
        for key, value in foo.iteritems():
            result[key[:2]].append(value)
        
        
        
        From makobu.mwambiriro at gmail.com  Tue Dec 15 03:56:22 2009
        From: makobu.mwambiriro at gmail.com (makobu)
        Date: Tue, 15 Dec 2009 00:56:22 -0800 (PST)
        Subject: multiprocessing module
        Message-ID: <79854c42-b2af-4adb-8967-3dc5e4ac0d2a@l13g2000yqb.googlegroups.com>
        
        I have a function that makes two subprocess.Popen() calls on a file.
        
        I have 8 cores. I need 8 instances of that function running in
        parallel at any given time till all the files are worked on.
        Can the multiprocessing module do this? If so, whats the best method?
        
        A technical overview of how the multiprocessing module actually works
        would also be really helpful.
        
        regards,
        mak.
        
        
        From makobu.mwambiriro at gmail.com  Tue Dec 15 04:00:37 2009
        From: makobu.mwambiriro at gmail.com (makobu)
        Date: Tue, 15 Dec 2009 01:00:37 -0800 (PST)
        Subject: parallelpython 1.5.7 crash
        References: 
        	
        Message-ID: 
        
        Thanks Zeph.
        
        
        From arts.martijn at gmail.com  Tue Dec 15 04:12:21 2009
        From: arts.martijn at gmail.com (Martijn Arts)
        Date: Tue, 15 Dec 2009 10:12:21 +0100
        Subject: pyZui - anyone know about this?
        In-Reply-To: <200912151028.41350.donn.ingle@gmail.com>
        References:  
        	
        	<948af6e4-ab38-4d6d-a296-40bccffa7083@2g2000prl.googlegroups.com>
        	<200912151028.41350.donn.ingle@gmail.com>
        Message-ID: <23739e0a0912150112p3c22be44jcae290a3060f3196@mail.gmail.com>
        
        You could do some really awesome stuff with that! I love the webpage example
        where you zoom in on the exclamation mark and there's a new page.
        
        Just imagine the possibilities!
        
        On Tue, Dec 15, 2009 at 9:28 AM, Donn  wrote:
        
        > On Tuesday 15 December 2009 04:29:39 David Roberts wrote:
        > > Yes, the toolkit used is PyQt.
        > \me makes note to start learning PyQt asap.
        >
        > > and employs pyramidal tiling for efficiency
        > \me ... time to hit Wikipedia :)
        >
        > > (I haven't used any Qt/KDE voodoo in this regard).
        > Imho, your code should *become* that voodoo -- from what I saw in that vid
        > it's unique and has such promise.
        >
        > > QtWebKit, and PDF with the pdftoppm utility.
        > Ah, thanks.
        >
        > > The project is opensource (GPLv2), but just hasn't been published
        > > yet :) . I'll try to make a release over the next few days, and I'll
        > > post a link here when I do.
        > Can't wait.
        >
        > David, thanks for replying here on the list. Well done on your pyZui and I
        > hope it catches fire in people's imaginations. I think that fire may
        > explain why
        > my socks are missing! :D
        >
        > \d
        > --
        > \/\/ave: donn.ingle at googlewave.com
        > home: http://otherwise.relics.co.za/
        > 2D vector animation : https://savannah.nongnu.org/projects/things/
        > Font manager : https://savannah.nongnu.org/projects/fontypython/
        > --
        > http://mail.python.org/mailman/listinfo/python-list
        >
        -------------- next part --------------
        An HTML attachment was scrubbed...
        URL: 
        
        From ben+python at benfinney.id.au  Tue Dec 15 04:32:04 2009
        From: ben+python at benfinney.id.au (Ben Finney)
        Date: Tue, 15 Dec 2009 20:32:04 +1100
        Subject: OS independent way to check if a python app is running?
        References: <1260818045.9273.1350060453@webmail.messagingengine.com>
        	
        	<7onmlcF3qrvc3U1@mid.uni-berlin.de>
        Message-ID: <87ocm037mz.fsf@benfinney.id.au>
        
        "Diez B. Roggisch"  writes:
        
        > Not only exists, he should also use the OS' locking mechanisms. The
        > file could otherwise be stale.
        >
        > We use this:
        
        Have you tried collaborating with the ?lockfile? library developer to
        converge these solutions?
        
        As I understand it, the ?lockfile? library is meant to provide a common
        API across platforms; but that doesn't prevent it from taking advantage
        of OS-specific locking implementation.
        
        -- 
         \           ?I do not believe in forgiveness as it is preached by the |
          `\        church. We do not need the forgiveness of God, but of each |
        _o__)                    other and of ourselves.? ?Robert G. Ingersoll |
        Ben Finney
        
        
        From wentland at cl.uni-heidelberg.de  Tue Dec 15 05:17:52 2009
        From: wentland at cl.uni-heidelberg.de (Wolodja Wentland)
        Date: Tue, 15 Dec 2009 11:17:52 +0100
        Subject: Memory consumption of multiprocessing.Pool
        Message-ID: <20091215101752.GG11942@kinakuta.local>
        
        Hi all,
        
        I have a problem with the memory consumption of multiprocessing.Pool()'s
        worker processes. I have a parent process that has to handle big data
        structures and would like to use a pool of processes for computations.
        
        The problem is, that all worker processes have the same memory
        requirement as the parent one, although they do *not* use any the parent
        processes data structures. The following snippet illustrates this
        behaviour:
        
        --- snip ---
        #!/usr/bin/env python
        # -*- coding: utf-8 -*-
        
        import multiprocessing
        import time
        
        def worker(el):
            time.sleep(10)
        
        def main():
            print 'Init Pool 1'
            p_pool = multiprocessing.Pool()
            
            print 'Call pool.map()'
            p_pool.map(worker, range(multiprocessing.cpu_count()))
        
            print 'Allocate memory'
            eat_memory = range(1000000)
            
            print 'Call pool.map()'
            p_pool.map(worker, range(multiprocessing.cpu_count()))
            
            print 'Delete pool 1'
            del p_pool
            
            print 'Init Pool 2'
            p_pool = multiprocessing.Pool()
            
            print 'Call pool.map()'
            p_pool.map(worker, range(multiprocessing.cpu_count()))
            
            print 'Delete pool 2'
            del p_pool
        
        if __name__ == '__main__':
            main()
        --- snip ---
        
        You will see that the memory consumption of the worker processes will be
        roughly the same for the first two calls to p_pool.map(), but rise for
        the third.
        
        How can I make sure that 'eat_memory' does not use any memory in the
        pool processes? This is important as I don't always know when a pool is
        instanciated and the pool processes should *not* have the same memory
        requirements as the parent process.
        
        Am I missing something here?
        
        -- 
          .''`.     Wolodja Wentland     
         : :'  :    
         `. `'`     4096R/CAF14EFC 
           `-       081C B7CD FF04 2BA9 94EA  36B2 8B7F 7D30 CAF1 4EFC
        -------------- next part --------------
        A non-text attachment was scrubbed...
        Name: signature.asc
        Type: application/pgp-signature
        Size: 836 bytes
        Desc: Digital signature
        URL: 
        
        From seb.binet at gmail.com  Tue Dec 15 05:57:19 2009
        From: seb.binet at gmail.com (Sebastien Binet)
        Date: Tue, 15 Dec 2009 11:57:19 +0100
        Subject: race/deadlock when creating a multiprocessing.manager instance
        	while =?iso-8859-1?q?=09importing_a_module?= ?
        In-Reply-To: <4B26EB0C.9060600@ieee.org>
        References: <52ce8fe6-7b3a-43dd-94bb-5a57ee7ad9b4@c34g2000yqn.googlegroups.com>
        	<4B26EB0C.9060600@ieee.org>
        Message-ID: <200912151157.19524.binet@cern.ch>
        
        Dave,
        
        [..snip..]
        On Tuesday 15 December 2009 02:49:00 Dave Angel wrote: 
        > Since I don't see any other responses, I'll give my guess, even though
        > I'm not very experienced with the multiprocessing module.
        > 
        > It's my understanding that threads may not be created or destroyed
        > during an import.  So you need to find a way to defer the creation till
        > the imports are done.
        
        yes, I figured this much and I already wrapped my module with a ModuleFacade 
        object which has lazy properties attributes [1].
        this solves the problem of import my module, but if the module importing my 
        module is itself being imported, I am back to square one.
        
        and my module is being used by many people.
        
        I guess I'd need at least a way to detect that somebody is trying to use the 
        lazy properties of my module facade while an import is "still active".
        is there such a mechanism ?
        
        cheers,
        sebastien.
        
        [1] 
        https://svnweb.cern.ch/trac/atlasoff/browser/Tools/PyUtils/trunk/python/AthFile/__init__.py
        -- 
        #########################################
        # Dr. Sebastien Binet
        # Laboratoire de l'Accelerateur Lineaire
        # Universite Paris-Sud XI
        # Batiment 200
        # 91898 Orsay
        #########################################
        
        
        From donn.ingle at gmail.com  Tue Dec 15 05:58:54 2009
        From: donn.ingle at gmail.com (Donn)
        Date: Tue, 15 Dec 2009 12:58:54 +0200
        Subject: pyZui - anyone know about this?
        In-Reply-To: <23739e0a0912150112p3c22be44jcae290a3060f3196@mail.gmail.com>
        References: 
        	<200912151028.41350.donn.ingle@gmail.com>
        	<23739e0a0912150112p3c22be44jcae290a3060f3196@mail.gmail.com>
        Message-ID: <200912151258.54268.donn.ingle@gmail.com>
        
        On Tuesday 15 December 2009 11:12:21 Martijn Arts wrote:
        > You could do some really awesome stuff with that! I love the webpage
        >  example where you zoom in on the exclamation mark and there's a new page.
        > 
        It is very cool, but I would inject a note of caution here: I'd a hate a zui 
        to become a case of "hunt-the-zoom."  A link is a link. They already work very 
        well, click and it goes to the page. 
         I find the notion of minute "hot" areas to be a little obscure -- Quick! Zoom 
        into the last full-stop, it's a whole word in there! 
        What I would enjoy is when you click a link - it zooms into the sub-page so 
        you get a feeling of traversal. Back buttons would zoom out again. Add to that 
        a kind of birds'-eye view of one's history (like a thumbnails node-graph of 
        some kind) and it would be perfect!
        
        \d
        -- 
        \/\/ave: donn.ingle at googlewave.com
        home: http://otherwise.relics.co.za/
        2D vector animation : https://savannah.nongnu.org/projects/things/
        Font manager : https://savannah.nongnu.org/projects/fontypython/
        
        
        From davea at ieee.org  Tue Dec 15 06:30:10 2009
        From: davea at ieee.org (Dave Angel)
        Date: Tue, 15 Dec 2009 06:30:10 -0500
        Subject: print format
        In-Reply-To: 
        References: <4b26c1af$0$8863$4fafbaef@reader5.news.tin.it>	<4B27024B.3060902@ieee.org>
        	
        Message-ID: <4B277342.1090903@ieee.org>
        
        Gabriel Genellina wrote:
        > 
        En Tue, > 15 Dec 2009 00:28:11 -0300, Dave Angel escribi?: >> mattia wrote: > >>> Hi all, I wanto to print just the first 5 characters of a string, >>> why this doesn't work (py3.1)? >>> >>>>>> print("{0:5}".format("123456789")) >>>>>> >>> 123456789 >>> I know I could use print("123456789"[:5]), yeah it's a stupid >>> example, but isn't format for string formatting? >>> >> The width field of the format is a *minimum* width. So you can use >> it to force padding, but not truncation. If you need the string >> truncated, just use slicing, as you already showed. > > Or use the .precision specifier: > > py> "{0:.5}".format("123412341234") > '12341' > > {0:5.5} has the same effect. See > http://docs.python.org/library/string.html#format-string-syntax > Whoa! i never realized you could use precision on strings. I knew (the hard way) that it won't work on ints, but I never thought to try it on strings. Thanks. DaveA From redforks at gmail.com Tue Dec 15 07:19:30 2009 From: redforks at gmail.com (Red Forks) Date: Tue, 15 Dec 2009 20:19:30 +0800 Subject: Interesting things of 'getattr' and 'setattr' Message-ID: <3f18b3f10912150419x79da1636oade026d57ef27a97@mail.gmail.com> I don't know it is a feature, or implement detail: >>> class C(object): pass ... >>> c = C() >>> setattr(c, ' ', 3) >>> getattr(c, ' ') 3 >>> setattr(c, 'with blank', 4) >>> getattr(c, 'with blank') 4 getattr / setattr seems treat any string as attribute name. From anh.hai.trinh at gmail.com Tue Dec 15 07:42:12 2009 From: anh.hai.trinh at gmail.com (Anh Hai Trinh) Date: Tue, 15 Dec 2009 04:42:12 -0800 (PST) Subject: Seek support for new slice syntax PEP. References: <8e5054b1-8424-4633-a52e-1d9dcd1637b6@c34g2000yqn.googlegroups.com> Message-ID: <9ac83631-d0a9-4570-b2df-dd6c5232d72d@u25g2000prh.googlegroups.com> > ? ? ? ? > from numpy import s_ > ? ? ? ? > s_[1:2:3] > ? ? ? ? slice(1, 2, 3) > ? ? ? ? > s_[1:2:3, ..., 4:5] > ? ? ? ? (slice(1, 2, 3), Ellipsis, slice(4, 5, None)) > > Or would it be possible to define "slice" itself so that it implements > __getitem__ and __getslice__? Indeed! Python 2.6.4 (r264:75706, Oct 27 2009, 06:25:13) [GCC 4.4.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> class slice(object): ... @staticmethod ... def __getitem__(sliceobj): ... return sliceobj >>> slice = slice() >>> slice[:] slice(None, None, None) >>> slice[1::-1] slice(1, None, -1) >>> range(10).__getitem__(slice[::2]) [0, 2, 4, 6, 8] ----aht From stefan_ml at behnel.de Tue Dec 15 08:20:54 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 15 Dec 2009 14:20:54 +0100 Subject: Interesting things of 'getattr' and 'setattr' In-Reply-To: References: Message-ID: <4b278d36$0$6574$9b4e6d93@newsspool3.arcor-online.net> Red Forks, 15.12.2009 13:19: > I don't know it is a feature, or implement detail: > > >>> class C(object): pass > ... > >>> c = C() > >>> setattr(c, ' ', 3) > >>> getattr(c, ' ') > 3 > >>> setattr(c, 'with blank', 4) > >>> getattr(c, 'with blank') > 4 > > getattr / setattr seems treat any string as attribute name. Feature. We're all adults. Stefan From rewonka at gmail.com Tue Dec 15 08:39:54 2009 From: rewonka at gmail.com (rewonka) Date: Tue, 15 Dec 2009 05:39:54 -0800 (PST) Subject: pyqt4 eric4 generated gui custom dialog open Message-ID: <1cbf59d3-6601-4dde-9c36-2a37951783b2@g26g2000yqe.googlegroups.com> Hi, I've made a little application with mainwindow and one dialog (something like input dialog). I can't open the input dialog from my mainwindow I tried to open the dialog with a button, here is a code: @pyqtSignature("") def on_BtnAdd_clicked(self): """ Open input dialog for some data input """ Dialog = QDialog() ui = DlgAdd() ui.setupUi(Dialog) Dialog.show() and if I clicked the button , it's like the dialog open and disappear. I searched a lot and found , that i need something to connect, but i didn't found how (exactly source code). On the dialog i have two button (OK,Cancel). As i saw the generated code for pyqt has line like this: QtCore.QMetaObject.connectSlotsByName(MainWindow) I think that's mean i don't need to connect, if i have the function for it,but I don't know how to write?? Thank for Help, Rewonka From jan.langer at etit.tu-chemnitz.de Tue Dec 15 09:17:20 2009 From: jan.langer at etit.tu-chemnitz.de (Jan Langer) Date: Tue, 15 Dec 2009 15:17:20 +0100 Subject: sys.stderr and PyErr_WriteUnraisable Message-ID: Hi all, I am using Python 2.6 and with the following code I expect a different result: from test.test_support import captured_output with captured_output("stderr") as stderr: def g(): try: g() except RuntimeError,e: pass g() print stderr.getvalue() I expect the ignored exceptions to be printed into the StringIO object stderr. With this code there are no warnings on the command line, but getvalue() returns nothing. I looked a little into Python and the warnings are printed from PyErr_WriteUnraisable to sys.stderr. Is this code supposed to work as I expect it or am I missing something? thanks, Jan From victorsubervi at gmail.com Tue Dec 15 10:30:23 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Tue, 15 Dec 2009 11:30:23 -0400 Subject: (OT) Where Are Cookies Stored? Message-ID: <4dc0cfea0912150730w1d0c131agb258029b3e9a21ca@mail.gmail.com> Hi; I've googled, found where cookies are supposed to be, the folders and files don't exist. I've opened my latest and greatest FF and seen cookies in there, but when I search for the name of the cookie in the C: dir, it's not there...anywhere. I've made sure no folders/files are hidden and I still can't find them. In as administrator. What up? XP OS I need to get in so I can learn how to program with cookies. Victor -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Tue Dec 15 10:44:39 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 15 Dec 2009 12:44:39 -0300 Subject: sys.stderr and PyErr_WriteUnraisable References: Message-ID: En Tue, 15 Dec 2009 11:17:20 -0300, Jan Langer escribi?: > from test.test_support import captured_output > with captured_output("stderr") as stderr: > def g(): > try: > g() > except RuntimeError,e: > pass > g() > print stderr.getvalue() > > I expect the ignored exceptions to be printed into the StringIO object > stderr. With this code there are no warnings on the command line, but > getvalue() returns nothing. If sys.stderr is not a real file, no error gets printed. PyErr_WriteUnraisable calls PyFile_WriteString, which checks for non-file objects and only writes to them when no error is set. Seems to be a safety measure. -- Gabriel Genellina From victorsubervi at gmail.com Tue Dec 15 10:50:37 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Tue, 15 Dec 2009 11:50:37 -0400 Subject: (OT) Where Are Cookies Stored? In-Reply-To: References: <4dc0cfea0912150730w1d0c131agb258029b3e9a21ca@mail.gmail.com> Message-ID: <4dc0cfea0912150750k5d69e860qa6139727c09f42c4@mail.gmail.com> On Tue, Dec 15, 2009 at 11:42 AM, geremy condra wrote: > Was on the first[1], second, and third google hits for me. Also, given the > number of web-related questions you're asking, you may want to look > into evolt's lists[2]. > > Geremy Condra > > [1]: > http://askville.amazon.com/Firefox-store-cookies/AnswerViewer.do?requestId=5709350 > [2]: http://lists.evolt.org/mailman/listinfo/thelist > Yeah, did all that and found them thru FF. I can delete them. I'd like to open the cookie I'm setting, and haven't figured out how to do that yet. That second link was broken. It's nice, however, that I can clear out cookies and see if I'm setting one at all. Still, if I can find where they're located, even better. V -------------- next part -------------- An HTML attachment was scrubbed... URL: From tavares at fe.up.pt Tue Dec 15 10:51:47 2009 From: tavares at fe.up.pt (tavares at fe.up.pt) Date: Tue, 15 Dec 2009 07:51:47 -0800 (PST) Subject: =?windows-1252?Q?Workshop_=93Medical_Imaging_Systems=94_within_EUROME?= =?windows-1252?Q?DIA_2010_=96_Announce_=26_Call_for_Papers?= Message-ID: <022334fc-7110-4213-b0cb-d61213786de8@p8g2000yqb.googlegroups.com> -------------------------------------------------------------------------------------------------------------------------------- Workshop ?Medical Imaging Systems? within EUROSIS EUROMEDIA 2010 April 14-16, 2010, UPV Gandia, Gandia, Spain http://www.eurosis.org/cms/?q=node/1103 -------------------------------------------------------------------------------------------------------------------------------- Dear Colleague, Efficient and powerful medical imaging systems have been assuming a growing and crucial importance in medicine, allowing a deep examination and understanding on the human body and, therefore, playing an essential role for adequate diagnosis, treatment and follow- up. 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. Due to your research activities, we would like to invite you to submit a contributed paper for the Workshop ?Medical Imaging Systems?. WORKSHOP TOPICS (not exhaustive): - 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; - Telemedicine systems and their applications; - Assistive technology; - Computational anatomy; - Medical robots; - Imaging devices; - Hardware systems. IMPORTANT DATES: - Submission Deadline (extended abstract or full paper): February 5, 2010; - Notification of Acceptance or Rejection: February 15, 2010; - Authors provide camera-ready manuscript: March 20, 2010; - Conference Events: April 14-16, 2010. SCIENTIFIC COMMITTEE: Ad?lia Sequeira, Instituto Superior T?cnico, Portugal Alberto De Santis, Universit? degli Studi di Roma "La Sapienza", Italy Aledir Silveira Pereira, S?o Paulo State University, Brazil Ana Mafalda Reis, University of Porto, Portugal Anton Vernet, University Rovira i Virgili, Spain Arrate Mu?oz Barrutia, University of Navarra, Spain Bego?a Calvo Calzada, University of Zaragoza, Spain Bernard Gosselin, Faculte Polytechnique de Mons, Belgium Christos E. Constantinou, Stanford University School of Medicine, USA Dinggang Shen, UNC-CH School of Medicine, USA Emmanuel A. Audenaert, Ghent University Hospital, Belgium Enrique Alegre Guti?rrez, University of Le?n, Spain Fiorella Sgallari, University of Bologna, Italy Jorge M. G. Barbosa, University of Porto, Portugal Lyuba Alboul, Sheffield Hallam University, UK Mahmoud El-Sakka, The University of Western Ontario London, Canada Manuel Gonz?lez Hidalgo- Balearic Islands University, Spain Maria Elizete Kunkel, Universit?t Ulm, Germany Maria Petrou, Imperial College London, UK Miguel Velhote Correia, University of Porto, Portugal Paola Lecca, The Microsoft Research, University of Trento, Italy Petia Radeva, Autonomous University of Barcelona, Spain Renato Natal Jorge, University of Porto, Portugal Sabina Tangaro, National Institute of Nuclear Physics, Italy Teresa Mascarenhas, University of Porto, Portugal Vassili Kovalev, University of Surrey, UK Yongjie Zhang, Carnegie Mellon University, USA Zeyun Yu, University of Wisconsin at Milwaukee, USA For further details please see the conference website at: http://www.eurosis.org/cms/?q=node/1103 We are looking forward to see you in Gandia next April. Yours sincerely, Jo?o Manuel R. S. Tavares, University of Porto, Portugal Daniela Iacoviello, Sapienza University of Rome, Italy (Workshop organizers) From gagsl-py2 at yahoo.com.ar Tue Dec 15 11:03:07 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 15 Dec 2009 13:03:07 -0300 Subject: (OT) Where Are Cookies Stored? References: <4dc0cfea0912150730w1d0c131agb258029b3e9a21ca@mail.gmail.com> Message-ID: En Tue, 15 Dec 2009 12:30:23 -0300, Victor Subervi escribi?: > I've googled, found where cookies are supposed to be, the folders and > files > don't exist. I've opened my latest and greatest FF and seen cookies in > there, but when I search for the name of the cookie in the C: dir, it's > not > there...anywhere. I've made sure no folders/files are hidden and I still > can't find them. In as administrator. What up? XP OS I need to get in so > I > can learn how to program with cookies. How the browser stores its cookies should be irrelevant. Whenever a server response contains a Set-Cookie header, the browser saves the cookie. When the client issues a request that matches a saved cookie, it adds a Cookie header with the cookie. From the server POV, you don't care how the cookie is stored. -- Gabriel Genellina From andrea.gavana at gmail.com Tue Dec 15 11:08:01 2009 From: andrea.gavana at gmail.com (Infinity77) Date: Tue, 15 Dec 2009 08:08:01 -0800 (PST) Subject: Where is PyMethod_GET_CLASS in Python 3? Message-ID: <1799a93b-5eb8-4818-ab94-7aa4108fcea1@j24g2000yqa.googlegroups.com> Hi All, When building C extensions In Python 2.X, there was a magical PyMethod_GET_CLASS implemented like this: #define PyMethod_GET_CLASS(meth) \ (((PyMethodObject *)meth) -> im_class) It looks like Python 3 has wiped out the "im_class" attribute. Which is the alternative was to handle this case in Python 3? How do I find to which class this particular method belongs to? BTW, it's very, very, *very* hard to find any possible reference to help migrating existing C extensions from Python 2.X to Python 3. Thank you for your suggestions. Andrea. From jan.langer at etit.tu-chemnitz.de Tue Dec 15 11:20:35 2009 From: jan.langer at etit.tu-chemnitz.de (Jan Langer) Date: Tue, 15 Dec 2009 17:20:35 +0100 Subject: sys.stderr and PyErr_WriteUnraisable In-Reply-To: References: Message-ID: Gabriel Genellina schrieb: > En Tue, 15 Dec 2009 11:17:20 -0300, Jan Langer > escribi?: > >> from test.test_support import captured_output >> with captured_output("stderr") as stderr: >> def g(): >> try: >> g() >> except RuntimeError,e: >> pass >> g() >> print stderr.getvalue() >> >> I expect the ignored exceptions to be printed into the StringIO object >> stderr. With this code there are no warnings on the command line, but >> getvalue() returns nothing. > > If sys.stderr is not a real file, no error gets printed. > PyErr_WriteUnraisable calls PyFile_WriteString, which checks for > non-file objects and only writes to them when no error is set. > Seems to be a safety measure. > thanks for the quick answer. PyErr_WriteUnraisable calls PyErr_Fetch first, which should clear the error indicator, and the PyErr_Occurred in PyFile_WriteString should return false. From claird.visiprise at gmail.com Tue Dec 15 11:22:20 2009 From: claird.visiprise at gmail.com (Cameron Laird) Date: Tue, 15 Dec 2009 08:22:20 -0800 (PST) Subject: Python-URL! - weekly Python news and links (Dec 15) Message-ID: <79f1ba0f-0905-4f63-9700-2b905d2f3196@z41g2000yqz.googlegroups.com> This installment, like all those for several months, was authored by Gabriel Genellina. We have hopes of correcting the attribution before year's-end. QOTW: "Plus, it's not something that's never foolproof." - Carl Banks, daring negater http://groups.google.com/group/comp.lang.python/msg/e8f3adbf2cc31514 Several graph libraries are available; which one is the best? maybe they should be merged? http://groups.google.com/group/comp.lang.python/t/785d100681f7d101/ http://groups.google.com/group/comp.lang.python/t/7e65ca66cd7b511/ list(generator) and the equivalent list comprehension are not always equivalent: http://groups.google.com/group/comp.lang.python/t/ae70dfa12677c1d5/ A succint way to parse a string of name=value pairs: http://groups.google.com/group/comp.lang.python/t/dc725717e63d6295/ Keep only unique elements in a list - and the perils of wrongly defining __hash__: http://groups.google.com/group/comp.lang.python/t/80491b9bc2f45547/ Python does not have a switch statement - how to overcome that? http://groups.google.com/group/comp.lang.python/t/9af90ddc7652beb0/ What are the advantages of an explicit "self"? http://groups.google.com/group/comp.lang.python/t/17a3369aef70fd38/ A new guy in the neighborhood, recently moved from PHP: http://groups.google.com/group/comp.lang.python/t/6e91d87a9a3a3edb/ http://groups.google.com/group/comp.lang.python4c295a7ca96f65c3101/ Another convert, this time coming from Perl-land: http://groups.google.com/group/comp.lang.python/t/22edc1c7eef569d5/ ======================================================================== 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 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 enthusiasts": http://pythonpapers.org/ The Python Magazine is a technical monthly devoted to Python: http://pythonmagazine.com Readers have recommended the "Planet" site: http://planet.python.org comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/group/comp.lang.python.announce/topics Python411 indexes "podcasts ... to help people learn Python ..." Updates appear more-than-weekly: http://www.awaretek.com/python/index.html The Python Package Index catalogues packages. http://www.python.org/pypi/ 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/donations/ The Summary of Python Tracker Issues is an automatically generated report summarizing new bugs, closed ones, and patch submissions. http://search.gmane.org/?author=status%40bugs.python.org&group=gmane.com p.python.devel&sort=date 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://code.activestate.com/recipes/langs/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, see: http://www.python.org/channews.rdf 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/ 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 Enjoy the *Python Magazine*. http://pymag.phparch.com/ *Py: the Journal of the Python Language* http://www.pyzine.com Dr.Dobb's Portal is another source of Python news and articles: http://www.ddj.com/TechSearch/searchResults.jhtml?queryText=python and Python articles regularly appear at IBM DeveloperWorks: http://www.ibm.com/developerworks/search/searchResults.jsp?searchSite=dW &searchScope=dW&encodedQuery=python&rankprofile=8 Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://search.gmane.org/?query=python+URL+weekly+news+links&group=gmane.comp.p ython.general&sort=date http://groups.google.com/groups/search?q=Python-URL!+group%3Acomp.lang.python& start=0&scoring=d& http://lwn.net/Search/DoSearch?words=python-url&ctype3=yes&cat_25=yes 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 python-url at phaseit.net Tue Dec 15 11:35:53 2009 From: python-url at phaseit.net (Gabriel Genellina) Date: Tue, 15 Dec 2009 16:35:53 +0000 (UTC) Subject: Python-URL! - weekly Python news and links (Dec 15) Message-ID: QOTW: "Plus, it's not something that's never foolproof." - Carl Banks, daring negater http://groups.google.com/group/comp.lang.python/msg/e8f3adbf2cc31514 Several graph libraries are available; which one is the best? maybe they should be merged? http://groups.google.com/group/comp.lang.python/t/785d100681f7d101/ http://groups.google.com/group/comp.lang.python/t/7e65ca66cd7b511/ list(generator) and the equivalent list comprehension are not always equivalent: http://groups.google.com/group/comp.lang.python/t/ae70dfa12677c1d5/ A succint way to parse a string of name=value pairs: http://groups.google.com/group/comp.lang.python/t/dc725717e63d6295/ Keep only unique elements in a list - and the perils of wrongly defining __hash__: http://groups.google.com/group/comp.lang.python/t/80491b9bc2f45547/ Python does not have a switch statement - how to overcome that? http://groups.google.com/group/comp.lang.python/t/9af90ddc7652beb0/ What are the advantages of an explicit "self"? http://groups.google.com/group/comp.lang.python/t/17a3369aef70fd38/ A new guy in the neighborhood, recently moved from PHP: http://groups.google.com/group/comp.lang.python/t/6e91d87a9a3a3edb/ http://groups.google.com/group/comp.lang.python4c295a7ca96f65c3101/ Another convert, this time coming from Perl-land: http://groups.google.com/group/comp.lang.python/t/22edc1c7eef569d5/ ======================================================================== 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 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 enthusiasts": http://pythonpapers.org/ The Python Magazine is a technical monthly devoted to Python: http://pythonmagazine.com Readers have recommended the "Planet" site: http://planet.python.org comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/group/comp.lang.python.announce/topics Python411 indexes "podcasts ... to help people learn Python ..." Updates appear more-than-weekly: http://www.awaretek.com/python/index.html The Python Package Index catalogues packages. http://www.python.org/pypi/ 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/donations/ The Summary of Python Tracker Issues is an automatically generated report summarizing new bugs, closed ones, and patch submissions. http://search.gmane.org/?author=status%40bugs.python.org&group=gmane.comp.python.devel&sort=date 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://code.activestate.com/recipes/langs/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, see: http://www.python.org/channews.rdf 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/ 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 Enjoy the *Python Magazine*. http://pymag.phparch.com/ *Py: the Journal of the Python Language* http://www.pyzine.com Dr.Dobb's Portal is another source of Python news and articles: http://www.ddj.com/TechSearch/searchResults.jhtml?queryText=python and Python articles regularly appear at IBM DeveloperWorks: http://www.ibm.com/developerworks/search/searchResults.jsp?searchSite=dW&searchScope=dW&encodedQuery=python&rankprofile=8 Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://search.gmane.org/?query=python+URL+weekly+news+links&group=gmane.comp.python.general&sort=date http://groups.google.com/groups/search?q=Python-URL!+group%3Acomp.lang.python&start=0&scoring=d& http://lwn.net/Search/DoSearch?words=python-url&ctype3=yes&cat_25=yes 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 jan.langer at etit.tu-chemnitz.de Tue Dec 15 11:44:23 2009 From: jan.langer at etit.tu-chemnitz.de (Jan Langer) Date: Tue, 15 Dec 2009 17:44:23 +0100 Subject: sys.stderr and PyErr_WriteUnraisable In-Reply-To: References: Message-ID: Jan Langer schrieb: > Gabriel Genellina schrieb: >> En Tue, 15 Dec 2009 11:17:20 -0300, Jan Langer >> escribi?: >> >>> from test.test_support import captured_output >>> with captured_output("stderr") as stderr: >>> def g(): >>> try: >>> g() >>> except RuntimeError,e: >>> pass >>> g() >>> print stderr.getvalue() >>> >>> I expect the ignored exceptions to be printed into the StringIO >>> object stderr. With this code there are no warnings on the command >>> line, but getvalue() returns nothing. >> >> If sys.stderr is not a real file, no error gets printed. >> PyErr_WriteUnraisable calls PyFile_WriteString, which checks for >> non-file objects and only writes to them when no error is set. >> Seems to be a safety measure. >> > > thanks for the quick answer. PyErr_WriteUnraisable calls PyErr_Fetch > first, which should clear the error indicator, and the PyErr_Occurred in > PyFile_WriteString should return false. When thinking about it, it might be possible that the writing to the StringIO object will hit the recursion limit, too. But then I would expect a inifinte loops of 1 write to stderr 2 raise recursion exception 3 detect the error 4 call writeunraisable 5 write to stderr 6 loop to 2 But I have no overview happens exactly. :-) From victorsubervi at gmail.com Tue Dec 15 11:46:55 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Tue, 15 Dec 2009 12:46:55 -0400 Subject: (OT) Where Are Cookies Stored? In-Reply-To: References: <4dc0cfea0912150730w1d0c131agb258029b3e9a21ca@mail.gmail.com> Message-ID: <4dc0cfea0912150846xdf8e139tbd959a2919c0359f@mail.gmail.com> On Tue, Dec 15, 2009 at 12:03 PM, Gabriel Genellina wrote: > En Tue, 15 Dec 2009 12:30:23 -0300, Victor Subervi < > victorsubervi at gmail.com> escribi?: > > > I've googled, found where cookies are supposed to be, the folders and >> files >> don't exist. I've opened my latest and greatest FF and seen cookies in >> there, but when I search for the name of the cookie in the C: dir, it's >> not >> there...anywhere. I've made sure no folders/files are hidden and I still >> can't find them. In as administrator. What up? XP OS I need to get in so I >> can learn how to program with cookies. >> > > How the browser stores its cookies should be irrelevant. Whenever a server > response contains a Set-Cookie header, the browser saves the cookie. When > the client issues a request that matches a saved cookie, it adds a Cookie > header with the cookie. From the server POV, you don't care how the cookie > is stored. > k. Thanks. V -------------- next part -------------- An HTML attachment was scrubbed... URL: From sjdevnull at yahoo.com Tue Dec 15 12:10:38 2009 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: Tue, 15 Dec 2009 09:10:38 -0800 (PST) Subject: read text file byte by byte References: <4519638f-c62b-46f6-ba1e-619035d48036@j14g2000yqm.googlegroups.com> <00ae1204$0$15654$c3e8da3@news.astraweb.com> Message-ID: <155a9e1e-7a2c-4e9d-ba71-03ea1e288e3b@9g2000yqa.googlegroups.com> On Dec 14, 11:44?pm, Terry Reedy wrote: > On 12/14/2009 7:37 PM, Gabriel Genellina wrote: > > > > > En Mon, 14 Dec 2009 18:09:52 -0300, Nobody escribi?: > >> On Sun, 13 Dec 2009 22:56:55 -0800, sjdevn... at yahoo.com wrote: > > >>> The 3.1 documentation specifies that file.read returns bytes: > > >>> Does it need fixing? > > >> There are no file objects in 3.x. The file() function no longer > >> exists. The return value from open(), will be an instance of > >> _io. depending upon the mode, e.g. _io.TextIOWrapper for 'r', > >> _io.BufferedReader for 'rb', _io.BufferedRandom for 'w+b', etc. > > >>http://docs.python.org/3.1/library/io.html > > >> io.IOBase.read() doesn't exist, io.RawIOBase.read(n) reads n bytes, > >> io.TextIOBase.read(n) reads n characters. > > > So basically this section [1] should not exist, or be completely rewritten? > > At least the references to C stdio library seem wrong to me. > > > [1]http://docs.python.org/3.1/library/stdtypes.html#file-objects > > I agree.http://bugs.python.org/issue7508 > > Terry Jan Reedy Thanks, Terry. From tony at tonyburrows.com Tue Dec 15 12:37:08 2009 From: tony at tonyburrows.com (Tony) Date: Tue, 15 Dec 2009 17:37:08 +0000 Subject: accessing gmail Message-ID: I'm having trouble getting to gmail messages. I can access my googlemail account through imap with no problems, that's an old one. The problem is trying to get to my current gmail account, which is actually tony at tonyburrows.com. The page shows up as mail.google.com/a/tonyburrows.com and I can't see how to get at it. mail = imaplib.IMAP4_SSL('imap.gmail.com, 993) mail.login(username, password) logs me in to my googlemail account and lets me collect mail in that one, but how do I get to the gmail one? Tony From unlearned at gmail.com Tue Dec 15 12:41:02 2009 From: unlearned at gmail.com (Intchanter / Daniel Fackrell) Date: Tue, 15 Dec 2009 09:41:02 -0800 (PST) Subject: accessing gmail References: Message-ID: <899b08c6-3162-4911-841e-fbc03dbeaa37@r24g2000prf.googlegroups.com> http://mail.google.com/support/bin/answer.py?hl=en&answer=77654 From bearophileHUGS at lycos.com Tue Dec 15 12:48:51 2009 From: bearophileHUGS at lycos.com (Bearophile) Date: Tue, 15 Dec 2009 09:48:51 -0800 (PST) Subject: Seek support for new slice syntax PEP. References: <8e5054b1-8424-4633-a52e-1d9dcd1637b6@c34g2000yqn.googlegroups.com> <00b03121$0$15654$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano: > I've lost all enthusiasm for discussing language enhancements That's probably the main downside of the moratorium. Humans need to play some to keep their will to work and improve things. Bye, bearophile From aahz at pythoncraft.com Tue Dec 15 12:49:26 2009 From: aahz at pythoncraft.com (Aahz) Date: 15 Dec 2009 09:49:26 -0800 Subject: good code to study References: <55477b4a-2095-4e52-9f1c-8337d421cc40@j9g2000prh.googlegroups.com> Message-ID: In article <55477b4a-2095-4e52-9f1c-8337d421cc40 at j9g2000prh.googlegroups.com>, Michael wrote: > >I want to improve my knowledge of Python (note: I'm still on 2.5 or >2.6) by studying good existing code, especially GUI programs. Any >suggestions? I'm looking at the eric source code now, for starters. Also look at IDLE. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Looking back over the years, after I learned Python I realized that I never really had enjoyed programming before. From detlev at die-offenbachs.de Tue Dec 15 12:56:40 2009 From: detlev at die-offenbachs.de (Detlev Offenbach) Date: Tue, 15 Dec 2009 18:56:40 +0100 Subject: pyqt4 eric4 generated gui custom dialog open References: <1cbf59d3-6601-4dde-9c36-2a37951783b2@g26g2000yqe.googlegroups.com> Message-ID: rewonka wrote: > Hi, > > I've made a little application with mainwindow and one dialog > (something like input dialog). > I can't open the input dialog from my mainwindow > > I tried to open the dialog with a button, here is a code: > @pyqtSignature("") > def on_BtnAdd_clicked(self): > """ > Open input dialog for some data input > """ > Dialog = QDialog() > ui = DlgAdd() > ui.setupUi(Dialog) > Dialog.show() > > and if I clicked the button , it's like the dialog open and disappear. That is caused by the Python garbage collector removing your objects when the method is left. In order to keep the dialog, you must assign it to some class members. Alternatively you may replace "Dialog.show()" with Dialog.exec_() to get a modal dialog. Detlev > I searched a lot and found , that i need something to connect, but i > didn't found how (exactly source code). On the dialog i have two > button (OK,Cancel). > As i saw the generated code for pyqt has line like this: > QtCore.QMetaObject.connectSlotsByName(MainWindow) > I think that's mean i don't need to connect, if i have the function > for it,but I don't know how to write?? > > Thank for Help, > Rewonka -- Detlev Offenbach detlev at die-offenbachs.de From victorsubervi at gmail.com Tue Dec 15 13:05:29 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Tue, 15 Dec 2009 14:05:29 -0400 Subject: Calling Cookie Values Message-ID: <4dc0cfea0912151005g7cf389ddx2e3d9d5a62338344@mail.gmail.com> Hi; import Cookie ... cookie = Cookie.SimpleCookie() cookieString = os.environ.get('HTTP_COOKIE') if not cookieString: cExpires, cPath, cComment, cDomain, cMaxAge, cVersion = myCookie() cookie['lastvisit'] = str(time.time()) cookie['lastvisit']['expires'] = cExpires cookie['lastvisit']['path'] = cPath cookie['lastvisit']['comment'] = cComment cookie['lastvisit']['domain'] = cDomain cookie['lastvisit']['max-age'] = cMaxAge cookie['lastvisit']['version'] = cVersion cookieFlag = 'new' else: cookieFlag = 'old' print cookie['lastvisit']['expires'].value Throws this error: /var/www/html/angrynates.com/cart/cart.py 192 193 ''' 194 195 cart() 196 cart = /var/www/html/angrynates.com/cart/cart.py in cart() 32 else: 33 cookieFlag = 'old' 34 print cookie['lastvisit']['expires'].value 35 # Don't know what to do with this. It's for when client won't accept cookies 36 # sessionDir = os.environ['DOCUMENT_ROOT'] + '/tmp/.session' cookie = , ].value undefined KeyError: 'lastvisit' args = ('lastvisit',) Please advise. TIA, Victor -------------- next part -------------- An HTML attachment was scrubbed... URL: From rami.chowdhury at gmail.com Tue Dec 15 13:24:23 2009 From: rami.chowdhury at gmail.com (Rami Chowdhury) Date: Tue, 15 Dec 2009 10:24:23 -0800 Subject: Calling Cookie Values In-Reply-To: <4dc0cfea0912151005g7cf389ddx2e3d9d5a62338344@mail.gmail.com> References: <4dc0cfea0912151005g7cf389ddx2e3d9d5a62338344@mail.gmail.com> Message-ID: <2f79f590912151024i107d0ec9k1be7a1e00175fa66@mail.gmail.com> On Tue, Dec 15, 2009 at 10:05, Victor Subervi wrote: > Hi; > > import Cookie > ... > ? cookie = Cookie.SimpleCookie() > ? cookieString = os.environ.get('HTTP_COOKIE') > ? if not cookieString: [snip] > ? else: > ??? cookieFlag = 'old' > ??? print cookie['lastvisit']['expires'].value What does cookie contain, at this point, in the else branch? -------- Rami Chowdhury "Never assume malice when stupidity will suffice." -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) From python at mrabarnett.plus.com Tue Dec 15 13:36:17 2009 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 15 Dec 2009 18:36:17 +0000 Subject: Calling Cookie Values In-Reply-To: <4dc0cfea0912151005g7cf389ddx2e3d9d5a62338344@mail.gmail.com> References: <4dc0cfea0912151005g7cf389ddx2e3d9d5a62338344@mail.gmail.com> Message-ID: <4B27D721.2010707@mrabarnett.plus.com> Victor Subervi wrote: > Hi; > > import Cookie > ... > cookie = Cookie.SimpleCookie() > cookieString = os.environ.get('HTTP_COOKIE') > if not cookieString: > cExpires, cPath, cComment, cDomain, cMaxAge, cVersion = myCookie() > cookie['lastvisit'] = str(time.time()) The following lines aren't going to work. You're setting a value to a string and then trying to use that string as a dict... > cookie['lastvisit']['expires'] = cExpires > cookie['lastvisit']['path'] = cPath > cookie['lastvisit']['comment'] = cComment > cookie['lastvisit']['domain'] = cDomain > cookie['lastvisit']['max-age'] = cMaxAge > cookie['lastvisit']['version'] = cVersion > cookieFlag = 'new' > else: > cookieFlag = 'old' > print cookie['lastvisit']['expires'].value > > Throws this error: > > /var/www/html/angrynates.com/cart/cart.py > > 192 > 193 ''' > 194 > 195 cart() > 196 > cart = > /var/www/html/angrynates.com/cart/cart.py > in cart() > 32 else: > 33 cookieFlag = 'old' > 34 print cookie['lastvisit']['expires'].value > 35 # Don't know what to do with this. It's for when client won't > accept cookies > 36 # sessionDir = os.environ['DOCUMENT_ROOT'] + '/tmp/.session' > cookie = , ].value undefined > > KeyError: 'lastvisit' > args = ('lastvisit',) > > Please advise. > You've just created a cookie, but are trying to get a value without having set it first! From your.master at gmail.com Tue Dec 15 14:02:18 2009 From: your.master at gmail.com (Brandon Devine) Date: Tue, 15 Dec 2009 11:02:18 -0800 (PST) Subject: dictionary with tuple keys References: <6cbdfcfd-8731-4538-aeba-db771794a5bb@u25g2000prh.googlegroups.com> <7xaaxky9hq.fsf@ruckus.brouhaha.com> Message-ID: So grateful! Thanks to all. The breadth of Python continues to amaze me, as does your generosity. ("Relative clarity like relative beauty is in the eye of the beholder, and few parents have ugly children"... fantastic!) Brandon From victorsubervi at gmail.com Tue Dec 15 14:12:53 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Tue, 15 Dec 2009 15:12:53 -0400 Subject: Calling Cookie Values In-Reply-To: <4B27D721.2010707@mrabarnett.plus.com> References: <4dc0cfea0912151005g7cf389ddx2e3d9d5a62338344@mail.gmail.com> <4B27D721.2010707@mrabarnett.plus.com> Message-ID: <4dc0cfea0912151112n235fa28vd509a36ddfc4ade9@mail.gmail.com> On Tue, Dec 15, 2009 at 2:36 PM, MRAB wrote: > You've just created a cookie, but are trying to get a value without > having set it first! > LOL! Rewrote code thus: cookie = os.environ.get('HTTP_COOKIE') if not cookie: cookie = Cookie.SimpleCookie() cExpires, cPath, cComment, cDomain, cMaxAge, cVersion = myCookie() cookie['lastvisit'] = str(time.time()) cookie['lastvisit']['expires'] = cExpires cookie['lastvisit']['path'] = cPath cookie['lastvisit']['comment'] = cComment cookie['lastvisit']['domain'] = cDomain cookie['lastvisit']['max-age'] = cMaxAge cookie['lastvisit']['version'] = cVersion cookieFlag = 'new' else: cookieFlag = 'old' print cookie['lastvisit']['expires'].value Got this error: /var/www/html/angrynates.com/cart/cart.py 191 192 ''' 193 194 cart() 195 cart = /var/www/html/angrynates.com/cart/cart.py in cart() 31 else: 32 cookieFlag = 'old' 33 print cookie['lastvisit']['expires'].value 34 # Don't know what to do with this. It's for when client won't accept cookies 35 # sessionDir = os.environ['DOCUMENT_ROOT'] + '/tmp/.session' cookie = 'lastvisit=1260898013.65; lastvisit=1260898315.01', ].value undefined TypeError: string indices must be integers args = ('string indices must be integers',) Please advise. TIA, V -------------- next part -------------- An HTML attachment was scrubbed... URL: From vmail at mycircuit.org Tue Dec 15 14:26:04 2009 From: vmail at mycircuit.org (Peter) Date: Tue, 15 Dec 2009 20:26:04 +0100 Subject: AttributeError: logging module bug ? In-Reply-To: <4dc0cfea0912151112n235fa28vd509a36ddfc4ade9@mail.gmail.com> References: <4dc0cfea0912151005g7cf389ddx2e3d9d5a62338344@mail.gmail.com> <4B27D721.2010707@mrabarnett.plus.com> <4dc0cfea0912151112n235fa28vd509a36ddfc4ade9@mail.gmail.com> Message-ID: <4B27E2CC.5030903@mycircuit.org> on python 2.6 the following code raises an AttributeError: #!/usr/bin/env python import os.path as p import logging, logging.config class Logger(object): def load_config(self): logging.config.fileConfig(p.join(p.dirname(__file__),'logging.cfg')) logger = Logger() logger.load_config() ====================================== Traceback (most recent call last): File "/p/python/exp/of_logging/logging_bug.py", line 11, in logger.load_config() File "/p/python/exp/of_logging/logging_bug.py", line 8, in load_config logging.config.fileConfig(p.join(p.dirname(__file__),'logging.cfg')) File "/usr/local/python2.6/lib/python2.6/logging/config.py", line 76, in fileConfig formatters = _create_formatters(cp) File "/usr/local/python2.6/lib/python2.6/logging/config.py", line 130, in _create_formatters c = _resolve(class_name) File "/usr/local/python2.6/lib/python2.6/logging/config.py", line 100, in _resolve __import__(used) File "/p/python/of/logger.py", line 144, in of_logger.load_config(p.join(p.dirname(__file__),'logging.cfg')) File "/p/python/of/logger.py", line 109, in load_config logging.config.fileConfig(conffile) File "/usr/local/python2.6/lib/python2.6/logging/config.py", line 76, in fileConfig formatters = _create_formatters(cp) File "/usr/local/python2.6/lib/python2.6/logging/config.py", line 130, in _create_formatters c = _resolve(class_name) File "/usr/local/python2.6/lib/python2.6/logging/config.py", line 101, in _resolve found = getattr(found, n) AttributeError: 'module' object has no attribute 'logger' From what I understand in the source, the _resolve functions does an import of the containing module during the parsing of the config file. In the imported module, the module variable 'logger' is not defined at that moment and the function fails. However, I can not see why my code should not work. I want to have a poor-man's Singleton Logger class ( see Python Cookbook 2nd edition p.275), so I rebind 'logger' to the only instance of its class. What's the problem ? Thanks Peter From python at mrabarnett.plus.com Tue Dec 15 15:05:25 2009 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 15 Dec 2009 20:05:25 +0000 Subject: Calling Cookie Values In-Reply-To: <4dc0cfea0912151112n235fa28vd509a36ddfc4ade9@mail.gmail.com> References: <4dc0cfea0912151005g7cf389ddx2e3d9d5a62338344@mail.gmail.com> <4B27D721.2010707@mrabarnett.plus.com> <4dc0cfea0912151112n235fa28vd509a36ddfc4ade9@mail.gmail.com> Message-ID: <4B27EC05.5020100@mrabarnett.plus.com> Victor Subervi wrote: > On Tue, Dec 15, 2009 at 2:36 PM, MRAB > wrote: > > You've just created a cookie, but are trying to get a value without > having set it first! > > > LOL! Rewrote code thus: > > cookie = os.environ.get('HTTP_COOKIE') > if not cookie: > cookie = Cookie.SimpleCookie() > cExpires, cPath, cComment, cDomain, cMaxAge, cVersion = myCookie() > cookie['lastvisit'] = str(time.time()) > cookie['lastvisit']['expires'] = cExpires > cookie['lastvisit']['path'] = cPath > cookie['lastvisit']['comment'] = cComment > cookie['lastvisit']['domain'] = cDomain > cookie['lastvisit']['max-age'] = cMaxAge > cookie['lastvisit']['version'] = cVersion > cookieFlag = 'new' > else: > cookieFlag = 'old' > print cookie['lastvisit']['expires'].value > > Got this error: > > /var/www/html/angrynates.com/cart/cart.py > > 191 > 192 ''' > 193 > 194 cart() > 195 > cart = > /var/www/html/angrynates.com/cart/cart.py > in cart() > 31 else: > 32 cookieFlag = 'old' > 33 print cookie['lastvisit']['expires'].value > 34 # Don't know what to do with this. It's for when client won't > accept cookies > 35 # sessionDir = os.environ['DOCUMENT_ROOT'] + '/tmp/.session' > cookie = 'lastvisit=1260898013.65; lastvisit=1260898315.01', ].value > undefined > > TypeError: string indices must be integers > args = ('string indices must be integers',) > What you got from HTTP_COOKIE was a _string_ (or None). You then need to turn it into a cookie: cookie_string = os.environ.get('HTTP_COOKIE') if cookie_string: cookie = Cookie.SimpleCookie(cookie_string) ... else: cookie = Cookie.SimpleCookie() ... From victorsubervi at gmail.com Tue Dec 15 15:14:37 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Tue, 15 Dec 2009 16:14:37 -0400 Subject: Calling Cookie Values In-Reply-To: <4B27EC05.5020100@mrabarnett.plus.com> References: <4dc0cfea0912151005g7cf389ddx2e3d9d5a62338344@mail.gmail.com> <4B27D721.2010707@mrabarnett.plus.com> <4dc0cfea0912151112n235fa28vd509a36ddfc4ade9@mail.gmail.com> <4B27EC05.5020100@mrabarnett.plus.com> Message-ID: <4dc0cfea0912151214v255ac481te2b972549bc45fb6@mail.gmail.com> On Tue, Dec 15, 2009 at 4:05 PM, MRAB wrote: > What you got from HTTP_COOKIE was a _string_ (or None). You then need to > turn it into a cookie: > > cookie_string = os.environ.get('HTTP_COOKIE') > if cookie_string: > cookie = Cookie.SimpleCookie(cookie_string) > ... > else: > cookie = Cookie.SimpleCookie() > Ah. Thanks! V -------------- next part -------------- An HTML attachment was scrubbed... URL: From neilc at norwich.edu Tue Dec 15 15:32:57 2009 From: neilc at norwich.edu (Neil Cerutti) Date: 15 Dec 2009 20:32:57 GMT Subject: AttributeError: logging module bug ? References: <4dc0cfea0912151005g7cf389ddx2e3d9d5a62338344@mail.gmail.com> <4B27D721.2010707@mrabarnett.plus.com> <4dc0cfea0912151112n235fa28vd509a36ddfc4ade9@mail.gmail.com> Message-ID: <7oqa3pF3mh99tU1@mid.individual.net> On 2009-12-15, Peter wrote: > on python 2.6 the following code raises an AttributeError: > > #!/usr/bin/env python > import os.path as p > import logging, logging.config > > > class Logger(object): > def load_config(self): > logging.config.fileConfig(p.join(p.dirname(__file__),'logging.cfg')) __file__ is undefined in your example code, so I'm not getting the same exception as you. -- Neil Cerutti From __peter__ at web.de Tue Dec 15 15:54:59 2009 From: __peter__ at web.de (Peter Otten) Date: Tue, 15 Dec 2009 21:54:59 +0100 Subject: AttributeError: logging module bug ? References: <4dc0cfea0912151005g7cf389ddx2e3d9d5a62338344@mail.gmail.com> <4B27D721.2010707@mrabarnett.plus.com> <4dc0cfea0912151112n235fa28vd509a36ddfc4ade9@mail.gmail.com> Message-ID: Peter wrote: > on python 2.6 the following code raises an AttributeError: > > #!/usr/bin/env python > import os.path as p > import logging, logging.config > > > class Logger(object): > def load_config(self): > logging.config.fileConfig(p.join(p.dirname(__file__),'logging.cfg')) > > logger = Logger() > logger.load_config() > What's the problem ? Please provide the config file "logging.cfg" to ease debugging. Peter From invalid at invalid.invalid Tue Dec 15 16:01:32 2009 From: invalid at invalid.invalid (Grant Edwards) Date: Tue, 15 Dec 2009 21:01:32 +0000 (UTC) Subject: Calling Cookie Values References: <4dc0cfea0912151005g7cf389ddx2e3d9d5a62338344@mail.gmail.com> <4B27D721.2010707@mrabarnett.plus.com> <4dc0cfea0912151112n235fa28vd509a36ddfc4ade9@mail.gmail.com> Message-ID: > On Tue, Dec 15, 2009 at 2:36 PM, MRAB > wrote: > > You've just created a cookie, but are trying to get a value without > having set it first! > > > LOL! Rewrote code thus: > > cookie = os.environ.get('HTTP_COOKIE') > if not cookie: > cookie = Cookie.SimpleCookie() > cExpires, cPath, cComment, cDomain, cMaxAge, cVersion = myCookie() > cookie['lastvisit'] = str(time.time()) cookie['lastvisit'] is a string. > cookie['lastvisit']['expires'] = cExpires Here you're using the string 'expires' as an index into the string returned by str(time.time()). You can only index into strings using integers. What do you expect the following statement to do? '1260910829.18'['expires'] = > cookie['lastvisit']['path'] = cPath > cookie['lastvisit']['comment'] = cComment > cookie['lastvisit']['domain'] = cDomain > cookie['lastvisit']['max-age'] = cMaxAge > cookie['lastvisit']['version'] = cVersion > cookieFlag = 'new' > else: > cookieFlag = 'old' > print cookie['lastvisit']['expires'].value > > Got this error: > > /var/www/html/angrynates.com/cart/cart.py > > 191 > 192 ''' > 193 > 194 cart() > 195 > cart = > /var/www/html/angrynates.com/cart/cart.py > in cart() > 31 else: > 32 cookieFlag = 'old' > 33 print cookie['lastvisit']['expires'].value > 34 # Don't know what to do with this. It's for when client won't > accept cookies > 35 # sessionDir = os.environ['DOCUMENT_ROOT'] + '/tmp/.session' > cookie = 'lastvisit=1260898013.65; lastvisit=1260898315.01', ].value > undefined > > TypeError: string indices must be integers > args = ('string indices must be integers',) You took the string returned by str(time.time()) and tried to use 'expires' as an index into that time string. You can't use a string to index into a string. You can only use integers. That's what is mean't by the error message: TypeError: string indices must be integers -- Grant Edwards grante Yow! ... I have read the at INSTRUCTIONS ... visi.com From tjreedy at udel.edu Tue Dec 15 16:03:58 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 15 Dec 2009 16:03:58 -0500 Subject: treaps in python In-Reply-To: <4B271567.4070604@gmail.com> References: <4B271567.4070604@gmail.com> Message-ID: On 12/14/2009 11:49 PM, Dan Stromberg wrote: > Also, what's the best way to package something like this for consumption > by python-folk? There seem to be so many ways of packaging things > anymore. Are dist utils, a .deb and a .rpm the way to go? Right now, > it's just using make to stuff things in /usr/local. > > There are two versions: One that is pure python, and one that is part > python and part cython. They're automatically generated from a common m4 > template. > > There are rather plentiful unit tests included in the tar archive. If the module is pure Python, then for Windows I would be happiest with a no-install .zip that I can stick into site-packages. From tjreedy at udel.edu Tue Dec 15 16:22:49 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 15 Dec 2009 16:22:49 -0500 Subject: Where is PyMethod_GET_CLASS in Python 3? In-Reply-To: <1799a93b-5eb8-4818-ab94-7aa4108fcea1@j24g2000yqa.googlegroups.com> References: <1799a93b-5eb8-4818-ab94-7aa4108fcea1@j24g2000yqa.googlegroups.com> Message-ID: On 12/15/2009 11:08 AM, Infinity77 wrote: > Hi All, > > When building C extensions In Python 2.X, there was a magical > PyMethod_GET_CLASS implemented like this: > > #define PyMethod_GET_CLASS(meth) \ > (((PyMethodObject *)meth) -> im_class) > > It looks like Python 3 has wiped out the "im_class" attribute. For bound methods, renamed to __class__ to be consistent with other objects. Unbound methods were eliminated as extra cruft. > Which > is the alternative was to handle this case in Python 3? How do I find > to which class this particular method belongs to? A method (unbound) is simply a function accessed as an attribute of a class. A function can be a method of 0 to n classes, and 'belongs' to none of them. Terry Jan Reedy From manouchk at gmail.com Tue Dec 15 16:24:07 2009 From: manouchk at gmail.com (Emmanuel) Date: Tue, 15 Dec 2009 13:24:07 -0800 (PST) Subject: csv reader Message-ID: <66830a07-57ff-4fe7-9a9a-c2bc17546410@f20g2000vbl.googlegroups.com> I have a problem with csv.reader from the library csv. I'm not able to import accentuated caracters. For example, I'm trying to import a simple file containing a single word "equa??o" using the following code: import csv arquivoCSV='test' a=csv.reader(open(arquivoCSV),delimiter=',') tab=[] for row in a: tab.append(row) print tab As a result, I get: [['equa\xe7\xe3o']] How can I solve this problem? From robert.kern at gmail.com Tue Dec 15 16:30:01 2009 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 15 Dec 2009 15:30:01 -0600 Subject: treaps in python In-Reply-To: <4B271567.4070604@gmail.com> References: <4B271567.4070604@gmail.com> Message-ID: On 2009-12-14 22:49 PM, Dan Stromberg wrote: > It's currently GPLv3-licensed, but I'd like to dual license it in such a > way that it could eventually be included in the standard library. How > would I go about this? I would recommend simply using the Apache v2 license. The PSF will only accept code for the standard library under this license or the Academic Free License. There is no need or benefit to dual-licensing it with the Apache license and the GPLv3 as the GPLv3 is a strict superset of requirements. People writing GPLv3 programs can incorporate your module without problems. You *may* want to consider dual-licensing Apache v2/GPLv2 or another GPLv2-compatible license. There are some people sticking with GPLv2 and the patent peace provisions in the Apache v2 (compatible with those in GPLv3) are incompatible with the GPLv2. Both of these dual-licensing scenarios are quite different from what people normally want to do when dual-licensing, which is to use a strong copyleft license like the GPL normally and sell individual commercial licenses on an ad hoc basis. This would not serve your purpose. I still recommend just licensing your code under the Apache v2 license and forgetting about dual-licensing until you get people asking for other licenses. -- 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 neilc at norwich.edu Tue Dec 15 16:32:46 2009 From: neilc at norwich.edu (Neil Cerutti) Date: 15 Dec 2009 21:32:46 GMT Subject: AttributeError: logging module bug ? References: <4dc0cfea0912151005g7cf389ddx2e3d9d5a62338344@mail.gmail.com> <4B27D721.2010707@mrabarnett.plus.com> <4dc0cfea0912151112n235fa28vd509a36ddfc4ade9@mail.gmail.com> <7oqa3pF3mh99tU1@mid.individual.net> Message-ID: <7oqdjuF3ql9elU1@mid.individual.net> On 2009-12-15, Neil Cerutti wrote: > On 2009-12-15, Peter wrote: >> on python 2.6 the following code raises an AttributeError: >> >> #!/usr/bin/env python >> import os.path as p >> import logging, logging.config >> >> >> class Logger(object): >> def load_config(self): >> logging.config.fileConfig(p.join(p.dirname(__file__),'logging.cfg')) > > __file__ is undefined in your example code, so I'm not getting > the same exception as you. Never mind. I was running it in interactive mode, and of course it doesn't work. -- Neil Cerutti From clp2 at rebertia.com Tue Dec 15 16:33:31 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 15 Dec 2009 13:33:31 -0800 Subject: csv reader In-Reply-To: <66830a07-57ff-4fe7-9a9a-c2bc17546410@f20g2000vbl.googlegroups.com> References: <66830a07-57ff-4fe7-9a9a-c2bc17546410@f20g2000vbl.googlegroups.com> Message-ID: <50697b2c0912151333x32acfce9u17a4358979d74499@mail.gmail.com> On Tue, Dec 15, 2009 at 1:24 PM, Emmanuel wrote: > I have a problem with csv.reader from the library csv. I'm not able to > import accentuated caracters. For example, I'm trying to import a > simple file containing a single word "equa??o" using the following > code: > > import csv > arquivoCSV='test' > a=csv.reader(open(arquivoCSV),delimiter=',') > tab=[] > for row in a: > ? ?tab.append(row) > print tab > > As a result, I get: > > [['equa\xe7\xe3o']] > > How can I solve this problem? >From http://docs.python.org/library/csv.html : """ Note: This version of the csv module doesn?t support Unicode input. Also, there are currently some issues regarding ASCII NUL characters. Accordingly, all input should be UTF-8 or printable ASCII to be safe; see the examples in section Examples. These restrictions will be removed in the future. """ Thus, you'll have to decode the results into Unicode manually; this will require knowing what encoding your file is using. Files in some encodings may not parse correctly due to the aforementioned NUL problem. Cheers, Chris -- http://blog.rebertia.com From malaclypse2 at gmail.com Tue Dec 15 16:37:52 2009 From: malaclypse2 at gmail.com (Jerry Hill) Date: Tue, 15 Dec 2009 16:37:52 -0500 Subject: csv reader In-Reply-To: <66830a07-57ff-4fe7-9a9a-c2bc17546410@f20g2000vbl.googlegroups.com> References: <66830a07-57ff-4fe7-9a9a-c2bc17546410@f20g2000vbl.googlegroups.com> Message-ID: <16651e80912151337t6542a68cl92db71acb7994181@mail.gmail.com> On Tue, Dec 15, 2009 at 4:24 PM, Emmanuel wrote: > I have a problem with csv.reader from the library csv. I'm not able to > import accentuated caracters. For example, I'm trying to import a > simple file containing a single word "equa??o" using the following > code: > > import csv > arquivoCSV='test' > a=csv.reader(open(arquivoCSV),delimiter=',') > tab=[] > for row in a: > ? ?tab.append(row) > print tab > > As a result, I get: > > [['equa\xe7\xe3o']] > > How can I solve this problem? I don't think it is a problem. \xe7 is the character ? encoded in Windows-1252, which is probably the encoding of your csv file. If you want to convert that to a unicode string, do something like the following. s = 'equa\xe7\xe3o' uni_s = s.decode('Windows-1252') print uni_s -- Jerry From thewellsoliver at gmail.com Tue Dec 15 17:03:50 2009 From: thewellsoliver at gmail.com (Wells) Date: Tue, 15 Dec 2009 14:03:50 -0800 (PST) Subject: Odd json encoding erro Message-ID: <891fb16f-7d3b-4b6a-8f49-08cea2c35439@h2g2000vbd.googlegroups.com> I get this exception when decoding a certain JSON string: 'ascii' codec can't encode character u'\u2019' in position 8: ordinal not in range(128) The JSON data in question: http://mlb.com/lookup/json/named.player_info.bam?sport_code=%27mlb%27&player_id=%27489002%27 It's in the 'high_school' key. Is there some string function I can run on the information before I decode it to avoid this? Thanks! From manouchk at gmail.com Tue Dec 15 17:12:01 2009 From: manouchk at gmail.com (Emmanuel) Date: Tue, 15 Dec 2009 14:12:01 -0800 (PST) Subject: csv reader References: <66830a07-57ff-4fe7-9a9a-c2bc17546410@f20g2000vbl.googlegroups.com> Message-ID: Then my problem is diferent! In fact I'm reading a csv file saved from openoffice oocalc using UTF-8 encoding. I get a list of list (let's cal it tab) with the csv data. If I do: print tab[2][4] In ipython, I get: equa??o de Toricelli. Tarefa exerc?cios PVR 1 e 2 ; PVP 1 If I only do: tab[2][4] In ipython, I get: 'equa\xc3\xa7\xc3\xa3o de Toricelli. Tarefa exerc\xc3\xadcios PVR 1 e 2 ; PVP 1' Does that mean that my problem is not the one I'm thinking? My real problem is when I use that that kind of UTF-8 encoded (?) with selenium here. Here is an small code example of a not-working case giving the same error that on my bigger program: #!/usr/bin/env python # -*- coding: utf-8 -*- from selenium import selenium import sys,os,csv,re class test: '''classe para interagir com o sistema acad?mico''' def __init__(self): self.webpage='' self.arquivo='' self.script=[] self.sel = selenium('localhost', 4444, '*firefox', 'http:// www.google.com.br') self.sel.start() self.sel.open('/') self.sel.wait_for_page_to_load(30000) self.sel.type("q", "equa??o") #self.sel.type("q", u"equacao") self.sel.click("btnG") self.sel.wait_for_page_to_load("30000") def main(): teste=test() if __name__ == "__main__": main() If I just switch the folowing line: self.sel.type("q", "equa??o") by: self.sel.type("q", u"equa??o") It works fine! The problem is that the csv.reader does give a "equa??o" and not a u"equa??o" Here is the error given with bad code (with "equa??o"): ERROR: An unexpected error occurred while tokenizing input The following traceback may be corrupted or invalid The error message is: ('EOF in multi-line statement', (1202, 0)) --------------------------------------------------------------------------- UnicodeDecodeError Traceback (most recent call last) /home/manu/Labo/Cefetes_Colatina/Scripts/ 20091215_test_acentuated_caracters.py in () 27 28 if __name__ == "__main__": ---> 29 main() 30 31 /home/manu/Labo/Cefetes_Colatina/Scripts/ 20091215_test_acentuated_caracters.py in main() 23 24 def main(): ---> 25 teste=test() 26 27 /home/manu/Labo/Cefetes_Colatina/Scripts/ 20091215_test_acentuated_caracters.py in __init__(self) 16 self.sel.open('/') 17 self.sel.wait_for_page_to_load(30000) ---> 18 self.sel.type("q", "equa??o") 19 #self.sel.type("q", u"equacao") 20 self.sel.click("btnG") /home/manu/Labo/Cefetes_Colatina/Scripts/selenium.pyc in type(self, locator, value) 588 'value' is the value to type 589 """ --> 590 self.do_command("type", [locator,value,]) 591 592 /home/manu/Labo/Cefetes_Colatina/Scripts/selenium.pyc in do_command (self, verb, args) 201 body = u'cmd=' + urllib.quote_plus(unicode(verb).encode ('utf-8')) 202 for i in range(len(args)): --> 203 body += '&' + unicode(i+1) + '=' + urllib.quote_plus(unicode(args[i]).encode('utf-8')) 204 if (None != self.sessionId): 205 body += "&sessionId=" + unicode(self.sessionId) UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 4: ordinal not in range(128) WARNING: Failure executing file: <20091215_test_acentuated_caracters.py> Python 2.6.4 (r264:75706, Oct 27 2009, 06:16:59) From tismer at stackless.com Tue Dec 15 17:17:10 2009 From: tismer at stackless.com (Christian Tismer) Date: Tue, 15 Dec 2009 23:17:10 +0100 Subject: insert unique data in a list In-Reply-To: References: <4b251840$0$30959$4fafbaef@reader3.news.tin.it> <4b252b1b$0$644$4fafbaef@reader4.news.tin.it> Message-ID: <4B280AE6.1060701@stackless.com> On 12/14/09 2:24 AM, knifenomad wrote: > On 12?14?, ??10?19?, knifenomad wrote: > >> On 12?14?, ??2?57?, mattia wrote: >> >> >> >> >> >> >>> Il Sun, 13 Dec 2009 16:37:20 +0000, mattia ha scritto: >>> >> >>>> How can I insert non-duplicate data in a list? I mean, is there a >>>> particular option in the creation of a list that permit me not to use >>>> something like: >>>> def append_unique(l, val): >>>> if val not in l: >>>> l.append(val) >>>> >> >>>> Thanks, >>>> Mattia >>>> >> >>> Ok, so you all suggest to use a set. Now the second question, more >>> interesting. Why can't I insert a list into a set? I mean, I have a >>> function that returns a list. I call this function several times and >>> maybe the list returned is the same as another one already returned. I >>> usually put all this lists into another list. How can I assure that my >>> list contains only unique lists? Using set does'n work (i.e. the python >>> interpreter tells me: TypeError: unhashable type: 'list')... >>> >> this makes the set type hashable. >> >> class Set(set): >> __hash__ = lambda self: id(self) >> >> s = Set() >> s.add(1) >> s.add(2) >> s.add(1) >> >> print s >> set([1, 2]) >> >> d = {} >> d[s] = 'voila' >> >> print d >> {Set([1,2]):'voila'} >> >> print d[s] >> 'voila'- ?? ??? ??? - >> >> - ?? ??? ?? - >> > > although it's not what you've asked about. it's intereting to make set > hashable using __hash__. Thoughtless messing with __hash__ is seldom useful. >>> s1 = Set([1]) >>> s2 = Set([1]) >>> s1 == s2 True >>> d = {} >>> d[s1] = 3 >>> d[s2] = 5 >>> d {Set([1]): 3, Set([1]): 5} >>> Equality is kept for comparison, but what is it worth to hash them by id? On the original problem: You could turn you lists into tuples. This would be clean and correct. ciao - chris -- Christian Tismer :^) tismerysoft GmbH : Have a break! Take a ride on Python's Johannes-Niemeyer-Weg 9A : *Starship* http://starship.python.net/ 14109 Berlin : PGP key -> http://wwwkeys.pgp.net/ work +49 30 802 86 56 mobile +49 173 24 18 776 fax +49 30 80 90 57 05 PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04 whom do you want to sponsor today? http://www.stackless.com/ From owenzhang.chicago at gmail.com Tue Dec 15 17:17:58 2009 From: owenzhang.chicago at gmail.com (Jennifer) Date: Tue, 15 Dec 2009 14:17:58 -0800 (PST) Subject: ftplib retrlines timeout Message-ID: I am writing a program that has a requirement for a timeout of retrlines after the connection established. I just wonder if timeout of ftplib.FTP('xxxx.xxx.com',username,password,timeout) will work for retrlines method after the connection established. Or socket.setdefaulttimeout will work in this case. Please let me know. What exception will be throwed if ftp.retrlines timed out. Many Thanks! - Jennifer From clp2 at rebertia.com Tue Dec 15 17:23:36 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 15 Dec 2009 14:23:36 -0800 Subject: Odd json encoding erro In-Reply-To: <891fb16f-7d3b-4b6a-8f49-08cea2c35439@h2g2000vbd.googlegroups.com> References: <891fb16f-7d3b-4b6a-8f49-08cea2c35439@h2g2000vbd.googlegroups.com> Message-ID: <50697b2c0912151423w229004eaoef05976f07753b5@mail.gmail.com> On Tue, Dec 15, 2009 at 2:03 PM, Wells wrote: > I get this exception when decoding a certain JSON string: > > 'ascii' codec can't encode character u'\u2019' in position 8: ordinal > not in range(128) > > The JSON data in question: > > http://mlb.com/lookup/json/named.player_info.bam?sport_code=%27mlb%27&player_id=%27489002%27 > > It's in the 'high_school' key. Is there some string function I can run > on the information before I decode it to avoid this? >From what I can guess (you didn't include any code), you're printing the result of loading the JSON (which probably loaded correctly) to the terminal without specifying the exact encoding to use. In such cases, Python defaults to ASCII. However, your data obviously includes non-ASCII characters, thus resulting in the error you're encountering. Instead of `print the_high_school`, try `print the_high_school.encode('utf8')`. Note that the `json` library returns Unicode strings of the type `unicode` and not byte strings of type `str` (unless you're using Python 3.0, in which case `unicode` got renamed to `str` and `str` got renamed to `bytes`). When outputting Unicode, it needs to be encoded to bytes. The built-in type() function* can help determine when you have Unicode data. Cheers, Chris -- http://blog.rebertia.com *Yes, it's not /really truly/ a function, but the distinction is not relevant here. From unlearned at gmail.com Tue Dec 15 17:24:24 2009 From: unlearned at gmail.com (Intchanter / Daniel Fackrell) Date: Tue, 15 Dec 2009 14:24:24 -0800 (PST) Subject: Odd json encoding erro References: <891fb16f-7d3b-4b6a-8f49-08cea2c35439@h2g2000vbd.googlegroups.com> Message-ID: On Dec 15, 3:03?pm, Wells wrote: > I get this exception when decoding a certain JSON string: > > 'ascii' codec can't encode character u'\u2019' in position 8: ordinal > not in range(128) > > The JSON data in question: > > http://mlb.com/lookup/json/named.player_info.bam?sport_code=%27mlb%27... > > It's in the 'high_school' key. Is there some string function I can run > on the information before I decode it to avoid this? In my test using this same data, I did not get such an error. Here's my code: data = '{"player_info": {"queryResults": { "row": { "active_sw": "Y", "bats": "R", "birth_city": "Baltimore", "birth_country": "USA", "birth_date": "1987-08-31T00:00:00", "birth_state": "MD", "college": "", "death_city": "", "death_country": "", "death_date": "", "death_state": "", "end_date": "", "file_code": "sf", "gender": "M", "height_feet": "6", "height_inches": "1", "high_school": "St. Paul \u2019s School For Boys (MN) HS", "jersey_number": "", "name_display_first_last": "Steve Johnson", "name_display_first_last_html": "Steve Johnson", "name_display_last_first": "Johnson, Steve", "name_display_last_first_html": "Johnson, Steve", "name_display_roster": "Johnson, S", "name_display_roster_html": "Johnson, S", "name_first": "Steven", "name_full": "Johnson, Steve", "name_last": "Johnson", "name_matrilineal": "", "name_middle": "David", "name_nick": "", "name_prefix": "", "name_title": "", "name_use": "Steve", "player_id": "489002", "primary_position": "1", "primary_position_txt": "P", "primary_sport_code": "", "pro_debut_date": "", "start_date": "2009-12-10T00:00:00", "status": "Active", "status_code": "A", "status_date": "2009-12-10T00:00:00", "team_abbrev": "SF", "team_code": "sfn", "team_id": "137", "team_name": "San Francisco Giants", "throws": "R", "weight": "200" }, "totalSize": "1" }}}' import json print json.loads(data) (I'm running 2.6.4 on Mac OS X) Intchanter Daniel Fackrell From aioe.org at technicalbloke.com Tue Dec 15 17:26:05 2009 From: aioe.org at technicalbloke.com (r0g) Date: Tue, 15 Dec 2009 22:26:05 +0000 Subject: Seek support for new slice syntax PEP. References: <8e5054b1-8424-4633-a52e-1d9dcd1637b6@c34g2000yqn.googlegroups.com> Message-ID: Terry Reedy wrote: > On 12/14/2009 1:10 PM, geremy condra wrote: >> http://www.python.org/dev/peps/pep-3003/ > > The moratorium does not stop proposals for things to be added after the > moratorium ends. But it does show that Guido and the devs are reluctant > to make *any* change to the core syntax of 3.x without really good > reason. Absent that, I would not mind if the syntax remains frozen for > the rest of 3.x. A minor abbreviation that makes the language look more > like Perl will not cut it. > > Terry Jan Reedy > I agree, string slicing syntax is already a little oblique, it certainly doesn't need complicating. Anyway... Simple is better than complex. Readability counts. If the implementation is hard to explain, it's a bad idea. Roger. From steve at REMOVE-THIS-cybersource.com.au Tue Dec 15 17:29:06 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 15 Dec 2009 22:29:06 GMT Subject: (OT) Where Are Cookies Stored? References: <4dc0cfea0912150730w1d0c131agb258029b3e9a21ca@mail.gmail.com> Message-ID: <00b19258$0$15654$c3e8da3@news.astraweb.com> On Tue, 15 Dec 2009 13:03:07 -0300, Gabriel Genellina wrote: > En Tue, 15 Dec 2009 12:30:23 -0300, Victor Subervi > escribi?: > >> I've googled, found where cookies are supposed to be, the folders and >> files don't exist. [...] > How the browser stores its cookies should be irrelevant. Whenever a > server response contains a Set-Cookie header, the browser saves the > cookie. When the client issues a request that matches a saved cookie, it > adds a Cookie header with the cookie. From the server POV, you don't > care how the cookie is stored. But you do care if you're writing a cookie manager, or if you need to grab an existing cookie from disk and do something with it (as wget allows you to do, for example). Victor, have you got Firefox set to delete all cookies when you log out? -- Steven From aioe.org at technicalbloke.com Tue Dec 15 17:31:24 2009 From: aioe.org at technicalbloke.com (r0g) Date: Tue, 15 Dec 2009 22:31:24 +0000 Subject: OS independent way to check if a python app is running? References: <1260818045.9273.1350060453@webmail.messagingengine.com> <8c7f10c60912141136g658caf6vad0ee55d03bcbeb3@mail.gmail.com> Message-ID: python at bdurham.com wrote: > LOL! Yes, I should of worded my original post better (meant to say "... > if a python app is already running". > > Enjoyed your post anyway - I'm still laughing :) > > Cheers, > Malcolm Quick and dirty way would be to keep a particular high numbered socket open. Roger From aioe.org at technicalbloke.com Tue Dec 15 17:57:06 2009 From: aioe.org at technicalbloke.com (r0g) Date: Tue, 15 Dec 2009 22:57:06 +0000 Subject: (OT) Where Are Cookies Stored? References: <4dc0cfea0912150730w1d0c131agb258029b3e9a21ca@mail.gmail.com> Message-ID: Gabriel Genellina wrote: > En Tue, 15 Dec 2009 12:30:23 -0300, Victor Subervi > escribi?: > >> I've googled, found where cookies are supposed to be, the folders and >> files >> don't exist. I've opened my latest and greatest FF and seen cookies in >> there, but when I search for the name of the cookie in the C: dir, >> it's not >> there...anywhere. I've made sure no folders/files are hidden and I still >> can't find them. In as administrator. What up? XP OS I need to get in >> so I >> can learn how to program with cookies. > > How the browser stores its cookies should be irrelevant. Whenever a > server response contains a Set-Cookie header, the browser saves the > cookie. When the client issues a request that matches a saved cookie, it > adds a Cookie header with the cookie. From the server POV, you don't > care how the cookie is stored. > Cookies in FF for Windows are stored in an sqlite database in here... ~\Application Data\Mozilla\Firefox\Profiles\%XYZ%\firefox_profile\ Roger. From thewellsoliver at gmail.com Tue Dec 15 18:04:07 2009 From: thewellsoliver at gmail.com (Wells) Date: Tue, 15 Dec 2009 15:04:07 -0800 (PST) Subject: Odd json encoding erro References: <891fb16f-7d3b-4b6a-8f49-08cea2c35439@h2g2000vbd.googlegroups.com> Message-ID: <1558e730-7653-4c74-98d8-c60f0a1022c7@q16g2000vbc.googlegroups.com> Sorry- more detail- the actual problem is an exception thrown when running str() on the value, like so: >>> a = u'St. Paul\u2019s School For Boys (MN) HS' >>> print str(a) Traceback (most recent call last): File "", line 1, in UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in position 8: ordinal not in range(128) Is there some way to run str() against a unicode object? From vmail at mycircuit.org Tue Dec 15 18:34:03 2009 From: vmail at mycircuit.org (Peter) Date: Wed, 16 Dec 2009 00:34:03 +0100 Subject: AttributeError: logging module bug ? In-Reply-To: References: <4dc0cfea0912151005g7cf389ddx2e3d9d5a62338344@mail.gmail.com> <4B27D721.2010707@mrabarnett.plus.com> <4dc0cfea0912151112n235fa28vd509a36ddfc4ade9@mail.gmail.com> Message-ID: <4B281CEB.7090807@mycircuit.org> >> What's the problem ? >> > Please provide the config file "logging.cfg" to ease debugging. > > Peter > Here it is, thanks for having a look Peter -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: logging.cfg URL: From clp2 at rebertia.com Tue Dec 15 18:38:19 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 15 Dec 2009 15:38:19 -0800 Subject: Odd json encoding erro In-Reply-To: <1558e730-7653-4c74-98d8-c60f0a1022c7@q16g2000vbc.googlegroups.com> References: <891fb16f-7d3b-4b6a-8f49-08cea2c35439@h2g2000vbd.googlegroups.com> <1558e730-7653-4c74-98d8-c60f0a1022c7@q16g2000vbc.googlegroups.com> Message-ID: <50697b2c0912151538g127f2944l76ca82eca91e8727@mail.gmail.com> On Tue, Dec 15, 2009 at 3:04 PM, Wells wrote: > Sorry- more detail- the actual problem is an exception thrown when > running str() on the value, like so: > >>>> a = u'St. Paul\u2019s School For Boys (MN) HS' >>>> print str(a) > Traceback (most recent call last): > ?File "", line 1, in > UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in > position 8: ordinal not in range(128) > > Is there some way to run str() against a unicode object? To repeat what I said earlier, you use the .encode() method instead: print a.encode('utf8') Might I recommend reading: http://www.joelonsoftware.com/articles/Unicode.html Regards, Chris -- http://blog.rebertia.com From aioe.org at technicalbloke.com Tue Dec 15 18:38:19 2009 From: aioe.org at technicalbloke.com (r0g) Date: Tue, 15 Dec 2009 23:38:19 +0000 Subject: (OT) Where Are Cookies Stored? References: <4dc0cfea0912150730w1d0c131agb258029b3e9a21ca@mail.gmail.com> Message-ID: r0g wrote: > Gabriel Genellina wrote: >> En Tue, 15 Dec 2009 12:30:23 -0300, Victor Subervi >> escribi?: >> >>> I've googled, found where cookies are supposed to be, the folders and >>> files >>> don't exist. I've opened my latest and greatest FF and seen cookies in >>> there, but when I search for the name of the cookie in the C: dir, >>> it's not >>> there...anywhere. I've made sure no folders/files are hidden and I still >>> can't find them. In as administrator. What up? XP OS I need to get in >>> so I >>> can learn how to program with cookies. >> How the browser stores its cookies should be irrelevant. Whenever a >> server response contains a Set-Cookie header, the browser saves the >> cookie. When the client issues a request that matches a saved cookie, it >> adds a Cookie header with the cookie. From the server POV, you don't >> care how the cookie is stored. >> > > > Cookies in FF for Windows are stored in an sqlite database in here... > > ~\Application Data\Mozilla\Firefox\Profiles\%XYZ%\firefox_profile\ > > Roger. Whoops that should be... ~\Application Data\Mozilla\Firefox\Profiles\%XYZ%\cookies.sqlite Where XYZ is a big ugly random string with ".default" at the end. I have also written a pure python graphical sqlite editor/viewer that you might find useful if you want to see inside these file or edit them. Be careful with it though, it writes any changes to the DB immediately and without prompting! It's called sqex and you can d/l it here: http://www.technicalbloke.com/sqex0.1.zip It needs a wx library too BTW. Regards, Roger. From manouchk at gmail.com Tue Dec 15 19:01:25 2009 From: manouchk at gmail.com (Emmanuel) Date: Tue, 15 Dec 2009 16:01:25 -0800 (PST) Subject: csv reader References: <66830a07-57ff-4fe7-9a9a-c2bc17546410@f20g2000vbl.googlegroups.com> Message-ID: <0e4eb3a9-edf2-4eab-8d36-58ecf142d456@p30g2000vbt.googlegroups.com> As csv.reader does not suport utf-8 encoded files, I'm using: fp = codecs.open(arquivoCSV, "r", "utf-8") self.tab=[] for l in fp: l=l.replace('\"','').strip() self.tab.append(l.split(',')) It works much better except that when I do self.sel.type("q", ustring) where ustring is a unicode string obtained from the file using the code showed above. Remaining problem is that I obtain insted of a regular space... From wangpurui at yahoo.com.cn Tue Dec 15 20:06:33 2009 From: wangpurui at yahoo.com.cn (pograph) Date: Tue, 15 Dec 2009 17:06:33 -0800 (PST) Subject: race/deadlock when creating a multiprocessing.manager instance while importing a module ? References: <52ce8fe6-7b3a-43dd-94bb-5a57ee7ad9b4@c34g2000yqn.googlegroups.com> <4B26EB0C.9060600@ieee.org> Message-ID: On Dec 15, 2:57 am, Sebastien Binet wrote: > Dave, > > [..snip..] > On Tuesday 15 December 2009 02:49:00 Dave Angel wrote: > > > Since I don't see any other responses, I'll give my guess, even though > > I'm not very experienced with the multiprocessing module. > > > It's my understanding that threads may not be created or destroyed > > during an import. So you need to find a way to defer the creation till > > the imports are done. > > yes, I figured this much and I already wrapped my module with a ModuleFacade > object which has lazy properties attributes [1]. > this solves the problem of import my module, but if the module importing my > module is itself being imported, I am back to square one. > > and my module is being used by many people. > > I guess I'd need at least a way to detect that somebody is trying to use the > lazy properties of my module facade while an import is "still active". > is there such a mechanism ? > > cheers, > sebastien. > > [1]https://svnweb.cern.ch/trac/atlasoff/browser/Tools/PyUtils/trunk/pyth... > -- > ######################################### > # Dr. Sebastien Binet > # Laboratoire de l'Accelerateur Lineaire > # Universite Paris-Sud XI > # Batiment 200 > # 91898 Orsay > ######################################### The document of multiprocessing says: Functionality within this package requires that the __main__ method be importable by the children. This is covered in Programming guidelines however it is worth pointing out here. This means that some examples, such as the multiprocessing.Pool examples will not work in the interactive interpreter. From wuwei23 at gmail.com Tue Dec 15 22:09:08 2009 From: wuwei23 at gmail.com (alex23) Date: Tue, 15 Dec 2009 19:09:08 -0800 (PST) Subject: pyZui - anyone know about this? References: <200912151028.41350.donn.ingle@gmail.com> <23739e0a0912150112p3c22be44jcae290a3060f3196@mail.gmail.com> Message-ID: Donn wrote: > I find the notion of minute "hot" areas to be a little obscure -- Quick! Zoom > into the last full-stop, it's a whole word in there! This aspect reminds me of the Red Dwarf episode "Back to Reality", in which Rimmer is criticised for not finding information contained in a microdot hidden in the dot on the 'i' of his name on a swimming certificate. ZUIs are useful for particular types of data - images & mapping especially - but I'd hate to have to navigate my desktop using its approach. From catphive at catphive.net Tue Dec 15 22:39:29 2009 From: catphive at catphive.net (Brendan Miller) Date: Tue, 15 Dec 2009 19:39:29 -0800 Subject: iterators and views of lists Message-ID: I was trying to reimplement some of the c++ library of generic algorithms in c++ in python, but I was finding that this is problematic to do this in a generic way because there isn't any equivalent of c++'s forward iterators, random access iterators, etc. i.e. all python iterators are just input iterators that can't mutate the sequence they iterate over nor move backwards or by an arbitrary offset. I'm wondering if anyone has done work towards creating more powerful iterators for python, or creating some more pythonic equivalent. In particular, I was thinking that slices are almost equivalent to a range of random access iterators, except that they create an unnecessary copy. If there was a version of slice that defined a mutable view over the original list, you'd have something equivalent to t a pair of random access iterators. For instance, if you wanted to reverse a segment of a list in place you would be able to do: list = [1,2,3,4] #pretend this is some variant of slice that produces views instead #obviously this couldn't use the same syntax, and might be a method instead. view = list[1:] view.reverse() print list [1,4,3,2] This doesn't really handle forward and bidirectional iterators... which I guess would be good for algorithms that operator over disk base datastructures... Anyone else had similar thoughts? Brendan From davea at ieee.org Tue Dec 15 22:50:56 2009 From: davea at ieee.org (Dave Angel) Date: Tue, 15 Dec 2009 22:50:56 -0500 Subject: (OT) Where Are Cookies Stored? In-Reply-To: <4dc0cfea0912150730w1d0c131agb258029b3e9a21ca@mail.gmail.com> References: <4dc0cfea0912150730w1d0c131agb258029b3e9a21ca@mail.gmail.com> Message-ID: <4B285920.6090407@ieee.org> Victor Subervi wrote: > Hi; > I've googled, found where cookies are supposed to be, the folders and files > don't exist. I've opened my latest and greatest FF and seen cookies in > there, but when I search for the name of the cookie in the C: dir, it's not > there...anywhere. I've made sure no folders/files are hidden and I still > can't find them. In as administrator. What up? XP OS I need to get in so I > can learn how to program with cookies. > Victor > > I can't imagine why you couldn't find them. For my version of Firefox, I see a file in: (appdata)\\Mozilla\Firefox\Profiles\1fjazjlkjflkjsdlfkj.default\cookies.sqlite In other words, you'd need some database code to get at them. Note that IE will store them somewhere else, and maybe the next point release of Firefox will as well. So you shouldn't hardwire any such knowledge. And you shouldn't make any modifications to such a file. DaveA From jkpeck at gmail.com Tue Dec 15 23:12:51 2009 From: jkpeck at gmail.com (JKPeck) Date: Tue, 15 Dec 2009 20:12:51 -0800 (PST) Subject: Problems with gettext and msgfmt Message-ID: <4caf86f5-c760-4c08-a9f8-ea70b49ca433@k9g2000vbl.googlegroups.com> I'm using Python 2.6 on Windows and having trouble with the charset in gettext. It seems to be so broken that I must be missing something. When I run msgfmt.py, as far as I can see it writes no charset information into the mo file. The actual po files are in utf-8 in this case and have a charset declaration. Then when ,_parse in gettext loads the messages, it does no conversion to Unicode, because it has no charset information. So the message dictionary is actually in utf-8 despite the comment in the code # Note: we unconditionally convert both msgids and msgstrs to # Unicode using the character encoding specified in the charset # parameter of the Content-Type header. Then ugettext tries to just return the translated message, which is not in Unicode, or to convert to Unicode, which fails because the unicode call is not specifying any encoding. The _parse code seems to expect to produce a Unicode translation dictionary, and gettext expects to encode Unicode into the current code page, but the message dictionary never gets mapped to Unicode in the first place. What I want is simply to use utf-8 po files and get translations in Unicode. TIA for any suggestions. -Jon Peck From gagsl-py2 at yahoo.com.ar Tue Dec 15 23:27:09 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 16 Dec 2009 01:27:09 -0300 Subject: csv reader References: <66830a07-57ff-4fe7-9a9a-c2bc17546410@f20g2000vbl.googlegroups.com> Message-ID: En Tue, 15 Dec 2009 19:12:01 -0300, Emmanuel escribi?: > Then my problem is diferent! > > In fact I'm reading a csv file saved from openoffice oocalc using > UTF-8 encoding. I get a list of list (let's cal it tab) with the csv > data. > If I do: > > print tab[2][4] > In ipython, I get: > equa??o de Toricelli. Tarefa exerc?cios PVR 1 e 2 ; PVP 1 > > If I only do: > tab[2][4] > > In ipython, I get: > 'equa\xc3\xa7\xc3\xa3o de Toricelli. Tarefa exerc\xc3\xadcios PVR 1 e > 2 ; PVP 1' > > Does that mean that my problem is not the one I'm thinking? Yes. You have a real problem, but not this one. When you say `print something`, you get a nice view of `something`, basically the result of doing `str(something)`. When you say `something` alone in the interpreter, you get a more formal representation, the result of calling `repr(something)`: py> x = "ecua??o" py> print x ecua??o py> x 'ecua\x87\xc6o' py> print repr(x) 'ecua\x87\xc6o' Those '' around the text and the \xNN notation allow for an unambiguous representation. Two strings may "look like" the same but be different, and repr shows that. ('ecua\x87\xc6o' is encoded in windows-1252; you should see 'equa\xc3\xa7\xc3\xa3o' in utf-8) > My real problem is when I use that that kind of UTF-8 encoded (?) with > selenium here. > If I just switch the folowing line: > self.sel.type("q", "equa??o") > > by: > self.sel.type("q", u"equa??o") > > > It works fine! Yes: you should work with unicode most of the time. The "recipe" for having as little unicode problems as possible says: - convert the input data (read from external sources, like a file) from bytes to unicode, using the (known) encoding of those bytes - handle unicode internally everywhere in your program - and convert from unicode to bytes as late as possible, when writing output (to screen, other files, etc) using the encoding expected by those external files. See the Unicode How To: http://docs.python.org/howto/unicode.html > The problem is that the csv.reader does give a "equa??o" and not a > u"equa??o" The csv module cannot handle unicode text directly, but see the last example in the csv documentation for a simple workaround: http://docs.python.org/library/csv.html -- Gabriel Genellina From d at vidr.cc Wed Dec 16 00:03:19 2009 From: d at vidr.cc (David Roberts) Date: Tue, 15 Dec 2009 21:03:19 -0800 (PST) Subject: pyZui - anyone know about this? References: <200912151028.41350.donn.ingle@gmail.com> <23739e0a0912150112p3c22be44jcae290a3060f3196@mail.gmail.com> Message-ID: <8b6746a9-e4d9-4a47-a11b-e2fd70e61bbc@y10g2000prg.googlegroups.com> > > and employs pyramidal tiling for efficiency > > \me ... time to hit Wikipedia :) It involves scaling an image to various resolutions, and partitioning them into fixed-size tiles. It's roughly the same technique used by Google Maps/Earth. > It is very cool, but I would inject a note of caution here: I'd a hate a zui > to become a case of "hunt-the-zoom." A link is a link. They already work very > well, click and it goes to the page. > I find the notion of minute "hot" areas to be a little obscure -- Quick! Zoom > into the last full-stop, it's a whole word in there! > What I would enjoy is when you click a link - it zooms into the sub-page so > you get a feeling of traversal. Back buttons would zoom out again. Add to that > a kind of birds'-eye view of one's history (like a thumbnails node-graph of > some kind) and it would be perfect! Sure, it was just a quick mockup of a potential application. A proper implementation would probably have more sophisticated features such as that. > This aspect reminds me of the Red Dwarf episode "Back to Reality", in > which Rimmer is criticised for not finding information contained in a > microdot hidden in the dot on the 'i' of his name on a swimming > certificate. Haha, true. > ZUIs are useful for particular types of data - images & mapping > especially - but I'd hate to have to navigate my desktop using its > approach. Obviously there will be some applications that suit more traditional GUIs better than ZUIs, just like there's plenty of applications more suited to the command-line than a GUI. After all, things such as the web and the desktop metaphor came into being long before ZUIs. On Dec 16, 1:09?pm, alex23 wrote: > Donn wrote: > > I find the notion of minute "hot" areas to be a little obscure -- Quick! Zoom > > into the last full-stop, it's a whole word in there! > > This aspect reminds me of the Red Dwarf episode "Back to Reality", in > which Rimmer is criticised for not finding information contained in a > microdot hidden in the dot on the 'i' of his name on a swimming > certificate. > > ZUIs are useful for particular types of data - images & mapping > especially - but I'd hate to have to navigate my desktop using its > approach. From tjreedy at udel.edu Wed Dec 16 00:09:34 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 16 Dec 2009 00:09:34 -0500 Subject: iterators and views of lists In-Reply-To: References: Message-ID: On 12/15/2009 10:39 PM, Brendan Miller wrote: > I was trying to reimplement some of the c++ library of generic > algorithms in c++ in python, but I was finding that this is > problematic to do this in a generic way because there isn't any > equivalent of c++'s forward iterators, random access iterators, etc. > i.e. all python iterators are just input iterators that can't mutate > the sequence they iterate over nor move backwards or by an arbitrary > offset. > > I'm wondering if anyone has done work towards creating more powerful > iterators for python, or creating some more pythonic equivalent. For sequences, integer indexes let you do anything you want that the container supports. No need for anything more, though you can wrap ints if you must. The read-only iterator protocal is intentionally minimal. I From pianomaestro at gmail.com Wed Dec 16 00:46:26 2009 From: pianomaestro at gmail.com (simon) Date: Tue, 15 Dec 2009 21:46:26 -0800 (PST) Subject: Wrapping paper, anyone ? Message-ID: #!/usr/bin/env python from math import * from random import * import cairo from cairo import Context Black = (0, 0, 0) White = (1, 1, 1) def rand(): return random()*2 - 1 def rotate(theta, x, y): x, y = x*cos(theta)-y*sin(theta), x*sin(theta)+y*cos(theta) return x, y def star(ctx, n=5, r0=0.4): for c in range(2): ctx.set_source_rgba(*(White, Black)[c]) x, y = 0, 1 ctx.move_to(x, y) theta = 2*pi / n for i in range(n): x1, y1 = rotate(theta/2, x, y) ctx.line_to(r0*x1, r0*y1) x, y = rotate(theta/2, x1, y1) ctx.line_to(x, y) ctx.close_path() (ctx.fill, ctx.stroke)[c]() class ScribeCall(object): def __init__(self, scribe, name): self.scribe = scribe self.name = name def __call__(self, *args, **kw): self.args = args self.kw = kw self.scribe.calls.append(self) class Scribe(object): def __init__(self): self.calls = [] __getattr__ = ScribeCall def run(self, ctx): for call in self.calls: #print "ctx.%s(%s)" % (call.name, ', '.join(str(x) for x in call.args)) getattr(ctx, call.name)(*call.args, **call.kw) def orbit(dx, dy, w, h): x = -2*w while x < 2*w: y = -2*h while y < 2*h: yield x, y y += dy x += dx def main_stars(w=800, h=1000): seed(0) surface = cairo.PSSurface('stars.ps', w, h) ctx = Context(surface) ctx.set_source_rgba(*White) ctx.rectangle(0, 0, w, h) ctx.fill() ctx.set_line_width(1./30) scribe = Scribe() for i in range(10): scribe.save() scribe.translate(w*random(), h*random()) scribe.scale(20, 20) scribe.rotate(random() * 2 * pi) r = exp(random()) scribe.scale(r, r) star(scribe, 5) scribe.scale(1./r, 1./r) scribe.translate(rand(), rand()) scribe.restore() for x, y in orbit(120, 240, w, h): ctx.save() ctx.translate(x, y) scribe.run(ctx) ctx.restore() if __name__=="__main__": main_stars() From timr at probo.com Wed Dec 16 00:47:00 2009 From: timr at probo.com (Tim Roberts) Date: Tue, 15 Dec 2009 21:47:00 -0800 Subject: strptime not strict enough References: Message-ID: <4ssgi55t36uocn9uqh27ouevnd0chfuiov@4ax.com> Tobias Weber wrote: > >despite the directives for leading zero stime.strptime('09121', >'%y%m%d') returns the first of December. Shouldn't it raise ValueError? Python merely calls the strptime function in your C run-time library. If it sucks, so will time.strptime. >Where do I get strict date parsing? You do it yourself. Strict date parsing is incredibly tricky. The eGenix mx.DateTime module might be more to your liking. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From clp2 at rebertia.com Wed Dec 16 01:20:52 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 15 Dec 2009 22:20:52 -0800 Subject: strptime not strict enough In-Reply-To: <4ssgi55t36uocn9uqh27ouevnd0chfuiov@4ax.com> References: <4ssgi55t36uocn9uqh27ouevnd0chfuiov@4ax.com> Message-ID: <50697b2c0912152220u536e0975kbf5da5acd78cfe99@mail.gmail.com> On Tue, Dec 15, 2009 at 9:47 PM, Tim Roberts wrote: > Tobias Weber wrote: >> >>despite the directives for leading zero stime.strptime('09121', >>'%y%m%d') returns the first of December. Shouldn't it raise ValueError? > > Python merely calls the strptime function in your C run-time library. ?If > it sucks, so will time.strptime. Er, no, wrong: http://svn.python.org/view/python/trunk/Lib/_strptime.py?view=markup Cheers, Chris -- http://blog.rebertia.com From d at vidr.cc Wed Dec 16 02:42:14 2009 From: d at vidr.cc (David Roberts) Date: Tue, 15 Dec 2009 23:42:14 -0800 (PST) Subject: pyZui - anyone know about this? References: <948af6e4-ab38-4d6d-a296-40bccffa7083@2g2000prl.googlegroups.com> Message-ID: PyZUI 0.1 has been released: http://da.vidr.cc/projects/pyzui/ On Dec 15, 12:29?pm, David Roberts wrote: > Hi, > > Yes, the toolkit used is PyQt. The ZUI is implemented using a simple > QPainter, and employs pyramidal tiling for efficiency (I haven't used > any Qt/KDE voodoo in this regard). I'm using Gnome at the moment, but > it should work just as well on KDE. Web pages are rendered using > QtWebKit, and PDF with the pdftoppm utility. > > The project is opensource (GPLv2), but just hasn't been published > yet :) . I'll try to make a release over the next few days, and I'll > post a link here when I do. > > -- > David Robertshttp://da.vidr.cc/ > > On Dec 15, 10:33?am, Donn wrote: > > > > > On Tuesday 15 December 2009 01:43:52 David Boddie wrote:> I managed to catch his address and sent him a message saying that people > > > were discussing PyZUI in this thread. > > > Oooh. Sits,fidgets and waits. I want my socks back! (OP) :D > > > \d > > -- > > \/\/ave: donn.in... at googlewave.com > > home:http://otherwise.relics.co.za/ > > 2D vector animation :https://savannah.nongnu.org/projects/things/ > > Font manager :https://savannah.nongnu.org/projects/fontypython/ From catphive at catphive.net Wed Dec 16 02:48:04 2009 From: catphive at catphive.net (Brendan Miller) Date: Tue, 15 Dec 2009 23:48:04 -0800 Subject: iterators and views of lists In-Reply-To: References: Message-ID: On Tue, Dec 15, 2009 at 9:09 PM, Terry Reedy wrote: > On 12/15/2009 10:39 PM, Brendan Miller wrote: >> I'm wondering if anyone has done work towards creating more powerful >> iterators for python, or creating some more pythonic equivalent. > > For sequences, integer indexes let you do anything you want that the > container supports. No, that's what I'm getting at... Most of the existing mutating algorithms in python (sort, reverse) operate over entire collections, not partial collections delimited by indexes... which would be really awkward anyway. Currently people slice and dice with well... slices, but those are copying, so if you want to operate over part of a range you make a copy, perform the operation, then copy the results back in. I was thinking you'd want something like random access iterators in c++, or pointers in c, to write typical in place algorithmic code. To me, something like non-copying slices (maybe you'd call it a list view?) would seem functionally similar and maybe more pythonic. From andrea.gavana at gmail.com Wed Dec 16 03:37:41 2009 From: andrea.gavana at gmail.com (Infinity77) Date: Wed, 16 Dec 2009 00:37:41 -0800 (PST) Subject: Where is PyMethod_GET_CLASS in Python 3? References: <1799a93b-5eb8-4818-ab94-7aa4108fcea1@j24g2000yqa.googlegroups.com> Message-ID: Hi, On Dec 15, 9:22?pm, Terry Reedy wrote: > On 12/15/2009 11:08 AM, Infinity77 wrote: > > > Hi All, > > > ? ? ?When building C extensions In Python 2.X, there was a magical > > PyMethod_GET_CLASS implemented like this: > > > #define PyMethod_GET_CLASS(meth) \ > > ? ?(((PyMethodObject *)meth) -> ?im_class) > > > It looks like Python 3 has wiped out the "im_class" attribute. > > For bound methods, renamed to __class__ to be consistent with other > objects. Unbound methods were eliminated as extra cruft. First of all, thank you for your answer. However, being a complete newbie in writing C extension, I couldn't seem to find a way to do what I asked in the first place: Try 1: # define PyMethod_GET_CLASS(meth) \ (((PyMethodObject *)meth) -> __class__) error C2039: '__class__' : is not a member of 'PyMethodObject' Try 2: PyObject * magicClass = method -> __class__ error C2039: '__class__' : is not a member of '_object' I know I am doing something stupid, please be patient :-D . Any suggestion is more than welcome. Andrea. From __peter__ at web.de Wed Dec 16 04:04:44 2009 From: __peter__ at web.de (Peter Otten) Date: Wed, 16 Dec 2009 10:04:44 +0100 Subject: AttributeError: logging module bug ? References: <4dc0cfea0912151005g7cf389ddx2e3d9d5a62338344@mail.gmail.com> <4B27D721.2010707@mrabarnett.plus.com> <4dc0cfea0912151112n235fa28vd509a36ddfc4ade9@mail.gmail.com> Message-ID: Peter wrote: >>> What's the problem ? >>> >> Please provide the config file "logging.cfg" to ease debugging. >> >> Peter >> > Here it is, thanks for having a look > Peter Unfortunately I still can't reproduce your problem. With a minimal file ./of/logger.py from logging import Formatter class RootFormatter(Formatter): pass class ModuleFormatter(Formatter): pass class ClassFormatter(Formatter): pass class DataFormatter(Formatter): pass (and an empty ./of/__init__.py) your initial script runs without error. If you want external help please (1) make sure that you provide all necessary files needed to reproduce the error (2) remove as much of the code as possible that does not contribute to the problem. (This is also an effective debugging technique) Peter From victorsubervi at gmail.com Wed Dec 16 04:13:57 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Wed, 16 Dec 2009 04:13:57 -0500 Subject: Storing a Value in a Cookie Message-ID: <4dc0cfea0912160113ne6fef2awcbad758f66450021@mail.gmail.com> Hi; >From what I've studied and gotten working about cookies, it seems one can store only a certain few pieces of information--expiration, path, comment, domain, max-age, version and last visit--but how is it useful if one can't also store, say, the name of a temporary MySQL table where pertinent customer data, such as shopping cart data, is stored? I guess I could put that into the comment field, but I suspect there's a better way of doing it. Please advise. TIA, Victor -------------- next part -------------- An HTML attachment was scrubbed... URL: From dmitrey.kroshko at scipy.org Wed Dec 16 04:35:42 2009 From: dmitrey.kroshko at scipy.org (dmitrey) Date: Wed, 16 Dec 2009 01:35:42 -0800 (PST) Subject: [ANN] OpenOpt 0.27 (optimization), FuncDesigner 0.17 (auto differentiation) Message-ID: <04ec8a11-e932-4446-a08a-7f01a21a8114@r1g2000vbp.googlegroups.com> Hi all, I'm glad to inform you about release of OpenOpt 0.27 (numerical optimization framework), FuncDesigner 0.17 (CAS with automatic differentiation, convenient modelling of linear/nonlinear functions, can use convenient modelling for some OpenOpt optimization problems and systems of linear/nonlinear equations, possibly sparse or overdetermined), DerApproximator 0.17 (finite-differences derivatives approximation, get or check user-supplied). These packages are written in Python language + NumPy; license BSD allows to use it in both free and closed-code soft See changelog for details: http://openopt.org/Changelog Regards, D. From clp2 at rebertia.com Wed Dec 16 04:42:19 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Wed, 16 Dec 2009 01:42:19 -0800 Subject: Storing a Value in a Cookie In-Reply-To: <4dc0cfea0912160113ne6fef2awcbad758f66450021@mail.gmail.com> References: <4dc0cfea0912160113ne6fef2awcbad758f66450021@mail.gmail.com> Message-ID: <50697b2c0912160142t31ede39at258853da62ee3cb@mail.gmail.com> On Wed, Dec 16, 2009 at 1:13 AM, Victor Subervi wrote: > Hi; > From what I've studied and gotten working about cookies, it seems one can > store only a certain few pieces of information--expiration, path, comment, > domain, max-age, version and last visit--but how is it useful if one can't > also store, say, the name of a temporary MySQL table where pertinent > customer data, such as shopping cart data, is stored? I guess I could put > that into the comment field, but I suspect there's a better way of doing it. > Please advise. Besides the metadata you mentioned, a cookie can also store one key-value pair, which is sent as the first part of the "Cookie" HTTP header when setting the cookie ("Cookie: name=value"); this is typically used to store a session ID. It is inadvisable to store much data other than a session ID in a cookie because as a rule, in order to avoid security risks, clients should not be trusted. In the example you give of storing the name of an SQL table, someone could guess the name of another user's SQL table and alter their cookie to masquerade as that user, thus compromising the other customer's shopping cart, and depending on the contents of the SQL table, potentially their credit card. Most web frameworks, like Django, will handle low-level details like setting and getting cookies for you and provide a higher-level API for dealing with sessions and/or users. Cheers, Chris -- http://blog.rebertia.com From victorsubervi at gmail.com Wed Dec 16 04:49:50 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Wed, 16 Dec 2009 04:49:50 -0500 Subject: Spot Metals Prices (slightly OT) Message-ID: <4dc0cfea0912160149r5ebd611boc681726fab293767@mail.gmail.com> Hi; I need to update a client's site with spot metals prices. I could build a scraper to grab them off someone else' site (they only need to be accurate within 24 hours), but is there a better *free* source? TIA, Victor -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Wed Dec 16 05:00:24 2009 From: __peter__ at web.de (Peter Otten) Date: Wed, 16 Dec 2009 11:00:24 +0100 Subject: Wrapping paper, anyone ? References: Message-ID: simon wrote: Nice :) --- stars.py 2009-12-16 10:52:49.553505036 +0100 +++ stars_fixed.py 2009-12-16 10:53:32.545786454 +0100 @@ -48,7 +48,9 @@ def __init__(self): self.calls = [] - __getattr__ = ScribeCall + def __getattr__(self, name): + return ScribeCall(self, name) + def run(self, ctx): for call in self.calls: #print "ctx.%s(%s)" % (call.name, ', '.join(str(x) for x in call.args)) Peter From lie.1296 at gmail.com Wed Dec 16 05:03:01 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Wed, 16 Dec 2009 21:03:01 +1100 Subject: strptime not strict enough In-Reply-To: References: Message-ID: <4b28b067$1@dnews.tpgi.com.au> On 12/15/2009 10:30 AM, Tobias Weber wrote: > Hi, > despite the directives for leading zero stime.strptime('09121', > '%y%m%d') returns the first of December. Shouldn't it raise ValueError? > > Where do I get strict date parsing? A bit hackish perhaps, but maybe you can check for the date's length: date = '09121' if len(date) == 6 and time.strptime(date, format): ... From tony at tonyburrows.com Wed Dec 16 05:09:38 2009 From: tony at tonyburrows.com (Tony) Date: Wed, 16 Dec 2009 10:09:38 +0000 Subject: accessing gmail References: <899b08c6-3162-4911-841e-fbc03dbeaa37@r24g2000prf.googlegroups.com> Message-ID: Intchanter / Daniel Fackrell wrote: > http://mail.google.com/support/bin/answer.py?hl=en&answer=77654 Thanks! Actually I had a sudden inspiration last night as I went to bed. I'd set up Thunderbird, all I needed to do was use the same full host at domain as the username. Stupid, stupid - I'd wasted so much time and it was so simple. I will remember it though. Now to figure out the rest of it. Tony From victorsubervi at gmail.com Wed Dec 16 05:21:52 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Wed, 16 Dec 2009 05:21:52 -0500 Subject: Storing a Value in a Cookie In-Reply-To: <50697b2c0912160142t31ede39at258853da62ee3cb@mail.gmail.com> References: <4dc0cfea0912160113ne6fef2awcbad758f66450021@mail.gmail.com> <50697b2c0912160142t31ede39at258853da62ee3cb@mail.gmail.com> Message-ID: <4dc0cfea0912160221v105dc4efvaddca97386431c13@mail.gmail.com> On Wed, Dec 16, 2009 at 4:42 AM, Chris Rebert wrote: > On Wed, Dec 16, 2009 at 1:13 AM, Victor Subervi > wrote: > > Hi; > > From what I've studied and gotten working about cookies, it seems one can > > store only a certain few pieces of information--expiration, path, > comment, > > domain, max-age, version and last visit--but how is it useful if one > can't > > also store, say, the name of a temporary MySQL table where pertinent > > customer data, such as shopping cart data, is stored? I guess I could put > > that into the comment field, but I suspect there's a better way of doing > it. > > Please advise. > > Besides the metadata you mentioned, a cookie can also store one > key-value pair, which is sent as the first part of the "Cookie" HTTP > header when setting the cookie ("Cookie: name=value"); this is > typically used to store a session ID. > It is inadvisable to store much data other than a session ID in a > cookie because as a rule, in order to avoid security risks, clients > should not be trusted. In the example you give of storing the name of > an SQL table, someone could guess the name of another user's SQL table > and alter their cookie to masquerade as that user, thus compromising > the other customer's shopping cart, and depending on the contents of > the SQL table, potentially their credit card. > Most web frameworks, like Django, will handle low-level details like > setting and getting cookies for you and provide a higher-level API for > dealing with sessions and/or users. > Well, I'm not using a web framework like Django and this shopping cart is almost completely written, so I'm not about to switch. So, how do I use the session ID to correlate with the user's temp MySQL table? TIA, V -------------- next part -------------- An HTML attachment was scrubbed... URL: From victorsubervi at gmail.com Wed Dec 16 05:23:03 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Wed, 16 Dec 2009 05:23:03 -0500 Subject: Calling Cookie Values In-Reply-To: References: <4dc0cfea0912151005g7cf389ddx2e3d9d5a62338344@mail.gmail.com> <4B27D721.2010707@mrabarnett.plus.com> <4dc0cfea0912151112n235fa28vd509a36ddfc4ade9@mail.gmail.com> Message-ID: <4dc0cfea0912160223w69a4b209ocea676e713934b8b@mail.gmail.com> On Tue, Dec 15, 2009 at 4:01 PM, Grant Edwards wrote: > > On Tue, Dec 15, 2009 at 2:36 PM, MRAB > > wrote: > > > > You've just created a cookie, but are trying to get a value without > > having set it first! > > > > > > LOL! Rewrote code thus: > > > > cookie = os.environ.get('HTTP_COOKIE') > > if not cookie: > > cookie = Cookie.SimpleCookie() > > cExpires, cPath, cComment, cDomain, cMaxAge, cVersion = myCookie() > > cookie['lastvisit'] = str(time.time()) > > cookie['lastvisit'] is a string. > > > cookie['lastvisit']['expires'] = cExpires > > Here you're using the string 'expires' as an index into the > string returned by str(time.time()). You can only index into > strings using integers. > > What do you expect the following statement to do? > > '1260910829.18'['expires'] = > > > cookie['lastvisit']['path'] = cPath > > cookie['lastvisit']['comment'] = cComment > > cookie['lastvisit']['domain'] = cDomain > > cookie['lastvisit']['max-age'] = cMaxAge > > cookie['lastvisit']['version'] = cVersion > > cookieFlag = 'new' > > else: > > cookieFlag = 'old' > > print cookie['lastvisit']['expires'].value > > > > Got this error: > > > > /var/www/html/angrynates.com/cart/cart.py > > > > 191 > > 192 ''' > > 193 > > 194 cart() > > 195 > > cart = > > /var/www/html/angrynates.com/cart/cart.py > > in cart() > > 31 else: > > 32 cookieFlag = 'old' > > 33 print cookie['lastvisit']['expires'].value > > 34 # Don't know what to do with this. It's for when client won't > > accept cookies > > 35 # sessionDir = os.environ['DOCUMENT_ROOT'] + '/tmp/.session' > > cookie = 'lastvisit=1260898013.65; lastvisit=1260898315.01', ].value > > undefined > > > > TypeError: string indices must be integers > > args = ('string indices must be integers',) > > You took the string returned by str(time.time()) and tried to > use 'expires' as an index into that time string. You can't use > a string to index into a string. You can only use integers. > That's what is mean't by the error message: > > TypeError: string indices must be integers > Thank you. V -------------- next part -------------- An HTML attachment was scrubbed... URL: From michele.simionato at gmail.com Wed Dec 16 05:31:57 2009 From: michele.simionato at gmail.com (Michele Simionato) Date: Wed, 16 Dec 2009 02:31:57 -0800 (PST) Subject: Dangerous behavior of list(generator) References: <20091213143521.2549.845539319.divmod.xquotient.731@localhost.localdomain> <4B2652AB.7080501@egenix.com> <07356731-e5be-43cd-8328-6ef6dc84f155@p23g2000vbl.googlegroups.com> Message-ID: <9afe41cb-0c00-4745-8fbf-2c8914c72d3e@k9g2000vbl.googlegroups.com> On Dec 14, 11:05?pm, Carl Banks wrote: > But to answer your question, I think "simple is better than complex" > rules the day. ?Right now StopIteration stops an iteration, simple as > that. ?Any fix would add complexity. +1 From john_re at fastmail.us Wed Dec 16 05:38:17 2009 From: john_re at fastmail.us (john_re) Date: Wed, 16 Dec 2009 02:38:17 -0800 Subject: Dec 20 Global Python & All Free SW HW Culture meeting - BerkeleyTIP Message-ID: <1260959897.25547.1350355127@webmail.messagingengine.com> A great December Solstice to you & yours. :) JOIN the Global All Free SW, HW, Culture meeting via VOIP Dec 20 Sunday, 12N-3PM (Pacific = UTC-8) = 3P-6P Eastern = 8P-11P UTC [Jan 2009 meetings: 2nd, 17th - mark your calendar] http://sites.google.com/site/berkeleytip/schedule == WATCH some VIDEOS: Mark Shuttleworth Interview - 10.04 Lucid Larynx Learning from Code History , Andreas Zeller Why does my program fail? Your version history might have the answer. Audio Hardware Enablement Session, UbuntuDevelopersSummit in Dallas Distributed Development, UDS in Dallas Splunk, Jeremy Thurgood CLUG Upstart, Stefano Rivera CLUG Interfacing with the real world, Mark Ter Morshuizen, Marc Welz CLUG Accelerating Graphics; Camp KDE 2009 http://sites.google.com/site/berkeleytip/talk-videos == Join the MAILING LIST & tell us which videos you will watch & why: http://groups.google.com/group/BerkTIPGlobal == JOIN the meeting via IRC & VOIP: Come discuss any & everything, & work on your individual or group projects. HOT TOPICS: Ub or KUb 9.10?, Ubuntu 10.04 plans, Android, Python3000 in 2010? Start on the #berkeleytip irc.freenode.net channel, & we'll help you get your VOIP system up & working. For VOIP SW, & connection info, see: http://sites.google.com/site/berkeleytip/remote-attendance Berkeley meeting LOCATION: Watch the website & mail list for latest details, perhaps at the Berkeley Public Library, or a cafe, due to Free Speech Cafe closed for winter break. http://sites.google.com/site/berkeleytip/ == OPPORTUNITIES to VOLUNTEER or learn new JOB SKILLS for 2010: Help set up our: Mailing list, FreeSwitch VOIP server, website http://sites.google.com/site/berkeleytip/opportunities Inquire & discuss at the meeting. == For Forwarding - You are invited to forward this announcement wherever it would be appreciated. From bearophileHUGS at lycos.com Wed Dec 16 05:54:03 2009 From: bearophileHUGS at lycos.com (Bearophile) Date: Wed, 16 Dec 2009 02:54:03 -0800 (PST) Subject: iterators and views of lists References: Message-ID: <996e713f-a2f6-440f-a0b3-e958d0da5b91@1g2000vbe.googlegroups.com> Brendan Miller: > Currently people slice and dice with well... slices, but those are > copying, so if you want to operate over part of a range you make a > copy, perform the operation, then copy the results back in. > > I was thinking you'd want something like random access iterators in > c++, or pointers in c, to write typical in place algorithmic code. To > me, something like non-copying slices (maybe you'd call it a list > view?) would seem functionally similar and maybe more pythonic. There are surely ways to modify the current situation, introducing views, and other kind of iterators (C++ design in this regard can be improved, see the last works of Andrei Alexandrescu about D). This can lead to a certain increase of the performance of Python programs, but it also surely makes writing programs harder and introduces new bug sources. Modern languages are now doing something kinda different from what you ask for, introducing more immutable data (that in theory lead to more copying, but in practice allow for more data sharing too, because there's less need to actually copy data when the data is immutable), see Clojure. An hypothetical Python language designed today probably copies more stuff from Haskell and Clojure. Python is kept intentionally simple, because it's designed to be usable by people that are not just professional programmers, but for example a biologist that needs to perform some computations and doesn't want to use all the time learning how to use the language itself (think about C++ again). So Python programmers live with a less performing language. When performance of the code is not enough (even with the future Unladen Swallow), they use another language (often to write extensions used from Python code). Bye, bearophile From steve at REMOVE-THIS-cybersource.com.au Wed Dec 16 06:39:07 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 16 Dec 2009 11:39:07 GMT Subject: iterators and views of lists References: Message-ID: <00b24b82$0$15654$c3e8da3@news.astraweb.com> On Tue, 15 Dec 2009 23:48:04 -0800, Brendan Miller wrote: > On Tue, Dec 15, 2009 at 9:09 PM, Terry Reedy wrote: >> On 12/15/2009 10:39 PM, Brendan Miller wrote: >>> I'm wondering if anyone has done work towards creating more powerful >>> iterators for python, or creating some more pythonic equivalent. >> >> For sequences, integer indexes let you do anything you want that the >> container supports. > > No, that's what I'm getting at... Most of the existing mutating > algorithms in python (sort, reverse) operate over entire collections, > not partial collections delimited by indexes... which would be really > awkward anyway. I'm sympathetic to your request for list views. I've often wanted some way to cleanly and neatly do this: for item in seq[1:]: process(item) without making an unnecessary copy of almost all of seq. None of the alternatives are very nice. They all obscure the simplicity of the algorithm and add unnecessary effort: for i, item in seq: if i != 0: process(item) it = iter(seq) try: it.next() # throw the first value away except StopIteration: pass for item in it: process(item) if not isinstance(seq, basestring): raise TypeError("this only works on strings") for item in buffer(seq, 1): process(item) Although that last one is the least horrible, particularly if you are prepared to drop the explicit type-check. > Currently people slice and dice with well... slices, but those are > copying, so if you want to operate over part of a range you make a copy, > perform the operation, then copy the results back in. > > I was thinking you'd want something like random access iterators in c++, > or pointers in c, to write typical in place algorithmic code. To me, > something like non-copying slices (maybe you'd call it a list view?) > would seem functionally similar and maybe more pythonic. Unless you have a really huge amount of data in your list, chances are that the cost of making a temporary copy will be relatively small. After all, under the hood you're just copying pointers (at least for CPython), not the entire data object. So most of the time the extra complexity of in-place algorithms is just premature optimization. But not always. -- Steven From paul.nospam at rudin.co.uk Wed Dec 16 07:16:03 2009 From: paul.nospam at rudin.co.uk (Paul Rudin) Date: Wed, 16 Dec 2009 12:16:03 +0000 Subject: iterators and views of lists References: <00b24b82$0$15654$c3e8da3@news.astraweb.com> Message-ID: <87hbrrunb0.fsf@rudin.co.uk> Steven D'Aprano writes: > I'm sympathetic to your request for list views. I've often wanted some > way to cleanly and neatly do this: > > for item in seq[1:]: > process(item) > > without making an unnecessary copy of almost all of seq. > I don't know how it's implemented - but presumably itertools.islice could provide what you're asking for? From brendandetracey at yahoo.com Wed Dec 16 07:41:17 2009 From: brendandetracey at yahoo.com (Brendan) Date: Wed, 16 Dec 2009 04:41:17 -0800 (PST) Subject: ftplib retrlines timeout References: Message-ID: On Dec 15, 6:17?pm, Jennifer wrote: > I am writing a program that has a requirement for ?a timeout of > retrlines after the connection established. I just wonder if timeout > of ftplib.FTP('xxxx.xxx.com',username,password,timeout) will work for > retrlines method after the connection established. Or > socket.setdefaulttimeout will work in this case. Please let me know. > > What exception will be throwed if ftp.retrlines timed out. > > Many Thanks! > > - Jennifer I asked a similar question on here a few days ago and got no response, however I tried a large download which timed out with the following: Traceback (most recent call last): File "./download_r1_neodf.py", line 167, in result = ftp.quit() File "/usr/local/lib/python2.6/ftplib.py", line 566, in quit resp = self.voidcmd('QUIT') File "/usr/local/lib/python2.6/ftplib.py", line 248, in voidcmd return self.voidresp() File "/usr/local/lib/python2.6/ftplib.py", line 223, in voidresp resp = self.getresp() File "/usr/local/lib/python2.6/ftplib.py", line 209, in getresp resp = self.getmultiline() File "/usr/local/lib/python2.6/ftplib.py", line 195, in getmultiline line = self.getline() File "/usr/local/lib/python2.6/ftplib.py", line 182, in getline line = self.file.readline() File "/usr/local/lib/python2.6/socket.py", line 406, in readline data = self._sock.recv(self._rbufsize) socket.error: [Errno 110] Connection timed out BTW, if you want to use the timeout paramter, you must also use the account parameter. Set it to ''. From gabriel.rossetti at arimaz.com Wed Dec 16 07:42:14 2009 From: gabriel.rossetti at arimaz.com (Gabriel Rossetti) Date: Wed, 16 Dec 2009 13:42:14 +0100 Subject: platform module problem when frozen? Message-ID: <4B28D5A6.6010201@arimaz.com> Hello everyone, I am having problems with the platform module when being run from a frozen program (py2exe). It imports it fine, but it gives me the following error : 'module' object does not contain attribute 'platform' when I do this : platform.platfom() Does platform have a problem with being called when in a frozen program or does it do some stuff behind the scenes that py2exe doesn't pickup? Thank you, Gabriel From fetchinson at googlemail.com Wed Dec 16 07:55:19 2009 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Wed, 16 Dec 2009 13:55:19 +0100 Subject: pyZui - anyone know about this? In-Reply-To: References: <948af6e4-ab38-4d6d-a296-40bccffa7083@2g2000prl.googlegroups.com> Message-ID: > PyZUI 0.1 has been released: > > http://da.vidr.cc/projects/pyzui/ Cool, thanks very much! I'm using python 2.6 these days and noticed that you use the sha module which makes py2.6 spit out a deprecation warning: /home/fetchinson/pyzui/pyzui/tilestore.py:22: DeprecationWarning: the sha module is deprecated; use the hashlib module instead import sha It's no big deal but if you want to be future proof maybe you can switch to hashlib for py2.6 and stay with sha for py2.5 and before (a try/except block would suffice). Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From anh.hai.trinh at gmail.com Wed Dec 16 07:58:58 2009 From: anh.hai.trinh at gmail.com (Anh Hai Trinh) Date: Wed, 16 Dec 2009 04:58:58 -0800 (PST) Subject: iterators and views of lists References: Message-ID: <10d50933-c1e8-44a8-af35-dce39c444778@u18g2000pro.googlegroups.com> On Dec 16, 10:39?am, Brendan Miller wrote: > I was trying to reimplement some of the c++ library of generic > algorithms in c++ in python, but I was finding that this is > problematic to do this in a generic way because there isn't any > equivalent of c++'s forward iterators, random access iterators, etc. > i.e. all python iterators are just input iterators that can't mutate > the sequence they iterate over nor move backwards or by an arbitrary > offset. You might be interested in this library . You can easily create arbitrary "slice", for example i = mylist >> takei(primes()) will return an iterator over the items of mylist with a prime number index, given that primes() return an iterator over prime numbers. I'm not familiar with forward/random-access/bidirectional iterators. From gervaz at gmail.com Wed Dec 16 08:23:10 2009 From: gervaz at gmail.com (gervaz) Date: Wed, 16 Dec 2009 05:23:10 -0800 (PST) Subject: py3.x urllib.request - HTTPCookieProcessor and header adding Message-ID: <5d3b4874-1c16-4472-9e85-f6928c8e7ede@g12g2000vbl.googlegroups.com> Hi all, I need to fetch some html pages and it is required to have cookies enabled. So, I'm using opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor ()) urllib.request.install_opener(opener) as a global instance. Is there a way to always use a default header like: {"User-Agent": "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv: 1.9.1.5) Gecko/20091102 Firefox/3.5.5"} instead of always creating urllib.request.Request(my_url, None, headers) and call different urls with the same cookies? Thanks, Mattia From aioe.org at technicalbloke.com Wed Dec 16 08:30:05 2009 From: aioe.org at technicalbloke.com (r0g) Date: Wed, 16 Dec 2009 13:30:05 +0000 Subject: pyZui - anyone know about this? References: <948af6e4-ab38-4d6d-a296-40bccffa7083@2g2000prl.googlegroups.com> Message-ID: David Roberts wrote: > PyZUI 0.1 has been released: > > http://da.vidr.cc/projects/pyzui/ > Cool, thanks :) Roger. From victorsubervi at gmail.com Wed Dec 16 08:30:35 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Wed, 16 Dec 2009 09:30:35 -0400 Subject: (OT) Where Are Cookies Stored? In-Reply-To: References: <4dc0cfea0912150730w1d0c131agb258029b3e9a21ca@mail.gmail.com> Message-ID: <4dc0cfea0912160530l5c7a66f0ia23ff98fbafb99e8@mail.gmail.com> On Tue, Dec 15, 2009 at 6:57 PM, r0g wrote: > Gabriel Genellina wrote: > > En Tue, 15 Dec 2009 12:30:23 -0300, Victor Subervi > > escribi?: > > > >> I've googled, found where cookies are supposed to be, the folders and > >> files > >> don't exist. I've opened my latest and greatest FF and seen cookies in > >> there, but when I search for the name of the cookie in the C: dir, > >> it's not > >> there...anywhere. I've made sure no folders/files are hidden and I still > >> can't find them. In as administrator. What up? XP OS I need to get in > >> so I > >> can learn how to program with cookies. > > > > How the browser stores its cookies should be irrelevant. Whenever a > > server response contains a Set-Cookie header, the browser saves the > > cookie. When the client issues a request that matches a saved cookie, it > > adds a Cookie header with the cookie. From the server POV, you don't > > care how the cookie is stored. > > > > > Cookies in FF for Windows are stored in an sqlite database in here... > > ~\Application Data\Mozilla\Firefox\Profiles\%XYZ%\firefox_profile\ > Man, I searched C drive (the only drive) on this computer where I'm working (Internet cafe) for "Application Data" and nuttin. V -------------- next part -------------- An HTML attachment was scrubbed... URL: From victorsubervi at gmail.com Wed Dec 16 08:31:38 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Wed, 16 Dec 2009 09:31:38 -0400 Subject: (OT) Where Are Cookies Stored? In-Reply-To: <00b19258$0$15654$c3e8da3@news.astraweb.com> References: <4dc0cfea0912150730w1d0c131agb258029b3e9a21ca@mail.gmail.com> <00b19258$0$15654$c3e8da3@news.astraweb.com> Message-ID: <4dc0cfea0912160531w212f7402y919d88f1dd473dd0@mail.gmail.com> On Tue, Dec 15, 2009 at 6:29 PM, Steven D'Aprano < steve at remove-this-cybersource.com.au> wrote: > On Tue, 15 Dec 2009 13:03:07 -0300, Gabriel Genellina wrote: > > > En Tue, 15 Dec 2009 12:30:23 -0300, Victor Subervi > > escribi?: > > > >> I've googled, found where cookies are supposed to be, the folders and > >> files don't exist. > [...] > > How the browser stores its cookies should be irrelevant. Whenever a > > server response contains a Set-Cookie header, the browser saves the > > cookie. When the client issues a request that matches a saved cookie, it > > adds a Cookie header with the cookie. From the server POV, you don't > > care how the cookie is stored. > > But you do care if you're writing a cookie manager, or if you need to > grab an existing cookie from disk and do something with it (as wget > allows you to do, for example). > > Victor, have you got Firefox set to delete all cookies when you log out? > No. I can see the *$^@& cookies in Tools/Options but I can't find 'em! V -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Wed Dec 16 08:33:05 2009 From: __peter__ at web.de (Peter Otten) Date: Wed, 16 Dec 2009 14:33:05 +0100 Subject: iterators and views of lists References: <00b24b82$0$15654$c3e8da3@news.astraweb.com> <87hbrrunb0.fsf@rudin.co.uk> Message-ID: Paul Rudin wrote: > Steven D'Aprano writes: > > >> I'm sympathetic to your request for list views. I've often wanted some >> way to cleanly and neatly do this: >> >> for item in seq[1:]: >> process(item) >> >> without making an unnecessary copy of almost all of seq. >> > > I don't know how it's implemented - but presumably itertools.islice > could provide what you're asking for? For skipping just a few items islice() is perfect, for big offsets its O(N) behaviour may get annoying: $ python -m timeit -s"from itertools import islice; N=10**5; r = range(N)" "for i in islice(r, N, N): pass" 100 loops, best of 3: 1.93 msec per loop $ python -m timeit -s"from itertools import islice; N=10**6; r = range(N)" "for i in islice(r, N, N): pass" 10 loops, best of 3: 18.9 msec per loop $ python -m timeit -s"from itertools import islice; N=10**7; r = range(N)" "for i in islice(r, N, N): pass" 10 loops, best of 3: 188 msec per loop islice() could be changed to special-case lists and tuples, but that feels a bit unclean. From aioe.org at technicalbloke.com Wed Dec 16 08:36:32 2009 From: aioe.org at technicalbloke.com (r0g) Date: Wed, 16 Dec 2009 13:36:32 +0000 Subject: Wrapping paper, anyone ? References: Message-ID: Peter Otten wrote: > simon wrote: > > Nice :) > > --- stars.py 2009-12-16 10:52:49.553505036 +0100 > +++ stars_fixed.py 2009-12-16 10:53:32.545786454 +0100 > @@ -48,7 +48,9 @@ > def __init__(self): > self.calls = [] > > - __getattr__ = ScribeCall > + def __getattr__(self, name): > + return ScribeCall(self, name) > + > def run(self, ctx): > for call in self.calls: > #print "ctx.%s(%s)" % (call.name, ', '.join(str(x) for x in > call.args)) > > Peter Nice :) Now all I need is an A0 printer, maybe Santa will bring me one! Roger. From pavlovevidence at gmail.com Wed Dec 16 09:06:08 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 16 Dec 2009 06:06:08 -0800 (PST) Subject: iterators and views of lists References: Message-ID: <328d8c18-5556-4371-8f24-40bfac92e280@g31g2000vbr.googlegroups.com> On Dec 15, 11:48?pm, Brendan Miller wrote: > I was thinking you'd want something like random access iterators in > c++, or pointers in c, to write typical in place algorithmic code. To > me, something like non-copying slices (maybe you'd call it a list > view?) would seem functionally similar and maybe more pythonic. My general answer to the question, "Has anyone done any work in Python to get a certain feature that we have in C++?, is, "There's little demand for many features of C++ because they are actually workarounds for the language's poor expressibility". I'd say that's kind of the case here. C++ is poorly expressive (container operations are often an excercise in line-noise-management), and values fine-tuned optimization. So it makes sense to offer things like mutator views that reduce the number of container operations needed, and avoids copying. Python expresses container operations succinctly and clearly, and doesn't value performance as much. Copying and replacing is good enough most of the time, so there's less demand for things like mutator views. Carl Banks From e_d_k at yahoo.com Wed Dec 16 09:09:32 2009 From: e_d_k at yahoo.com (Ed Keith) Date: Wed, 16 Dec 2009 06:09:32 -0800 (PST) Subject: Raw string substitution problem Message-ID: <931375.44828.qm@web58902.mail.re1.yahoo.com> I am having a problem when substituting a raw string. When I do the following: re.sub('abc', r'a\nb\nc', '123abcdefg') I get """ 123a b cdefg """ what I want is r'123a\nb\ncdefg' How do I get what I want? Thanks, -EdK Ed Keith e_d_k at yahoo.com Blog: edkeith.blogspot.com From daniel at stutzbachenterprises.com Wed Dec 16 09:12:58 2009 From: daniel at stutzbachenterprises.com (Daniel Stutzbach) Date: Wed, 16 Dec 2009 08:12:58 -0600 Subject: iterators and views of lists In-Reply-To: References: <00b24b82$0$15654$c3e8da3@news.astraweb.com> <87hbrrunb0.fsf@rudin.co.uk> Message-ID: On Wed, Dec 16, 2009 at 7:33 AM, Peter Otten <__peter__ at web.de> wrote: > islice() could be changed to special-case lists and tuples, but that feels > a > bit unclean. > How about special-casing objects that implement collections.Sequence? -- Daniel Stutzbach, Ph.D. President, Stutzbach Enterprises, LLC -------------- next part -------------- An HTML attachment was scrubbed... URL: From daniel at stutzbachenterprises.com Wed Dec 16 09:18:23 2009 From: daniel at stutzbachenterprises.com (Daniel Stutzbach) Date: Wed, 16 Dec 2009 08:18:23 -0600 Subject: iterators and views of lists In-Reply-To: <00b24b82$0$15654$c3e8da3@news.astraweb.com> References: <00b24b82$0$15654$c3e8da3@news.astraweb.com> Message-ID: On Wed, Dec 16, 2009 at 5:39 AM, Steven D'Aprano < steve at remove-this-cybersource.com.au> wrote: > for item in seq[1:]: > process(item) > > without making an unnecessary copy of almost all of seq. > I use the following idiom: for i in range(1, len(seq)): process(seq[i]) Alternately, if I'm using the blist extension type that I wrote, then seq[1:] is O(log n). http://pypi.python.org/pypi/blist/ -- Daniel Stutzbach, Ph.D. President, Stutzbach Enterprises, LLC -------------- next part -------------- An HTML attachment was scrubbed... URL: From jkpeck at gmail.com Wed Dec 16 09:21:29 2009 From: jkpeck at gmail.com (JKPeck) Date: Wed, 16 Dec 2009 06:21:29 -0800 (PST) Subject: Problems with gettext and msgfmt References: <4caf86f5-c760-4c08-a9f8-ea70b49ca433@k9g2000vbl.googlegroups.com> Message-ID: <5b8b8c35-cb67-4d1a-8579-ac7a81bbc0f5@h2g2000vbd.googlegroups.com> On Dec 15, 9:12?pm, JKPeck wrote: > I'm using Python 2.6 on Windows and having trouble with the charset in > gettext. ?It seems to be so broken that I must be missing something. > > When I run msgfmt.py, as far as I can see it writes no charset > information into the mo file. ?The actual po files are in utf-8 in > this case and have a charset declaration. > > Then when ,_parse in gettext loads the messages, it does no conversion > to Unicode, because it has no charset information. ?So the message > dictionary is actually in utf-8 despite the comment in the code > # Note: we unconditionally convert both msgids and msgstrs to > ? ? ? ? ? ? # Unicode using the character encoding specified in the > charset > ? ? ? ? ? ? # parameter of the Content-Type header. > > Then ugettext tries to just return the translated message, which is > not in Unicode, or to convert to Unicode, which fails because the > unicode call is not specifying any encoding. > > The _parse code seems to expect to produce a Unicode translation > dictionary, and gettext expects to encode Unicode into the current > code page, but the message dictionary never gets mapped to Unicode in > the first place. > > What I want is simply to use utf-8 po files and get translations in > Unicode. > > TIA for any suggestions. > > -Jon Peck Never mind. I figured this out. The problem is that a line such as _("") in the source that is scanned causes all the meta information to be lost in the mo file. Once I changed that code, I get the expected result. From james at agentultra.com Wed Dec 16 09:26:02 2009 From: james at agentultra.com (J Kenneth King) Date: Wed, 16 Dec 2009 09:26:02 -0500 Subject: Object Relational Mappers are evil (a meditation) References: <06532563-3f2b-4cca-802f-34cb326e6d9f@v20g2000vbs.googlegroups.com> <16a44521-1f07-454a-ace7-9ba5d5db4b9c@y28g2000prd.googlegroups.com> <50f98a4c0910060810k3a4fa910vabc5bf51381d00f9@mail.gmail.com> <00ac7cf3$0$15654$c3e8da3@news.astraweb.com> Message-ID: <85hbrrxaf9.fsf@agentultra.com> Steven D'Aprano writes: > On Fri, 11 Dec 2009 19:20:21 -0500, Steve Holden wrote: > >> Simon Forman wrote: >> [...] >>> As far as the OP rant goes, my $0.02: bad programmers will write bad >>> code in any language, with any tool or system or environment they're >>> given. If you want to avoid bad code there's (apparently) no >>> substitute for smrt programmers who are familiar with the tools they're >>> using, not just the syntax but the underlying conceptual models as >>> well. >>> >> Hear, hear! > > That's all very well, but some languages and techniques encourage the > programmer to write bad code. That's just BS. Bad code doesn't just write itself. Programmers write bad code. And ignorance is not an excuse. Just because a language allows a programmer to write sloppy code doesn't put the language at fault for the bad code programmers write with it. Any half-way decent programmer should be cognisant of when they're writing bad code and when they're writing good code. They should be able to admit that they don't know enough about a language to be writing programs for money in it. They should be able to see anti-patterns and areas of their code that should be re-factored or re-written. The real underlying problem is the human characteristic that allows us to let ourselves believe that we're better than everyone else or more simply, better than we really are. From gagsl-py2 at yahoo.com.ar Wed Dec 16 09:35:55 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 16 Dec 2009 11:35:55 -0300 Subject: Raw string substitution problem References: <931375.44828.qm@web58902.mail.re1.yahoo.com> Message-ID: En Wed, 16 Dec 2009 11:09:32 -0300, Ed Keith escribi?: > I am having a problem when substituting a raw string. When I do the > following: > > re.sub('abc', r'a\nb\nc', '123abcdefg') > > I get > > """ > 123a > b > cdefg > """ > > what I want is > > r'123a\nb\ncdefg' From http://docs.python.org/library/re.html#re.sub re.sub(pattern, repl, string[, count]) ...repl can be a string or a function; if it is a string, any backslash escapes in it are processed. That is, \n is converted to a single newline character, \r is converted to a linefeed, and so forth. So you'll have to double your backslashes: py> re.sub('abc', r'a\\nb\\nc', '123abcdefg') '123a\\nb\\ncdefg' -- Gabriel Genellina From chris.hulan at gmail.com Wed Dec 16 09:36:35 2009 From: chris.hulan at gmail.com (Chris Hulan) Date: Wed, 16 Dec 2009 06:36:35 -0800 (PST) Subject: Raw string substitution problem References: Message-ID: <7345fd13-cc85-466e-83af-6e06882c4992@u37g2000vbc.googlegroups.com> On Dec 16, 9:09?am, Ed Keith wrote: > I am having a problem when substituting a raw string. When I do the following: > > re.sub('abc', r'a\nb\nc', '123abcdefg') > > I get > > """ > 123a > b > cdefg > """ > > what I want is > > r'123a\nb\ncdefg' > > How do I get what I want? > > Thanks, > > ? ? -EdK > > Ed Keith > e_... at yahoo.com > > Blog: edkeith.blogspot.com Looks like raw strings lets you avoid having to escape slashes when specifying the literal, but doesn't preserve it during operations. changing your replacement string to r'a\\nb\\nc' seems to give the desired output cheers From gagsl-py2 at yahoo.com.ar Wed Dec 16 09:41:09 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 16 Dec 2009 06:41:09 -0800 (PST) Subject: power of explicit self? In-Reply-To: References: <73d81fbc-95c5-4897-bca1-852471eb7938@q16g2000vbc.googlegroups.com> Message-ID: <943045.190.qm@web32805.mail.mud.yahoo.com> Fire Crow : > > Nowhere, I'd say. An *implicit* self would have to be implemented > > somewhere in the compiler -- but an explicit self doesn't. It's > > homogeneous, always name-dot-attribute; the name 'self' is not special at > > all. > This is I find very interesting, If I understand your comment > correctly, > one of the advantages of implicit self is that it does not need > any special treatment, it's handled like any other name-dot-attribute. Yes. -- Gabriel Genellina Yahoo! Cocina Encontra las mejores recetas con Yahoo! Cocina. http://ar.mujer.yahoo.com/cocina/ From pianomaestro at gmail.com Wed Dec 16 09:54:30 2009 From: pianomaestro at gmail.com (simon) Date: Wed, 16 Dec 2009 06:54:30 -0800 (PST) Subject: Wrapping paper, anyone ? References: Message-ID: On Dec 16, 9:00?pm, Peter Otten <__pete... at web.de> wrote: > simon wrote: > > Nice :) > > --- stars.py ? ?2009-12-16 10:52:49.553505036 +0100 > +++ stars_fixed.py ? ? ?2009-12-16 10:53:32.545786454 +0100 > @@ -48,7 +48,9 @@ > ? ? ?def __init__(self): > ? ? ? ? ?self.calls = [] > > - ? ?__getattr__ = ScribeCall > + ? ?def __getattr__(self, name): > + ? ? ? ?return ScribeCall(self, name) > + > ? ? ?def run(self, ctx): > ? ? ? ? ?for call in self.calls: > ? ? ? ? ? ? ?#print "ctx.%s(%s)" % (call.name, ', '.join(str(x) for x in > call.args)) > > Peter Oh.. I'm on py2.5.. does this not work for you ? From pianomaestro at gmail.com Wed Dec 16 09:56:15 2009 From: pianomaestro at gmail.com (simon) Date: Wed, 16 Dec 2009 06:56:15 -0800 (PST) Subject: Wrapping paper, anyone ? References: Message-ID: On Dec 17, 12:36?am, r0g wrote: > Peter Otten wrote: > > simon wrote: > > > Nice :) > > > --- stars.py ? ?2009-12-16 10:52:49.553505036 +0100 > > +++ stars_fixed.py ? ? ?2009-12-16 10:53:32.545786454 +0100 > > @@ -48,7 +48,9 @@ > > ? ? ?def __init__(self): > > ? ? ? ? ?self.calls = [] > > > - ? ?__getattr__ = ScribeCall > > + ? ?def __getattr__(self, name): > > + ? ? ? ?return ScribeCall(self, name) > > + > > ? ? ?def run(self, ctx): > > ? ? ? ? ?for call in self.calls: > > ? ? ? ? ? ? ?#print "ctx.%s(%s)" % (call.name, ', '.join(str(x) for x in > > call.args)) > > > Peter > > Nice :) Now all I need is an A0 printer, maybe Santa will bring me one! > > Roger. I found I could wrap a CD in A4 paper... for bigger things, i might stick some A4 paper together. Wow. Who is getting the A0 gift ? From invalid at invalid.invalid Wed Dec 16 09:56:17 2009 From: invalid at invalid.invalid (Grant Edwards) Date: Wed, 16 Dec 2009 14:56:17 +0000 (UTC) Subject: power of explicit self? References: <73d81fbc-95c5-4897-bca1-852471eb7938@q16g2000vbc.googlegroups.com> Message-ID: On 2009-12-16, Gabriel Genellina wrote: > Fire Crow : > >> > Nowhere, I'd say. An *implicit* self would have to be implemented >> > somewhere in the compiler -- but an explicit self doesn't. It's >> > homogeneous, always name-dot-attribute; the name 'self' is not special at >> > all. > >> This is I find very interesting, If I understand your comment >> correctly, one of the advantages of implicit self is that it >> does not need any special treatment, it's handled like any >> other name-dot-attribute. > > Yes. I presume you both meant that is an advantage of explicit self not implicit? -- Grant Edwards grante Yow! What's the MATTER at Sid? ... Is your BEVERAGE visi.com unsatisfactory? From davea at ieee.org Wed Dec 16 10:07:52 2009 From: davea at ieee.org (Dave Angel) Date: Wed, 16 Dec 2009 10:07:52 -0500 Subject: platform module problem when frozen? In-Reply-To: <4B28D5A6.6010201@arimaz.com> References: <4B28D5A6.6010201@arimaz.com> Message-ID: <4B28F7C8.4060803@ieee.org> Gabriel Rossetti wrote: >
        Hello > everyone, > > I am having problems with the platform module when being run from a > frozen program (py2exe). It imports it fine, but it gives me the > following error : > > 'module' object does not contain attribute 'platform' when I do this : > > platform.platfom() > > Does platform have a problem with being called when in a frozen > program or does it do some stuff behind the scenes that py2exe doesn't > pickup? > > Thank you, > Gabriel > >
        > Chances are that there is another module "platform" which is being picked up instead of the one in the library. Have you tried printing platform.__file__ ?? If it's getting the wrong one, you probably have a search-order problem. DaveA From corona10 at gmail.com Wed Dec 16 10:18:13 2009 From: corona10 at gmail.com (codefly) Date: Wed, 16 Dec 2009 07:18:13 -0800 (PST) Subject: basic grammer error.. Message-ID: class codefly: def WaitFreecatz(self, hours): hours = self.hours i = 1 while i < hours: print 'i wait %s hours' %(i) i = i+1 if i == hours: print '\nhe never comes' run error// what's wrong?? From __peter__ at web.de Wed Dec 16 10:18:35 2009 From: __peter__ at web.de (Peter Otten) Date: Wed, 16 Dec 2009 16:18:35 +0100 Subject: Wrapping paper, anyone ? References: Message-ID: simon wrote: > On Dec 16, 9:00 pm, Peter Otten <__pete... at web.de> wrote: >> simon wrote: >> >> Nice :) >> >> --- stars.py 2009-12-16 10:52:49.553505036 +0100 >> +++ stars_fixed.py 2009-12-16 10:53:32.545786454 +0100 >> @@ -48,7 +48,9 @@ >> def __init__(self): >> self.calls = [] >> >> - __getattr__ = ScribeCall >> + def __getattr__(self, name): >> + return ScribeCall(self, name) >> + >> def run(self, ctx): >> for call in self.calls: >> #print "ctx.%s(%s)" % (call.name, ', '.join(str(x) for x in >> call.args)) >> >> Peter > > Oh.. I'm on py2.5.. does this not work for you ? You mean 2.4? Here's a little demo: $ cat scribecall.py class ScribeCall(object): def __init__(self, scribe, name): print "init", scribe, name def __call__(self, *args, **kw): print "call", args, kw class Scribe(object): __getattr__ = ScribeCall if __name__ == "__main__": scribe = Scribe() scribe.yadda(42) $ python2.4 scribecall.py init <__main__.Scribe object at 0x7fc87b9a1450> yadda call (42,) {} $ python2.5 scribecall.py Traceback (most recent call last): File "scribecall.py", line 12, in scribe.yadda(42) TypeError: __init__() takes exactly 3 arguments (2 given) $ python2.5 -V Python 2.5.4 $ python2.6 scribecall.py Traceback (most recent call last): File "scribecall.py", line 12, in scribe.yadda(42) TypeError: __init__() takes exactly 3 arguments (2 given) Peter From deets at nospam.web.de Wed Dec 16 10:23:35 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 16 Dec 2009 16:23:35 +0100 Subject: basic grammer error.. References: Message-ID: <7oscbnF3rorvrU1@mid.uni-berlin.de> codefly wrote: > class codefly: > > def WaitFreecatz(self, hours): > hours = self.hours > i = 1 > while i < hours: > print 'i wait %s hours' %(i) > i = i+1 > if i == hours: > print '\nhe never comes' > > > run error// what's wrong?? Next time, be so kind to tell us what the actual error *is*, will you? Because there is none for me after c'n'p-ing that code into a source-file... Diez From aioe.org at technicalbloke.com Wed Dec 16 10:26:01 2009 From: aioe.org at technicalbloke.com (r0g) Date: Wed, 16 Dec 2009 15:26:01 +0000 Subject: Object Relational Mappers are evil (a meditation) References: <06532563-3f2b-4cca-802f-34cb326e6d9f@v20g2000vbs.googlegroups.com> <16a44521-1f07-454a-ace7-9ba5d5db4b9c@y28g2000prd.googlegroups.com> <50f98a4c0910060810k3a4fa910vabc5bf51381d00f9@mail.gmail.com> <00ac7cf3$0$15654$c3e8da3@news.astraweb.com> <85hbrrxaf9.fsf@agentultra.com> Message-ID: J Kenneth King wrote: > Steven D'Aprano writes: > >> On Fri, 11 Dec 2009 19:20:21 -0500, Steve Holden wrote: >> >>> Hear, hear! >> That's all very well, but some languages and techniques encourage the >> programmer to write bad code. > > That's just BS. > > Bad code doesn't just write itself. Programmers write bad code. And > ignorance is not an excuse. > > Just because a language allows a programmer to write sloppy code doesn't > put the language at fault for the bad code programmers write with it. Okay, as long as you realize the corollary of your argument is: It is impossible for a language to encourage programmers to write good code and promote good programming practices by design. I'm not sure that's entirely true either. I think python's "one way to do something" design philosophy goes some way toward that, as does Smalltalk's enforced message passing. I think PHP's superglobals and namespacing encourage bad practices (or used to back in the day), as do Basic's GOTO and Ecmascript's prototype overriding. Surely a language CAN be said to encourage kludges and sloppiness if it allows a good way and a bad way and makes the bad way much easier to implement or understand for noobs. Roger. From aioe.org at technicalbloke.com Wed Dec 16 10:27:49 2009 From: aioe.org at technicalbloke.com (r0g) Date: Wed, 16 Dec 2009 15:27:49 +0000 Subject: Wrapping paper, anyone ? References: Message-ID: simon wrote: > On Dec 17, 12:36 am, r0g wrote: >> Peter Otten wrote: >>> simon wrote: >>> Nice :) >>> --- stars.py 2009-12-16 10:52:49.553505036 +0100 >>> +++ stars_fixed.py 2009-12-16 10:53:32.545786454 +0100 >>> @@ -48,7 +48,9 @@ >>> def __init__(self): >>> self.calls = [] >>> - __getattr__ = ScribeCall >>> + def __getattr__(self, name): >>> + return ScribeCall(self, name) >>> + >>> def run(self, ctx): >>> for call in self.calls: >>> #print "ctx.%s(%s)" % (call.name, ', '.join(str(x) for x in >>> call.args)) >>> Peter >> Nice :) Now all I need is an A0 printer, maybe Santa will bring me one! >> >> Roger. > > I found I could wrap a CD in A4 paper... for bigger things, i might > stick some A4 paper together. > > Wow. Who is getting the A0 gift ? > > I was thinking of selling it, this is BSD licensed right! ;D R. From corona10 at gmail.com Wed Dec 16 10:29:34 2009 From: corona10 at gmail.com (codefly) Date: Wed, 16 Dec 2009 07:29:34 -0800 (PST) Subject: basic grammer error.. References: <7oscbnF3rorvrU1@mid.uni-berlin.de> Message-ID: <5c025e6b-9142-4979-84c1-a58a41f7a78f@g22g2000prf.googlegroups.com> On 12?17?, ??12?23?, "Diez B. Roggisch" wrote: > codefly wrote: > > class codefly: > > > def WaitFreecatz(self, hours): > > hours = self.hours > > i = 1 > > while i < hours: > > print 'i wait %s hours' %(i) > > i = i+1 > > if i == hours: > > print '\nhe never comes' > > > run error// what's wrong?? > > Next time, be so kind to tell us what the actual error *is*, will you? > > Because there is none for me after c'n'p-ing that code into a source-file... > > Diez Thank you Sir.^^ From davea at ieee.org Wed Dec 16 10:33:00 2009 From: davea at ieee.org (Dave Angel) Date: Wed, 16 Dec 2009 10:33:00 -0500 Subject: (OT) Where Are Cookies Stored? In-Reply-To: <4dc0cfea0912160530l5c7a66f0ia23ff98fbafb99e8@mail.gmail.com> References: <4dc0cfea0912150730w1d0c131agb258029b3e9a21ca@mail.gmail.com> <4dc0cfea0912160530l5c7a66f0ia23ff98fbafb99e8@mail.gmail.com> Message-ID: <4B28FDAC.5020009@ieee.org> Victor Subervi wrote: > On Tue, Dec 15, 2009 at 6:57 PM, r0g wrote: > > >> Cookies in FF for Windows are stored in an sqlite database in here... >> >> ~\Application Data\Mozilla\Firefox\Profiles\%XYZ%\firefox_profile\ >> >> > > Man, I searched C drive (the only drive) on this computer where I'm working > (Internet cafe) for "Application Data" and nuttin. > V > > How are you searching? Microsoft is so sure we don't want to see the gory details that they hide all sorts of things, by default. And especially on a public computer, you shouldn't even look with Explorer. As for searching with Explorer, there are not only design problems, but bugs as well. Get a command line, and do something like: dir /s c:\Firefox if you search directly for Application Data, you have to be sure to properly use quotes. You also need to add the /ah switch, since it's a hidden directory. So I cheat by searching for a subdirectory under it. You can also find the appdata directory by looking at the environment variable USERPROFILE, switching to that directory, and descending directly into "application data" by using the tab key. C:\>set USERPROFILE USERPROFILE=C:\Documents and Settings\davea C:\>cd "Documents and Settings\davea" C:\Documents and Settings\davea>cd "Application Data" I got the last line by typing cd app then pressing the tab key (this adds the quotes and spaces for me) Anyway, once you're in the Firefox directory, do: C:\Documents and Settings\davea\Application Data\Mozilla\Firefox>dir /s cook* and you'll see the actual file. You can also search for it from the root, but I have 13 files cookies.* and 8 cookies.sqlite Incidentally, lots of interesting stuff is in the USERPROFILE directory, so it's a good thing to know how to quickly find. Different versions of Windows put it different places, but it ends with the logged-in user name. So user-specific data is typically stored there. Some versions of Python even include a directory under it in the sys.path directory list. DaveA From gagsl-py2 at yahoo.com.ar Wed Dec 16 10:35:26 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 16 Dec 2009 12:35:26 -0300 Subject: power of explicit self? References: <73d81fbc-95c5-4897-bca1-852471eb7938@q16g2000vbc.googlegroups.com> Message-ID: En Wed, 16 Dec 2009 11:56:17 -0300, Grant Edwards escribi?: > On 2009-12-16, Gabriel Genellina wrote: >> Fire Crow : >> >>> > Nowhere, I'd say. An *implicit* self would have to be implemented >>> > somewhere in the compiler -- but an explicit self doesn't. It's >>> > homogeneous, always name-dot-attribute; the name 'self' is not >>> special at >>> > all. >> >>> This is I find very interesting, If I understand your comment >>> correctly, one of the advantages of implicit self is that it >>> does not need any special treatment, it's handled like any >>> other name-dot-attribute. >> >> Yes. > > I presume you both meant that is an advantage of explicit self > not implicit? Yes, sorry, the advantage of an *explicit* self is being homogeneous. -- Gabriel Genellina From corona10 at gmail.com Wed Dec 16 10:38:36 2009 From: corona10 at gmail.com (codefly) Date: Wed, 16 Dec 2009 07:38:36 -0800 (PST) Subject: i re-write it Message-ID: <83ca27f7-f06d-477d-add4-8c2e5346b665@k32g2000prb.googlegroups.com> error message is here.. when i type import code2 Traceback (most recent call last): File "", line 1, in File "code2.py", line 11 ~ ^ SyntaxError: invalid syntax and source code is here class codefly: def WaitFreecatz(self, hours): hours = self.hours i =1 while i < hours: print ' i wait for %s hours' %(i) i = i+1 if i ==hours: print 'he never comes' From __peter__ at web.de Wed Dec 16 10:42:09 2009 From: __peter__ at web.de (Peter Otten) Date: Wed, 16 Dec 2009 16:42:09 +0100 Subject: Subclassing RegexObject References: Message-ID: Tobias Weber wrote: > how do I subclass or at least add a method to something returned by > re.compile()? Let's see: >>> import re >>> r = re.compile("yadda") >>> class S(type(r)): pass ... Traceback (most recent call last): File "", line 1, in TypeError: Error when calling the metaclass bases type '_sre.SRE_Pattern' is not an acceptable base type So I'm afraid you can't subclass... >>> def hello(self): print "hello" ... >>> type(r).hello = hello Traceback (most recent call last): File "", line 1, in TypeError: can't set attributes of built-in/extension type '_sre.SRE_Pattern' >>> r.hello = hello Traceback (most recent call last): File "", line 1, in AttributeError: '_sre.SRE_Pattern' object has no attribute 'hello' ...nor add a method... >>> class W(object): ... def __init__(self, match): ... self._match = match ... def __getattr__(self, name): ... return getattr(self._match, name) ... hello = hello ... >>> def my_compile(*args, **kw): ... m = original_compile(*args, **kw) ... if m is not None: ... return W(m) ... >>> original_compile = re.compile >>> re.compile = my_compile >>> re.compile("yadda").hello() hello ...but alter the meaning of "something returned by re.compile()" you can. Now who would want to do that? And why? Peter From deets at nospam.web.de Wed Dec 16 10:43:48 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 16 Dec 2009 16:43:48 +0100 Subject: i re-write it References: <83ca27f7-f06d-477d-add4-8c2e5346b665@k32g2000prb.googlegroups.com> Message-ID: <7osdhkF3rj14uU1@mid.uni-berlin.de> codefly wrote: > error message is here.. > when i type import code2 > > Traceback (most recent call last): > File "", line 1, in > File "code2.py", line 11 > ~ > ^ > SyntaxError: invalid syntax > > > and source code is here No, it isn't. The above error says "line 11", but the code you show doesn't have 11 lines. >From the above error, it looks as if you have a stray "tilde"-character on the last or so line in code.py. Remove it. Diez From corona10 at gmail.com Wed Dec 16 10:47:17 2009 From: corona10 at gmail.com (codefly) Date: Wed, 16 Dec 2009 07:47:17 -0800 (PST) Subject: i re-write it References: <83ca27f7-f06d-477d-add4-8c2e5346b665@k32g2000prb.googlegroups.com> <7osdhkF3rj14uU1@mid.uni-berlin.de> Message-ID: <424db007-c872-419b-b740-79b924f3b69f@x25g2000prf.googlegroups.com> On Dec 17, 12:43?am, "Diez B. Roggisch" wrote: > codefly wrote: > > error message is here.. > > when i type import code2 > > > Traceback (most recent call last): > > ? File "", line 1, in > > ? File "code2.py", line 11 > > ? ? ~ > > ? ? ? ? ? ? ? ? ? ? ? ?^ > > SyntaxError: invalid syntax > > > and source code is here > > No, it isn't. The above error says "line 11", but the code you show doesn't > have 11 lines. > > From the above error, it looks as if you have a stray "tilde"-character on > the last or so line in code.py. Remove it. > > Diez Oh my Thanks.. From drobinow at gmail.com Wed Dec 16 10:50:28 2009 From: drobinow at gmail.com (David Robinow) Date: Wed, 16 Dec 2009 10:50:28 -0500 Subject: (OT) Where Are Cookies Stored? In-Reply-To: <4B28FDAC.5020009@ieee.org> References: <4dc0cfea0912150730w1d0c131agb258029b3e9a21ca@mail.gmail.com> <4dc0cfea0912160530l5c7a66f0ia23ff98fbafb99e8@mail.gmail.com> <4B28FDAC.5020009@ieee.org> Message-ID: <4eb0089f0912160750s2cff1ddem869e7a711f1de2da@mail.gmail.com> On Wed, Dec 16, 2009 at 10:33 AM, Dave Angel wrote: > You can also find the appdata directory by looking at the environment > variable USERPROFILE, switching to that directory, and descending directly > into "application data" by using the tab key. > ... Lots of good advice. I'd just point out that there's an APPDATA environment variable, which is usually but not necessarily the "Application Data" directory under USERPROFILE. From corona10 at gmail.com Wed Dec 16 10:50:53 2009 From: corona10 at gmail.com (codefly) Date: Wed, 16 Dec 2009 07:50:53 -0800 (PST) Subject: i re-write it References: <83ca27f7-f06d-477d-add4-8c2e5346b665@k32g2000prb.googlegroups.com> <7osdhkF3rj14uU1@mid.uni-berlin.de> Message-ID: <0786169d-47aa-46b2-8cfb-56e90fb0127e@z4g2000prh.googlegroups.com> On Dec 17, 12:43?am, "Diez B. Roggisch" wrote: > codefly wrote: > > error message is here.. > > when i type import code2 > > > Traceback (most recent call last): > > ? File "", line 1, in > > ? File "code2.py", line 11 > > ? ? ~ > > ? ? ? ? ? ? ? ? ? ? ? ?^ > > SyntaxError: invalid syntax > > > and source code is here > > No, it isn't. The above error says "line 11", but the code you show doesn't > have 11 lines. > > From the above error, it looks as if you have a stray "tilde"-character on > the last or so line in code.py. Remove it. > > Diez now.. another problem.. when i type me = code2() the error is here.. Traceback (most recent call last): File "", line 1, in TypeError: 'module' object is not callable From victorsubervi at gmail.com Wed Dec 16 10:51:25 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Wed, 16 Dec 2009 11:51:25 -0400 Subject: (OT) Where Are Cookies Stored? In-Reply-To: <4B28FDAC.5020009@ieee.org> References: <4dc0cfea0912150730w1d0c131agb258029b3e9a21ca@mail.gmail.com> <4dc0cfea0912160530l5c7a66f0ia23ff98fbafb99e8@mail.gmail.com> <4B28FDAC.5020009@ieee.org> Message-ID: <4dc0cfea0912160751r50a561d8rae9a9caf1c19deb0@mail.gmail.com> On Wed, Dec 16, 2009 at 11:33 AM, Dave Angel wrote: > > > Victor Subervi wrote: > >> On Tue, Dec 15, 2009 at 6:57 PM, r0g wrote: >> >> >> >> Cookies in FF for Windows are stored in an sqlite database in here... >>> >>> ~\Application Data\Mozilla\Firefox\Profiles\%XYZ%\firefox_profile\ >>> >>> >>> >> >> Man, I searched C drive (the only drive) on this computer where I'm >> working >> (Internet cafe) for "Application Data" and nuttin. >> V >> >> >> > How are you searching? Microsoft is so sure we don't want to see the gory > details that they hide all sorts of things, by default. And especially on a > public computer, you shouldn't even look with Explorer. As for searching > with Explorer, there are not only design problems, but bugs as well. Get a > command line, and do something like: > > dir /s c:\Firefox > > if you search directly for Application Data, you have to be sure to > properly use quotes. You also need to add the /ah switch, since it's a > hidden directory. So I cheat by searching for a subdirectory under it. > > You can also find the appdata directory by looking at the environment > variable USERPROFILE, switching to that directory, and descending directly > into "application data" by using the tab key. > > C:\>set USERPROFILE > USERPROFILE=C:\Documents and Settings\davea > > C:\>cd "Documents and Settings\davea" > > C:\Documents and Settings\davea>cd "Application Data" > > I got the last line by typing cd app then pressing the tab key (this > adds the quotes and spaces for me) > > Anyway, once you're in the Firefox directory, do: > > C:\Documents and Settings\davea\Application Data\Mozilla\Firefox>dir /s > cook* > > and you'll see the actual file. > > You can also search for it from the root, but I have 13 files cookies.* > and 8 cookies.sqlite > > Incidentally, lots of interesting stuff is in the USERPROFILE directory, so > it's a good thing to know how to quickly find. Different versions of > Windows put it different places, but it ends with the logged-in user name. > So user-specific data is typically stored there. Some versions of Python > even include a directory under it in the sys.path directory list. > That was great! Thanks, Dave! V -------------- next part -------------- An HTML attachment was scrubbed... URL: From corona10 at gmail.com Wed Dec 16 11:03:06 2009 From: corona10 at gmail.com (codefly) Date: Wed, 16 Dec 2009 08:03:06 -0800 (PST) Subject: another problem.. Message-ID: now.. another problem.. when i type me = code2() the error is here.. Traceback (most recent call last): File "", line 1, in TypeError: 'module' object is not callable From Eric_Dexter at msn.com Wed Dec 16 11:03:31 2009 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: Wed, 16 Dec 2009 08:03:31 -0800 (PST) Subject: I have a cross platform os.startfile but I need to asociate files with xdg-open in linux how do I do that?? Message-ID: #this should be a cross platform example of os.startfile ( startfile ) #for windows and linux. this is the first version and #linux, mac, other os's commands for exceptions to the #rule would be appreciated. at some point this will be #in the dex tracker project. import os import subprocess def startfile(filename) try: os.startfile(filename) except: subprocess.Popen(['xdg-open', filename]) _______________________________ http://dextracker.blogspot.com/ From paulo.jpinto at gmail.com Wed Dec 16 11:07:30 2009 From: paulo.jpinto at gmail.com (paulo.jpinto at gmail.com) Date: Wed, 16 Dec 2009 08:07:30 -0800 (PST) Subject: Python Imaging Library status Message-ID: <7125750d-f3d0-490c-be21-b475ef685f21@m11g2000vbo.googlegroups.com> Hi guys, is the famous PIL now a dead project? Latest available download is from 2006 and I still don't see any signs of having it updated for Python 2.6 or 3.x versions. Thanks in Advance, Paulo From davea at ieee.org Wed Dec 16 11:10:43 2009 From: davea at ieee.org (Dave Angel) Date: Wed, 16 Dec 2009 11:10:43 -0500 Subject: basic grammer error.. In-Reply-To: References: Message-ID: <4B290683.6030901@ieee.org> codefly wrote: > class codefly: > > def WaitFreecatz(self, hours): > hours = self.hours > i = 1 > while i < hours: > print 'i wait %s hours' %(i) > i = i+1 > if i == hours: > print '\nhe never comes' > > > run error// what's wrong?? > > You can't get a runtime error there, because nothing instantiates the class, nor calls its method. Once you add that code, you'll find an uninitialized instance attribute, plus a couple of logic errors. So, if you actually have a question, how about stating it completely? Given a complete code sample, you run it (on what version of what computer language, on what OS), and you get some error (show complete traceback). Explain what you tried, to identify the error, and then state what has you stumped. And if you don't get a Python error, but get the wrong results, then state what you expected, and what you got. DaveA From deets at nospam.web.de Wed Dec 16 11:33:55 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 16 Dec 2009 17:33:55 +0100 Subject: i re-write it References: <83ca27f7-f06d-477d-add4-8c2e5346b665@k32g2000prb.googlegroups.com> <7osdhkF3rj14uU1@mid.uni-berlin.de> <0786169d-47aa-46b2-8cfb-56e90fb0127e@z4g2000prh.googlegroups.com> Message-ID: <7osgfjF3n9j13U1@mid.uni-berlin.de> codefly wrote: > On Dec 17, 12:43?am, "Diez B. Roggisch" wrote: >> codefly wrote: >> > error message is here.. >> > when i type import code2 >> >> > Traceback (most recent call last): >> > File "", line 1, in >> > File "code2.py", line 11 >> > ~ >> > ^ >> > SyntaxError: invalid syntax >> >> > and source code is here >> >> No, it isn't. The above error says "line 11", but the code you show >> doesn't have 11 lines. >> >> From the above error, it looks as if you have a stray "tilde"-character >> on the last or so line in code.py. Remove it. >> >> Diez > > now.. another problem.. > > when i type me = code2() > > the error is here.. > Traceback (most recent call last): > File "", line 1, in > TypeError: 'module' object is not callable Not surprisingly, because you try to instantiate a module. Which isn't possible. What you most probably want is me = code2.codefly() May I suggest you move your questions here: http://mail.python.org/mailman/listinfo/tutor It seems that you have some very basic misconceptions about python, so that might be a forum more geared towards your needs. Diez From bartc at freeuk.com Wed Dec 16 11:35:49 2009 From: bartc at freeuk.com (bartc) Date: Wed, 16 Dec 2009 16:35:49 GMT Subject: Wrapping paper, anyone ? In-Reply-To: References: Message-ID: "simon" wrote in message news:a50b1c21-287b-498d-a8c3-51a3a2f94871 at k9g2000vbl.googlegroups.com... > #!/usr/bin/env python > > from math import * > > from random import * > > import cairo > from cairo import Context What's cairo? From paul at boddie.org.uk Wed Dec 16 11:36:33 2009 From: paul at boddie.org.uk (Paul Boddie) Date: Wed, 16 Dec 2009 08:36:33 -0800 (PST) Subject: I have a cross platform os.startfile but I need to asociate files with xdg-open in linux how do I do that?? References: Message-ID: <0829f1b4-b9eb-442c-9b09-0b1c41622ca6@n13g2000vbe.googlegroups.com> On 16 Des, 17:03, "Eric_Dex... at msn.com" wrote: > #this should be a cross platform example of os.startfile ( startfile ) > #for windows and linux. ?this is the first version and > #linux, mac, other os's commands for exceptions to the > #rule would be appreciated. ?at some point this will be > #in the dex tracker project. You could look at the desktop package for something similar: http://pypi.python.org/pypi/desktop The desktop.open function supports a few extra workarounds, mostly because it pre-dates xdg-open. Paul From bruno.42.desthuilliers at websiteburo.invalid Wed Dec 16 11:36:40 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 16 Dec 2009 17:36:40 +0100 Subject: basic grammer error.. In-Reply-To: References: Message-ID: <4b290c8a$0$1187$426a74cc@news.free.fr> codefly a ?crit : > class codefly: > > def WaitFreecatz(self, hours): > hours = self.hours > i = 1 > while i < hours: > print 'i wait %s hours' %(i) > i = i+1 > if i == hours: > print '\nhe never comes' > > > run error// what's wrong?? wrt/ the code : bad capitalisation on the class name and method name, access to an inexistant attribute, useless param 'hours' (not used), failure to use the appropriate iteration construct. wrt/ your post: failure to post both the full traceback and the minimal required code to produce this traceback. From bruno.42.desthuilliers at websiteburo.invalid Wed Dec 16 11:50:37 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 16 Dec 2009 17:50:37 +0100 Subject: i re-write it In-Reply-To: <0786169d-47aa-46b2-8cfb-56e90fb0127e@z4g2000prh.googlegroups.com> References: <83ca27f7-f06d-477d-add4-8c2e5346b665@k32g2000prb.googlegroups.com> <7osdhkF3rj14uU1@mid.uni-berlin.de> <0786169d-47aa-46b2-8cfb-56e90fb0127e@z4g2000prh.googlegroups.com> Message-ID: <4b290fcf$0$8271$426a74cc@news.free.fr> codefly a ?crit : > now.. another problem.. > > when i type me = code2() where ? and what is 'code2' in this context ? Sorry, my crystal ball is out for repair... > the error is here.. > Traceback (most recent call last): > File "", line 1, in > TypeError: 'module' object is not callable > Ok, so it's in the python shell, you imported your module named 'code2', and tried to call it. Well... the error message say it all: module objects are not callable (IOW : they are not functions). If I may ask : what's your background in programming ? From davea at ieee.org Wed Dec 16 11:58:16 2009 From: davea at ieee.org (Dave Angel) Date: Wed, 16 Dec 2009 11:58:16 -0500 Subject: another problem.. In-Reply-To: References: Message-ID: <4B2911A8.6080501@ieee.org> codefly wrote: > now.. another problem.. > when i type me = code2() > the error is here.. > Traceback (most recent call last): > File "", line 1, in > TypeError: 'module' object is not callable > > By creating a new thread for each new question, you're forcing yourself to repeat the code and environment answers, which you did not. So let's ignore this thread, and I'll respond on the previous one. From davea at ieee.org Wed Dec 16 12:05:47 2009 From: davea at ieee.org (Dave Angel) Date: Wed, 16 Dec 2009 12:05:47 -0500 Subject: i re-write it In-Reply-To: <0786169d-47aa-46b2-8cfb-56e90fb0127e@z4g2000prh.googlegroups.com> References: <83ca27f7-f06d-477d-add4-8c2e5346b665@k32g2000prb.googlegroups.com> <7osdhkF3rj14uU1@mid.uni-berlin.de> <0786169d-47aa-46b2-8cfb-56e90fb0127e@z4g2000prh.googlegroups.com> Message-ID: <4B29136B.4080800@ieee.org> codefly wrote: > On Dec 17, 12:43 am, "Diez B. Roggisch" wrote: > >> codefly wrote: >> >>> error message is here.. >>> when i type import code2 >>> >>> Traceback (most recent call last): >>> File "", line 1, in >>> File "code2.py", line 11 >>> ~ >>> ^ >>> SyntaxError: invalid syntax >>> >>> and source code is here >>> >> No, it isn't. The above error says "line 11", but the code you show doesn't >> have 11 lines. >> >> From the above error, it looks as if you have a stray "tilde"-character on >> the last or so line in code.py. Remove it. >> >> Diez >> > > now.. another problem.. > > when i type me = code2() > > the error is here.. > Traceback (most recent call last): > File "", line 1, in > TypeError: 'module' object is not callable > > > Your code was/is in code2.py ----------------- class codefly: def WaitFreecatz(self, hours): hours = self.hours i =1 while i < hours: print ' i wait for %s hours' %(i) i = i+1 if i ==hours: print 'he never comes' ----------------- The message is pretty clear. Why are you trying to call the module you just imported? Perhaps you meant to instantiate the class that was defined there. In that case, the syntax would be: me = code2.codefly() To save you some trouble on your next bug, let me point out that your class does not initialize its instance variable self.hours That's normally done in the __init__() method. Also, you can interactively see the objects of an object with the dir() function. So try dir(code2) dir(code2.codefly) and dir(me) DaveA From aioe.org at technicalbloke.com Wed Dec 16 12:12:01 2009 From: aioe.org at technicalbloke.com (r0g) Date: Wed, 16 Dec 2009 17:12:01 +0000 Subject: Wrapping paper, anyone ? References: Message-ID: bartc wrote: > > "simon" wrote in message > news:a50b1c21-287b-498d-a8c3-51a3a2f94871 at k9g2000vbl.googlegroups.com... >> #!/usr/bin/env python >> >> from math import * >> >> from random import * >> >> import cairo >> from cairo import Context > > What's cairo? > > A vector graphics library. http://en.wikipedia.org/wiki/Cairo_(graphics) Roger. From gabriel.rossetti at arimaz.com Wed Dec 16 12:16:45 2009 From: gabriel.rossetti at arimaz.com (Gabriel Rossetti) Date: Wed, 16 Dec 2009 18:16:45 +0100 Subject: regex help Message-ID: <4B2915FD.9090405@arimaz.com> Hello everyone, I'm going nuts with some regex, could someone please show me what I'm doing wrong? I have an XMPP msg : 123 456 ... the node may be absent or empty (), the node may be absent. I'd like to grab everything exept the nod and create something new using regex, with the XMPP message example above I'd get this : 123 456 for some reason my regex doesn't work correctly : r"().*?().*?(?:(.*?)|)?.*?()?" I group the opening node, the opening node and if the node is present and not empty I group it and if the node is present I group it. For some reason this doesn't work correctly : >>> import re >>> s1 = "123456..." >>> s2 = "..." >>> s3 = "..." >>> s4 = "123456..." >>> s5 = "..." >>> s6 = "..." >>> exp = r"().*?().*?(?:(.*?)|)?.*?()?" >>> >>> re.match(exp, s1).groups() ("", "", '123456', None) >>> >>> re.match(exp, s2).groups() ("", "", None, None) >>> >>> re.match(exp, s3).groups() ("", "", None, None) >>> >>> re.match(exp, s4).groups() ("", "", '123456', None) >>> >>> re.match(exp, s5).groups() ("", "", None, None) >>> >>> re.match(exp, s6).groups() ("", "", None, None) >>> Does someone know what is wrong with my expression? Thank you, Gabriel From e_d_k at yahoo.com Wed Dec 16 12:19:01 2009 From: e_d_k at yahoo.com (Ed Keith) Date: Wed, 16 Dec 2009 09:19:01 -0800 (PST) Subject: Raw string substitution problem In-Reply-To: Message-ID: <250840.26825.qm@web58907.mail.re1.yahoo.com> --- On Wed, 12/16/09, Gabriel Genellina wrote: > From: Gabriel Genellina > Subject: Re: Raw string substitution problem > To: python-list at python.org > Date: Wednesday, December 16, 2009, 9:35 AM > En Wed, 16 Dec 2009 11:09:32 -0300, > Ed Keith > escribi?: > > > I am having a problem when substituting a raw string. > When I do the following: > > > > re.sub('abc', r'a\nb\nc', '123abcdefg') > > > > I get > > > > """ > > 123a > > b > > cdefg > > """ > > > > what I want is > > > > r'123a\nb\ncdefg' > > From http://docs.python.org/library/re.html#re.sub > > ??? re.sub(pattern, repl, string[, count]) > > ??? ...repl can be a string or a function; > if > ??? it is a string, any backslash escapes > in > ??? it are processed. That is, \n is > converted > ??? to a single newline character, \r is > ??? converted to a linefeed, and so forth. > > So you'll have to double your backslashes: > > py> re.sub('abc', r'a\\nb\\nc', '123abcdefg') > '123a\\nb\\ncdefg' > > --Gabriel Genellina > > --http://mail.python.org/mailman/listinfo/python-list > That is going to be a nontrivial exercise. I have control over the pattern, but the texts to be substituted and substituted into will be read from user supplied files. I need to reproduce the exact text the is read from the file. Maybe what I should do is use re to break the string into two pieces, the part before the pattern to be replaces and the part after it, then splice the replacement text in between them. Seems like doing it the hard way, but it should work. Thanks, -EdK From aioe.org at technicalbloke.com Wed Dec 16 12:22:25 2009 From: aioe.org at technicalbloke.com (r0g) Date: Wed, 16 Dec 2009 17:22:25 +0000 Subject: regex help References: Message-ID: Gabriel Rossetti wrote: > Hello everyone, > > I'm going nuts with some regex, could someone please show me what I'm > doing wrong? > > I have an XMPP msg : > > > > Does someone know what is wrong with my expression? Thank you, Gabriel Gabriel, trying to debug a long regex in situ can be a nightmare however the following technique always works for me... Use the interactive interpreter and see if half the regex works, if it does your problem is in the second half, if not it's in the first so try the first half of that and so on an so forth. You'll find the point at which it goes wrong in a snip. Non-trivial regexes are always best built up and tested a bit at a time, the interactive interpreter is great for this. Roger. From joanmg at gmail.com Wed Dec 16 12:28:25 2009 From: joanmg at gmail.com (Juanre) Date: Wed, 16 Dec 2009 09:28:25 -0800 (PST) Subject: Python tricks with applescript in OS-X References: <445d6$4b225ab5$4275d90a$24371@FUSE.NET> Message-ID: <4a840ada-ddcf-4d30-9583-fafe3c26ca8e@v7g2000vbd.googlegroups.com> Thanks for the pointers to appscript, and for the comments on the page. I have changed the examples at http://juanreyero.com/article/python/os-x-python.html to reflect them. Cheers, Juan -- http://juanreyero.com From invalid at invalid.invalid Wed Dec 16 12:30:16 2009 From: invalid at invalid.invalid (Grant Edwards) Date: Wed, 16 Dec 2009 17:30:16 +0000 (UTC) Subject: another problem.. References: Message-ID: On 2009-12-16, codefly wrote: > now.. another problem.. Sorry to be so blunt, but your main problem is that you don't know how to ask questions. Fix that, and everything else will become much easier: 1) Read this: http://catb.org/~esr/faqs/smart-questions.html 2) Read it again. 3) Read these sections one more time: http://catb.org/~esr/faqs/smart-questions.html#beprecise http://catb.org/~esr/faqs/smart-questions.html#code -- Grant Edwards grante Yow! Is it NOUVELLE at CUISINE when 3 olives are visi.com struggling with a scallop in a plate of SAUCE MORNAY? From vinay_sajip at red-dove.com Wed Dec 16 12:31:03 2009 From: vinay_sajip at red-dove.com (Vinay Sajip at Red Dove) Date: Wed, 16 Dec 2009 17:31:03 +0000 Subject: Question to logging In-Reply-To: <18692129.17761.1260967769931.JavaMail.postmaster@post.ch> References: <18692129.17761.1260967769931.JavaMail.postmaster@post.ch> Message-ID: <4B291957.80705@red-dove.com> On 16/12/2009 12:49, stefan.messerli.1 at postfinance.ch wrote: > I have the following error and no clue, how to solve that. Up to python version 2.5 the following script worked without an error, but since python 2.6. I get the following error: > > #!/usr/bin/env python > # -*- coding: ISO-8859-1 -*- > import logging > logging.getLogger().addHandler( logging.StreamHandler() ) > log = logging.getLogger() > t = "???" > print "this is printed : " + t > log.error( "this is log.error : " + t ) > > > > # running the above script with Python 2.5 > $ ./x.py > this is printed : ??? > this is log.error : ??? > > > # running the above script with Python 2.6 > $ ./x.py > this is printed : ??? > Traceback (most recent call last): > File "/var/tmp/pf-python-2.6-2.6.1-root/appl_local/python-2.6/lib/python2.6/logging/__init__.py", line 765, in emit > UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 20: ordinal not in range(128) > > > I found your answer of issue6991 in bugs.python.org, where somebody had a similar problem, but to be honest, I have no idea how to solve my problem. > > Can you please give me a tip what I have to change or where I can find more information ? > Hello Stefan, You should pass a stream to StreamHandler which has an encoding attribute set to the appropriate encoding (presumably iso-8859-1) and ensure that your stream will encode any Unicode sent to it with that encoding. For example, import codecs ENCODING = 'iso-8859-1' # or whatever writer = codecs.getwriter(ENCODING) w = writer(sys.stderr) w.encoding = ENCODING ... handler = logging.StreamHandler(w) ... In future, please ask questions like this on comp.lang.python (python-list at python.org) to give others the chance to participate in any discussion. Regards, Vinay Sajip From vinay_sajip at red-dove.com Wed Dec 16 12:31:59 2009 From: vinay_sajip at red-dove.com (Vinay Sajip at Red Dove) Date: Wed, 16 Dec 2009 17:31:59 +0000 Subject: Fwd: Re: Logging question Message-ID: <4B29198F.8040006@red-dove.com> -------- Original Message -------- Subject: Re: Logging question Date: Tue, 15 Dec 2009 18:28:54 +0000 From: Vinay Sajip at Red Dove To: Yaroslav Molochko On 15/12/2009 14:29, Yaroslav Molochko wrote: > Hello Vinay Sajip, > > my name is Yaroslav, I'm trying to use your logging module, and it's > working quite good. There is one issue I've figure out: > > logging.basicConfig(filename=c_logfile, > level=logging_level, # By default logging is > in INFO mode. You can change it to DEBUG by -v variable > format="gert > :%(asctime)-10s%(msecs)d:%(levelname)s: %(message)s", > datefmt='%d%m %H%M%S.',) > > if I use it, and delete the logfile it will not create the logfile > again. Only restart of the application will do. Is there any > workaround for this? > Hello Yaroslav, Once you create a FileHandler, the file "belongs" to the logging package which assumes it has exclusive access to the file. If the file is deleted, in order to log to it again, you need to remove the existing handler, close it, open a new handler, and attach it to the root logger. For this you will have to use the other logging API functions. Please post questions like this on comp.lang.python so that others can join in the discussion. Regards, Vinay Sajip -------------- next part -------------- An HTML attachment was scrubbed... URL: From unlearned at gmail.com Wed Dec 16 12:38:42 2009 From: unlearned at gmail.com (Intchanter / Daniel Fackrell) Date: Wed, 16 Dec 2009 09:38:42 -0800 (PST) Subject: regex help References: Message-ID: <9ce63877-c9f6-42a6-9bd3-9ae53e557dfa@u8g2000prd.googlegroups.com> On Dec 16, 10:22?am, r0g wrote: > Gabriel Rossetti wrote: > > Hello everyone, > > > I'm going nuts with some regex, could someone please show me what I'm > > doing wrong? > > > I have an XMPP msg : > > > > > Does someone know what is wrong with my expression? Thank you, Gabriel > > Gabriel, trying to debug a long regex in situ can be a nightmare however > the following technique always works for me... > > Use the interactive interpreter and see if half the regex works, if it > does your problem is in the second half, if not it's in the first so try > the first half of that and so on an so forth. You'll find the point at > which it goes wrong in a snip. > > Non-trivial regexes are always best built up and tested a bit at a time, > the interactive interpreter is great for this. > > Roger. I'll just add that the "now you have two problems" quip applies here, especially when there are very good XML parsing libraries for Python that will keep you from having to reinvent the wheel for every little change. See sections 20.5 through 20.13 of the Python Documentation for several built-in options, and I'm sure there are many community projects that may fit the bill if none of those happen to. Personally, I consider regular expressions of any substantial length and complexity to be bad practice as it inhibits readability and maintainability. They are also decidedly non-Zen on at least "Readability counts" and "Sparse is better than dense". Intchanter Daniel Fackrell P.S. I'm not sure how any of these libraries are implemented yet, but I'd hope they're using a finite state machine tailored to the parsing task rather than using regexes, but even if they do the latter, having that abstracted out in a mature library with a clean interface is still a huge win. From pdlemper at earthlink.net Wed Dec 16 12:41:13 2009 From: pdlemper at earthlink.net (pdlemper at earthlink.net) Date: Wed, 16 Dec 2009 11:41:13 -0600 Subject: Apple Mac OS X 10.6 support & compatability with Python 3 ? Message-ID: I've been given a MAC AIR laptop with OS X 10.6 "Snow Leopard". On my desktop I dual boot with XP - Ubuntu and have Python on both. Unfortunately all my Python programs are written on Windows XP and I heavily rely on WConio for console I/O. Called Apple tech support. The technician had never heard of Python, ascertained the MAC AIR does not come preloaded with Python and did not know if Python 3 would run under OS X 10.6. This was "beyond" their expertise. Does anyone have experience with OS X ? Could I use WConio in a Windows emulator ? I have no experience with MACs and am debating whether to send this back before opening. Thanks. Dave WB3DWE From bieffe62 at gmail.com Wed Dec 16 12:44:47 2009 From: bieffe62 at gmail.com (Francesco Bochicchio) Date: Wed, 16 Dec 2009 09:44:47 -0800 (PST) Subject: iterators and views of lists References: <10d50933-c1e8-44a8-af35-dce39c444778@u18g2000pro.googlegroups.com> Message-ID: <33e302a5-b509-4fa1-949a-b2123116c1b5@19g2000vbq.googlegroups.com> On Dec 16, 1:58?pm, Anh Hai Trinh wrote: > > You might be interested in this library stream>. > > You can easily create arbitrary "slice", for example > > ? i = mylist >> takei(primes()) > > will return an iterator over the items of mylist with a prime number > index, given that primes() return an iterator over prime numbers. > Nice :-) I was starting to experiment data flow programming with python myself, although I'm just playing with it.. I find the idea of data flow programming fascinatin, and wonder if it can be considered a general-purpose program paradigm. Ciao ----- FB From __peter__ at web.de Wed Dec 16 12:51:08 2009 From: __peter__ at web.de (Peter Otten) Date: Wed, 16 Dec 2009 18:51:08 +0100 Subject: Raw string substitution problem References: Message-ID: Ed Keith wrote: > --- On Wed, 12/16/09, Gabriel Genellina wrote: > >> From: Gabriel Genellina >> Subject: Re: Raw string substitution problem >> To: python-list at python.org >> Date: Wednesday, December 16, 2009, 9:35 AM >> En Wed, 16 Dec 2009 11:09:32 -0300, >> Ed Keith >> escribi?: >> >> > I am having a problem when substituting a raw string. >> When I do the following: >> > >> > re.sub('abc', r'a\nb\nc', '123abcdefg') >> > >> > I get >> > >> > """ >> > 123a >> > b >> > cdefg >> > """ >> > >> > what I want is >> > >> > r'123a\nb\ncdefg' >> >> From http://docs.python.org/library/re.html#re.sub >> >> re.sub(pattern, repl, string[, count]) >> >> ...repl can be a string or a function; >> if >> it is a string, any backslash escapes >> in >> it are processed. That is, \n is >> converted >> to a single newline character, \r is >> converted to a linefeed, and so forth. >> >> So you'll have to double your backslashes: >> >> py> re.sub('abc', r'a\\nb\\nc', '123abcdefg') >> '123a\\nb\\ncdefg' >> >> --Gabriel Genellina >> >> --http://mail.python.org/mailman/listinfo/python-list >> > > That is going to be a nontrivial exercise. I have control over the > pattern, but the texts to be substituted and substituted into will be read > from user supplied files. I need to reproduce the exact text the is read > from the file. There is a helper function re.escape() that you can use to sanitize the substitution: >>> print re.sub('abc', re.escape(r'a\nb\nc'), '123abcdefg') 123a\nb\ncdefg Peter From josujugo at gmail.com Wed Dec 16 12:58:23 2009 From: josujugo at gmail.com (josu) Date: Wed, 16 Dec 2009 09:58:23 -0800 (PST) Subject: python and command shell on Windows Message-ID: <7bcb0305-ed44-4c36-acab-c5584dfae060@k9g2000vbl.googlegroups.com> Hi I am trying to execute a windows command based on a shell by mean of python. I have proven subprocess test=subprocess.Popen (['shell_command'],shell=True,stdin=PIPE,stdout=PIPE) Initally, all seems ok, but, after seconds the python shell is frozen. Does someone know alternative ways valid for windows OS? Thanks in advance josu From philip at semanchuk.com Wed Dec 16 13:08:37 2009 From: philip at semanchuk.com (Philip Semanchuk) Date: Wed, 16 Dec 2009 13:08:37 -0500 Subject: Apple Mac OS X 10.6 support & compatability with Python 3 ? In-Reply-To: References: Message-ID: <917A489F-3BDD-40E7-A128-72921E8CD890@semanchuk.com> On Dec 16, 2009, at 12:41 PM, pdlemper at earthlink.net wrote: > I've been given a MAC AIR laptop with OS X 10.6 "Snow Leopard". > On my desktop I dual boot with XP - Ubuntu and have Python on both. > Unfortunately all my Python programs are written on Windows XP and > I heavily rely on WConio for console I/O. > Called Apple tech support. The technician had never heard of Python, > ascertained the MAC AIR does not come preloaded with Python and > did not know if Python 3 would run under OS X 10.6. This was "beyond" > their expertise. Sounds like the tech you spoke to was a knucklehead. http://developer.apple.com/mac/library/documentation/Darwin/Reference/ManPages/man1/python.1.html I've read about some Python-related headaches under Snow Leopard stemming from the fact that the stock Python is 64 bit and some 3rd party extensions assume/are compiled as 32 bit. > Does anyone have experience with OS X ? Could I use WConio in a > Windows emulator ? I have no experience with MACs and am debating > whether to send this back before opening. WConio I don't know about. I'm not sure what you mean by a "Windows emulator". I run Windows XP under VirtualBox with OS X as the host, and that works fine for me. That's pretty heavy to call "emulation" though. Hope this helps at least a little Philip From rami.chowdhury at gmail.com Wed Dec 16 13:10:14 2009 From: rami.chowdhury at gmail.com (Rami Chowdhury) Date: Wed, 16 Dec 2009 10:10:14 -0800 Subject: Apple Mac OS X 10.6 support & compatability with Python 3 ? In-Reply-To: References: Message-ID: <2f79f590912161010x37d4ce21xcbb3f0dbb1dacdb2@mail.gmail.com> On Wed, Dec 16, 2009 at 09:41, wrote: > I've been given a MAC AIR laptop with OS X 10.6 "Snow Leopard". > On my desktop I dual boot with XP - Ubuntu and have Python on both. > Unfortunately all my Python programs are written on Windows XP and > I heavily rely on WConio for console I/O. > Called Apple tech support. The technician had never heard of Python, > ascertained the MAC AIR does not come preloaded with Python As far as I am aware, OS X always comes with Python. I'm not sure if 10.6 comes with Python 2.6 or 2.5, but one or the other is certainly there, unless you have some sort of stripped-down install I'm not familiar with. > Does anyone have experience with OS X ? Could I use WConio in a > Windows emulator ? I don't know much about WConio, but a quick search indicates it does for Windows what curses does for Unix-like OSes. I believe OS X is sufficiently Unix-like that curses will do the job. -- Rami Chowdhury "Never assume malice when stupidity will suffice." -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) From aioe.org at technicalbloke.com Wed Dec 16 13:19:50 2009 From: aioe.org at technicalbloke.com (r0g) Date: Wed, 16 Dec 2009 18:19:50 +0000 Subject: Apple Mac OS X 10.6 support & compatability with Python 3 ? References: Message-ID: pdlemper at earthlink.net wrote: > I've been given a MAC AIR laptop with OS X 10.6 "Snow Leopard". > On my desktop I dual boot with XP - Ubuntu and have Python on both. > Unfortunately all my Python programs are written on Windows XP and > I heavily rely on WConio for console I/O. > Called Apple tech support. The technician had never heard of Python, > ascertained the MAC AIR does not come preloaded with Python and > did not know if Python 3 would run under OS X 10.6. This was "beyond" > their expertise. > Does anyone have experience with OS X ? Could I use WConio in a > Windows emulator ? I have no experience with MACs and am debating > whether to send this back before opening. > Thanks. Dave WB3DWE Snow leopard comes with 2.6 so that shouldn't be a problem but I think you're probably going to be SOL on the Wconio front - its a windows only module AFAIK. The equivalent on *nix os's is ncurses so if you want your apps to support Windows, Linux & Mac you're probably going to have to use both. Whatever you decide to do about the above you'd be mad to send back an AIR anyway, that's a v.sleek bit of kit you've been 'given'! You can install Windows and Linux via bootcamp if you want, or run them in a VM, macs are very nearly standard PC's now anyway. I suppose if you want a desktop replacement rather than something super portable you might find some other machines more suitable but if you want to be coding on the go you'd be hard pushed to find a nicer machine - except maybe the thinkpad X300 for the removable battery and optical drive. Roger. From gagsl-py2 at yahoo.com.ar Wed Dec 16 13:21:06 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 16 Dec 2009 15:21:06 -0300 Subject: Python Imaging Library status References: <7125750d-f3d0-490c-be21-b475ef685f21@m11g2000vbo.googlegroups.com> Message-ID: En Wed, 16 Dec 2009 13:07:30 -0300, paulo.jpinto at gmail.com escribi?: > is the famous PIL now a dead project? > > Latest available download is from 2006 and I still don't see any signs > of having it updated for Python 2.6 or 3.x versions. Version 1.1.7 is in beta. Here you can find all available versions: http://effbot.org/downloads/#pil There is no official 3.x version yet, but ask in the image-SIG list. -- Gabriel Genellina From dickinsm at gmail.com Wed Dec 16 13:22:42 2009 From: dickinsm at gmail.com (Mark Dickinson) Date: Wed, 16 Dec 2009 10:22:42 -0800 (PST) Subject: Apple Mac OS X 10.6 support & compatability with Python 3 ? References: Message-ID: <6af2ed53-1852-4298-8cd6-26cc495088ec@p23g2000vbl.googlegroups.com> On Dec 16, 5:41?pm, pdlem... at earthlink.net wrote: > I've been given a MAC AIR laptop with OS X 10.6 "Snow Leopard". > On my desktop I dual boot with XP - Ubuntu and have Python on both. > Unfortunately all my Python programs are written on Windows XP and > I heavily rely on WConio for console I/O. > Called Apple tech support. The technician had never heard of Python, > ascertained the MAC AIR does not come preloaded with Python and > did not know if Python 3 would run under OS X 10.6. This was "beyond" > their expertise. Unless the MacBook Air has some sort of cut-down version of Snow Leopard (which I doubt), it'll have Python 2.5.4 and Python 2.6.1 pre-installed. You'd have to install Python 3.1 yourself if you want it, but it runs just fine on OS X 10.6 (and earlier). There may be some problems with the Python 3.1.1 version from the official download page, though, since Python 3.1.1 was released *before* Snow Leopard was. An easy way to get a working Python 3.1.1 on OS X 10.6 is to install MacPorts and then do a 'sudo port install python31'. I don't know anything about WConio. -- Mark From mensanator at aol.com Wed Dec 16 13:31:41 2009 From: mensanator at aol.com (Mensanator) Date: Wed, 16 Dec 2009 10:31:41 -0800 (PST) Subject: Apple Mac OS X 10.6 support & compatability with Python 3 ? References: Message-ID: On Dec 16, 11:41?am, pdlem... at earthlink.net wrote: > I've been given a MAC AIR laptop with OS X 10.6 "Snow Leopard". > On my desktop I dual boot with XP - Ubuntu and have Python on both. > Unfortunately all my Python programs are written on Windows XP and > I heavily rely on WConio for console I/O. > Called Apple tech support. The technician had never heard of Python, > ascertained the MAC AIR does not come preloaded with Python and > did not know if Python 3 would run under OS X 10.6. This was "beyond" > their expertise. No, it's not. Call them back and if you get that bullshit again, ask to speak to the supervisor. And then ask for his supervisor, if necessary. It probably doesn't come with 3.1, you just got ahold of an idiot. BTW, I was just looking at an iMac the other day and it had 2.3, 2.4 and 2.5 installed. Beyond their expertise indeed. > Does anyone have experience with OS X ? Could I use WConio in a > Windows emulator ? ?I have no experience with MACs and am debating > whether to send this back before opening. ? > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?Thanks. ? ? Dave WB3DWE From emile at fenx.com Wed Dec 16 13:35:53 2009 From: emile at fenx.com (Emile van Sebille) Date: Wed, 16 Dec 2009 10:35:53 -0800 Subject: Python Imaging Library status In-Reply-To: <7125750d-f3d0-490c-be21-b475ef685f21@m11g2000vbo.googlegroups.com> References: <7125750d-f3d0-490c-be21-b475ef685f21@m11g2000vbo.googlegroups.com> Message-ID: On 12/16/2009 8:07 AM paulo.jpinto at gmail.com said... > Hi guys, > > is the famous PIL now a dead project? > > Latest available download is from 2006 and I still don't see any signs > of having it updated for Python 2.6 or 3.x versions. PIL for Python 2.6 is available for download from http://www.pythonware.com/products/pil/ -- I don't know about 3.x plans... Emile From catphive at catphive.net Wed Dec 16 13:57:45 2009 From: catphive at catphive.net (Brendan Miller) Date: Wed, 16 Dec 2009 10:57:45 -0800 Subject: iterators and views of lists In-Reply-To: <87hbrrunb0.fsf@rudin.co.uk> References: <00b24b82$0$15654$c3e8da3@news.astraweb.com> <87hbrrunb0.fsf@rudin.co.uk> Message-ID: On Wed, Dec 16, 2009 at 4:16 AM, Paul Rudin wrote: > Steven D'Aprano writes: > > >> I'm sympathetic to your request for list views. I've often wanted some >> way to cleanly and neatly do this: >> >> for item in seq[1:]: >> ? ? process(item) >> >> without making an unnecessary copy of almost all of seq. >> > > I don't know how it's implemented - but presumably itertools.islice > could provide what you're asking for? > -- > http://mail.python.org/mailman/listinfo/python-list > itertools.islice returns an iterator. My main point is that in python iterators are weak and can't be used to write many types of algorithms. They only go in one direction and they can't write to the collection. Another poster mentioned a stream library that is also iterator based. Basically I'm saying that anything with iterators is pretty limited because of the interface they present. See section 6.5 here for the iterator protocol: http://docs.python.org/library/stdtypes.html Basically this is only useful for writing for loops or map/reduce operations. However, python's primary datastructures, the dynamic array (list) and hashtable (dictionary) are more powerful than that. From lutz at rmi.net Wed Dec 16 13:57:49 2009 From: lutz at rmi.net (Mark Lutz) Date: Wed, 16 Dec 2009 10:57:49 -0800 (PST) Subject: Python training in Florida, January 19-21 Message-ID: <2bb28dc9-0624-4de3-8333-4c1d913775c4@l2g2000vbg.googlegroups.com> Don't miss your chance to attend our upcoming Florida Python training class next month. This 3-day public class is being held January 19-21, in Sarasota, Florida. It is open to both individual and group enrollments. For more details on the class, as well as registration instructions, please visit the class web page: http://home.earthlink.net/~python-training/2010-public-classes.html If you are unable to attend in January, our next Sarasota class is already scheduled for April 6-8. Thanks, and we hope to see you at a Python class in sunny and warm Florida soon. --Mark Lutz at Python Training Services From bigblueswope at gmail.com Wed Dec 16 14:23:26 2009 From: bigblueswope at gmail.com (BJ Swope) Date: Wed, 16 Dec 2009 14:23:26 -0500 Subject: ftplib retrlines timeout In-Reply-To: References: Message-ID: I've had experiences with some python mail servers that time out connections if data from the socket is not sent to the application within the timeout parameter. I have seen a python app on FreeBSD that would timeout a connection after 600 seconds if freebsd did not receive at least 32 kb of data within the 600 second timeout. FreeBSD would only send from the buffer to the app if there was 32kb of data, unless TCP segments were received with the PUSH flag set which would force a flush of the network buffer. It sounds like this is the behavior Brendan is seeing. ---- Auburn fans are like slinkys... not really good for anything but they still bring a smile to your face when you push them down a flight of stairs. To argue that honorable conduct is only required against an honorable enemy degrades the Americans who must carry out the orders. -- Charles Krulak, Former Commandant of the Marine Corps 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 On Wed, Dec 16, 2009 at 7:41 AM, Brendan wrote: > On Dec 15, 6:17 pm, Jennifer wrote: > > I am writing a program that has a requirement for a timeout of > > retrlines after the connection established. I just wonder if timeout > > of ftplib.FTP('xxxx.xxx.com',username,password,timeout) will work for > > retrlines method after the connection established. Or > > socket.setdefaulttimeout will work in this case. Please let me know. > > > > What exception will be throwed if ftp.retrlines timed out. > > > > Many Thanks! > > > > - Jennifer > > I asked a similar question on here a few days ago and got no response, > however I tried a large download which timed out with the following: > Traceback (most recent call last): > File "./download_r1_neodf.py", line 167, in > result = ftp.quit() > File "/usr/local/lib/python2.6/ftplib.py", line 566, in quit > resp = self.voidcmd('QUIT') > File "/usr/local/lib/python2.6/ftplib.py", line 248, in voidcmd > return self.voidresp() > File "/usr/local/lib/python2.6/ftplib.py", line 223, in voidresp > resp = self.getresp() > File "/usr/local/lib/python2.6/ftplib.py", line 209, in getresp > resp = self.getmultiline() > File "/usr/local/lib/python2.6/ftplib.py", line 195, in getmultiline > line = self.getline() > File "/usr/local/lib/python2.6/ftplib.py", line 182, in getline > line = self.file.readline() > File "/usr/local/lib/python2.6/socket.py", line 406, in readline > data = self._sock.recv(self._rbufsize) > socket.error: [Errno 110] Connection timed out > > > BTW, if you want to use the timeout paramter, you must also use the > account parameter. Set it to ''. > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Wed Dec 16 14:23:59 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 16 Dec 2009 16:23:59 -0300 Subject: Raw string substitution problem References: Message-ID: En Wed, 16 Dec 2009 14:51:08 -0300, Peter Otten <__peter__ at web.de> escribi?: > Ed Keith wrote: > >> --- On Wed, 12/16/09, Gabriel Genellina wrote: >> >>> Ed Keith >>> escribi?: >>> >>> > I am having a problem when substituting a raw string. >>> When I do the following: >>> > >>> > re.sub('abc', r'a\nb\nc', '123abcdefg') >>> > >>> > I get >>> > >>> > """ >>> > 123a >>> > b >>> > cdefg >>> > """ >>> > >>> > what I want is >>> > >>> > r'123a\nb\ncdefg' >>> >>> So you'll have to double your backslashes: >>> >>> py> re.sub('abc', r'a\\nb\\nc', '123abcdefg') >>> '123a\\nb\\ncdefg' >>> >> That is going to be a nontrivial exercise. I have control over the >> pattern, but the texts to be substituted and substituted into will be >> read >> from user supplied files. I need to reproduce the exact text the is read >> from the file. > > There is a helper function re.escape() that you can use to sanitize the > substitution: > >>>> print re.sub('abc', re.escape(r'a\nb\nc'), '123abcdefg') > 123a\nb\ncdefg Unfortunately re.escape does much more than that: py> print re.sub('abc', re.escape(r'a.b.c'), '123abcdefg') 123a\.b\.cdefg I think the string_escape encoding is what the OP needs: py> print re.sub('abc', r'a\n(b.c)\nd'.encode("string_escape"), '123abcdefg') 123a\n(b.c)\nddefg -- Gabriel Genellina From paulo.jpinto at gmail.com Wed Dec 16 14:31:48 2009 From: paulo.jpinto at gmail.com (paulo.jpinto at gmail.com) Date: Wed, 16 Dec 2009 11:31:48 -0800 (PST) Subject: Python Imaging Library status References: <7125750d-f3d0-490c-be21-b475ef685f21@m11g2000vbo.googlegroups.com> Message-ID: <8da130c4-2ede-46a9-9bc9-90e2fb37b8e1@x15g2000vbr.googlegroups.com> On 16 Dez., 19:21, "Gabriel Genellina" wrote: > En Wed, 16 Dec 2009 13:07:30 -0300, paulo.jpi... at gmail.com ? > escribi?: > > > is the famous PIL now a dead project? > > > Latest available download is from 2006 and I still don't see any signs > > of having it updated for Python 2.6 or 3.x versions. > > Version 1.1.7 is in beta. > Here you can find all available versions:http://effbot.org/downloads/#pil > There is no official 3.x version yet, but ask in the image-SIG list. > > -- > Gabriel Genellina Thanks for the quick feedback, it is good to know that PIL is still alive. Paulo From james at agentultra.com Wed Dec 16 14:40:07 2009 From: james at agentultra.com (J Kenneth King) Date: Wed, 16 Dec 2009 14:40:07 -0500 Subject: Object Relational Mappers are evil (a meditation) References: <06532563-3f2b-4cca-802f-34cb326e6d9f@v20g2000vbs.googlegroups.com> <16a44521-1f07-454a-ace7-9ba5d5db4b9c@y28g2000prd.googlegroups.com> <50f98a4c0910060810k3a4fa910vabc5bf51381d00f9@mail.gmail.com> <00ac7cf3$0$15654$c3e8da3@news.astraweb.com> <85hbrrxaf9.fsf@agentultra.com> Message-ID: <85d42eyag8.fsf@agentultra.com> r0g writes: > J Kenneth King wrote: >> Steven D'Aprano writes: >> >>> On Fri, 11 Dec 2009 19:20:21 -0500, Steve Holden wrote: >>> > > >>>> Hear, hear! >>> That's all very well, but some languages and techniques encourage the >>> programmer to write bad code. >> >> That's just BS. >> >> Bad code doesn't just write itself. Programmers write bad code. And >> ignorance is not an excuse. >> >> Just because a language allows a programmer to write sloppy code doesn't >> put the language at fault for the bad code programmers write with it. > > > > Okay, as long as you realize the corollary of your argument is: > > It is impossible for a language to encourage programmers to write good > code and promote good programming practices by design. > > I'm not sure that's entirely true either. > > I think python's "one way to do something" design philosophy goes some > way toward that, as does Smalltalk's enforced message passing. I think > PHP's superglobals and namespacing encourage bad practices (or used to > back in the day), as do Basic's GOTO and Ecmascript's prototype > overriding. I think your corollary is slightly misleading. It would be more apt to say, "Just because a language allows a programmer to write good code doesn't mean that the language is responsible for the good code programmers write with it." It is the responsibility of the programmer to recognize the advantages and flaws of their tools. PHP doesn't encourage a programmer to be a bad programmer because it lacks name-spaces or because BASIC has GOTO statements. A bad programmer will be a bad programmer because they don't understand what makes these features distinct, useful, or damaging. The language doesn't encourage anything. It's just a medium like oil paints and canvas. A painting can be good or bad despite the medium it is constructed on. The skill of the painter is what matters. > > Surely a language CAN be said to encourage kludges and sloppiness if it > allows a good way and a bad way and makes the bad way much easier to > implement or understand for noobs. > > Roger. The programmer can be encouraged to use kludges and produce sloppy code. Whether by ignorance or inflated ego. Languages with more choice just give them more rope to hang themselves with. From __peter__ at web.de Wed Dec 16 14:54:32 2009 From: __peter__ at web.de (Peter Otten) Date: Wed, 16 Dec 2009 20:54:32 +0100 Subject: Raw string substitution problem References: Message-ID: Gabriel Genellina wrote: > En Wed, 16 Dec 2009 14:51:08 -0300, Peter Otten <__peter__ at web.de> > escribi?: > >> Ed Keith wrote: >> >>> --- On Wed, 12/16/09, Gabriel Genellina wrote: >>> >>>> Ed Keith >>>> escribi?: >>>> >>>> > I am having a problem when substituting a raw string. >>>> When I do the following: >>>> > >>>> > re.sub('abc', r'a\nb\nc', '123abcdefg') >>>> > >>>> > I get >>>> > >>>> > """ >>>> > 123a >>>> > b >>>> > cdefg >>>> > """ >>>> > >>>> > what I want is >>>> > >>>> > r'123a\nb\ncdefg' >>>> >>>> So you'll have to double your backslashes: >>>> >>>> py> re.sub('abc', r'a\\nb\\nc', '123abcdefg') >>>> '123a\\nb\\ncdefg' >>>> >>> That is going to be a nontrivial exercise. I have control over the >>> pattern, but the texts to be substituted and substituted into will be >>> read >>> from user supplied files. I need to reproduce the exact text the is read >>> from the file. >> >> There is a helper function re.escape() that you can use to sanitize the >> substitution: >> >>>>> print re.sub('abc', re.escape(r'a\nb\nc'), '123abcdefg') >> 123a\nb\ncdefg > > Unfortunately re.escape does much more than that: > > py> print re.sub('abc', re.escape(r'a.b.c'), '123abcdefg') > 123a\.b\.cdefg Sorry, I didn't think of that. > I think the string_escape encoding is what the OP needs: > > py> print re.sub('abc', r'a\n(b.c)\nd'.encode("string_escape"), > '123abcdefg') > 123a\n(b.c)\nddefg Another possibility: >>> print re.sub('abc', lambda m: r'a\nb\n.c\a', '123abcdefg') 123a\nb\n.c\adefg Peter From mrstevegross at gmail.com Wed Dec 16 15:10:38 2009 From: mrstevegross at gmail.com (mrstevegross) Date: Wed, 16 Dec 2009 12:10:38 -0800 (PST) Subject: How to create a self-destructing Tkinter dialog box? Message-ID: Ok, I would like to put together a Python/Tkinter dialog box that displays a simple message and self-destructs after N seconds. Is there a simple way to do this? Thanks, --Steve From anh.hai.trinh at gmail.com Wed Dec 16 15:38:47 2009 From: anh.hai.trinh at gmail.com (Anh Hai Trinh) Date: Wed, 16 Dec 2009 12:38:47 -0800 (PST) Subject: iterators and views of lists References: Message-ID: <89604fb4-9dfa-45f1-a3df-f676cd4353ea@x5g2000prf.googlegroups.com> On Dec 16, 2:48?pm, Brendan Miller wrote: > No, that's what I'm getting at... Most of the existing mutating > algorithms in python (sort, reverse) operate over entire collections, > not partial collections delimited by indexes... which would be really > awkward anyway. Ok it can be done! The code is here: . >>> from listagent import listagent >>> x = [22, 7, 2, -5, 8, 4] >>> listagent(x)[1:].sort() >>> x [22, -5, 2, 4, 7, 8] >>> listagent(x)[::2].reverse() >>> x [7, -5, 2, 4, 22, 8] Basically the agent refers to the original list only by "address translation", and indeed made no copy of anything whatever! I implemented Shell sort but I suppose others are possible. The implementation is incomplete, for now you cannot do slice assignment, i.e. a = listagent(x)[::-2] a[1:] = [4, 2] but it should be easy to implement, and I'm too sleepy. Peace, ----aht From neilc at norwich.edu Wed Dec 16 15:48:41 2009 From: neilc at norwich.edu (Neil Cerutti) Date: 16 Dec 2009 20:48:41 GMT Subject: Object Relational Mappers are evil (a meditation) References: <06532563-3f2b-4cca-802f-34cb326e6d9f@v20g2000vbs.googlegroups.com> <16a44521-1f07-454a-ace7-9ba5d5db4b9c@y28g2000prd.googlegroups.com> <50f98a4c0910060810k3a4fa910vabc5bf51381d00f9@mail.gmail.com> <00ac7cf3$0$15654$c3e8da3@news.astraweb.com> <85hbrrxaf9.fsf@agentultra.com> <85d42eyag8.fsf@agentultra.com> Message-ID: <7osvd9F3r79lcU1@mid.individual.net> On 2009-12-16, J Kenneth King wrote: > The language doesn't encourage anything. It's just a medium > like oil paints and canvas. A painting can be good or bad > despite the medium it is constructed on. The skill of the > painter is what matters. Technically, oil paints do encourage a certain kind of painting. They can be layered on top of old paint easily, and they dry slowly, allowing you to slowly "build up" a painting in layers, and create effects with texture. If you try doing thse things with watercolors, and you'll probably be discouraged. I think a programming language does encourage a certain kind of code. Good code in one language can be poor in another. -- Neil Cerutti From Eric_Dexter at msn.com Wed Dec 16 15:52:58 2009 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: Wed, 16 Dec 2009 12:52:58 -0800 (PST) Subject: python and command shell on Windows References: <7bcb0305-ed44-4c36-acab-c5584dfae060@k9g2000vbl.googlegroups.com> Message-ID: <46aad873-9047-4461-b0df-5b755ee68b97@v7g2000vbd.googlegroups.com> On Dec 16, 11:58?am, josu wrote: > Hi > > I am trying to execute a windows command based on a shell by mean of > python. I have proven subprocess > > test=subprocess.Popen > (['shell_command'],shell=True,stdin=PIPE,stdout=PIPE) > > Initally, all seems ok, but, after seconds the python shell is frozen. > > Does someone know alternative ways valid for windows OS? > > Thanks in advance > > josu os.startfile() works you will find the pipe commands are different on unix and windows anyway. From e_d_k at yahoo.com Wed Dec 16 15:53:26 2009 From: e_d_k at yahoo.com (Ed Keith) Date: Wed, 16 Dec 2009 12:53:26 -0800 (PST) Subject: Raw string substitution problem In-Reply-To: Message-ID: <538722.28415.qm@web58907.mail.re1.yahoo.com> --- On Wed, 12/16/09, Peter Otten <__peter__ at web.de> wrote: > Another possibility: > > >>> print re.sub('abc', lambda m: r'a\nb\n.c\a', > '123abcdefg') > 123a\nb\n.c\adefg I'm not sure whether that is clever, ugly, or just plain strange! I think I'll stick with: >>> m = re.match('^(.*)abc(.*)$', '123abcdefg') >>> print m.group(1) + r'a\nb\n.c\a' + m.group(2) 123a\nb\n.c\adefg It's much less likely to fry the poor maintenance programmer's mind. -EdK Ed Keith e_d_k at yahoo.com Blog: edkeith.blogspot.com From Eric_Dexter at msn.com Wed Dec 16 16:02:20 2009 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: Wed, 16 Dec 2009 13:02:20 -0800 (PST) Subject: I have a cross platform os.startfile but I need to asociate files with xdg-open in linux how do I do that?? References: <0829f1b4-b9eb-442c-9b09-0b1c41622ca6@n13g2000vbe.googlegroups.com> Message-ID: <4fb87f04-b058-45a4-9c07-eceb35bdc657@f20g2000vbl.googlegroups.com> On Dec 16, 10:36?am, Paul Boddie wrote: > On 16 Des, 17:03, "Eric_Dex... at msn.com" wrote: > > > #this should be a cross platform example of os.startfile ( startfile ) > > #for windows and linux. ?this is the first version and > > #linux, mac, other os's commands for exceptions to the > > #rule would be appreciated. ?at some point this will be > > #in the dex tracker project. > > You could look at the desktop package for something similar: > > http://pypi.python.org/pypi/desktop > > The desktop.open function supports a few extra workarounds, mostly > because it pre-dates xdg-open. > > Paul "Since desktop environments like KDE and GNOME provide mechanisms for running browsers and editors according to the identified type of a file or resource, just as Windows "runs" files or resources, it is appropriate to have a module which accesses these mechanisms. It is this kind of functionality that the desktop package aims to support. Note that this approach is arguably better" I am concerned this means I cant do something like associate python files with python in artistx (ubuntu). It just associates text files with editors?? It does look like a cool package and I will look into that further. From alfps at start.no Wed Dec 16 16:31:00 2009 From: alfps at start.no (Alf P. Steinbach) Date: Wed, 16 Dec 2009 22:31:00 +0100 Subject: More stuff added to ch 2 of my programming intro In-Reply-To: References: Message-ID: * Alf P. Steinbach: > * Alf P. Steinbach: >> Format: PDF >> >> >> The new stuff, section 2.7, is about programs as simulations and >> handling data, focusing on modeling things. It includes some Python >> GUI programming. The plan is to discuss containers like lists and >> dictionaries in perhaps two more subsections of 2.7, but I'm not quite >> sure about how to approach that or exactly how much to cover, since >> the intent of ch 2 is to introduce mostly general concepts and enable >> the reader to try out (more or less) interesting things. >> >> >> Cheers, >> >> - Alf >> >> PS: comments welcome! > > Well, I posted the current doc. It has a not yet quite complete section > 2.7.7 about arrays, and that will be the last subsection of the > chapter. I thought using the Josephus circle problem as example was > pretty neat... :-) > > But anyway, comments welcome, even if that last section's not yet finished. Well, what's a programming introduction without Lena S?derberg and Blaise Pascal -- the beauty & the beast? :-) So I added them. Examples with some Sierpinsky triangles (from Pascal's triangle) and simple photo processing (of Lena). With Lena, Josephus and Blaise in the examples it's almost like the Good, the Bad and the Ugly... Comments very welcome. Especially, from the Python community, I'm pretty sure that there must be more Pythonic ways of copying things like my Matrix in section 2.7.7, or conventions established for that. Although Python details aren't essential -- since this is about programming and so far only about concepts, notwithstanding the photo processing not yet delving into actually technical stuff -- it would be Bad to teach very inferior ways of using the language. So, Better Ways (considering that I've endavoured to introduce only a minimal subset of the language in order to teach concepts cleanly!) would be good! Current contents listing below (it's now also as PDF on Google Docs). Cheers, - Alf Contents: 1 Getting started ... 1 1.1 Python variants, implementations and distributions. 1 1.2 Download and install a Python implementation. 2 1.3 Test-drive the Python interpreter. 2 1.4 Create and run a Python console program. 4 1.5 Syntax highlighting and programmers? editors. 6 1.6 Create and run a Python GUI program. 7 1.7 About compilation. 9 1.8 About standalone Windows programs & other kinds. 10 1.9 Browse the local documentation. 11 ? EOT ? ... 12 2 Basic concepts ... 1 2.1 Super-basic concept: why programming is not DWIM. 1 2.2 Reported errors. 4 2.2.1 Case-sensitivity. 4 2.2.2 Syntax / compilation errors. 4 2.2.3 Runtime errors / crashes. 5 2.3 A programming exploration tool: turtle graphics. 6 2.4 Naming things. 8 2.4.1 Naming actions: routines. 8 2.4.2 Naming data part I: variables. 11 2.4.3 Naming data part II: routine arguments. 13 2.5 Controlling the flow of execution. 14 2.5.1 Repeating actions automatically: loops. 14 2.5.2 Basic comparisions & boolean values. 16 2.5.3 Interlude I: a function graph program / about types. 17 2.5.4 Automated action choices. 21 2.5.5 Value-producing (function-like) routines. 23 2.5.6 Interlude II: a graph with zeroes marked / about program structure. 26 2.5.7 Dynamically nested actions: recursive routines. 28 2.6 Basic data. 36 2.6.1 Basic fundamental types / strings & concatenation. 36 2.6.2 Indexing and single characters (+ vaguely about sequences in general). 39 2.6.3 Interlude III: a ROT-13 encryption/decryption program, refactoring. 40 2.6.4 Attributes, methods, objects. 43 2.6.5 Doc strings. 44 2.6.6 Interlude IV: attribute names as strings, listing str attributes. 45 2.6.7 References & automatic garbage collection. 46 2.7 Programs as simulations / handling data. 51 2.7.1 Real system, model, user illusion. 51 2.7.2 Scopes ? global versus local variables. 53 2.7.3 Attribute collections & models with accessor and modifier routines. 57 2.7.4 Defining your own data types: classes. 63 2.7.5 Using optional and named actual arguments (Python ?keyword? arguments). 68 2.7.6 Interlude V: a GUI light switch simulation (+ about delegates and MVC). 71 2.7.7 Indexable collections (arrays). 84 ? EOT ? ... 98 From dreadpiratejeff at gmail.com Wed Dec 16 16:32:57 2009 From: dreadpiratejeff at gmail.com (J) Date: Wed, 16 Dec 2009 16:32:57 -0500 Subject: Help with parsing a list Message-ID: <36dec4ff0912161332y18233d1em8acf566ecf4356a@mail.gmail.com> Hi all, I need some help in turning a list into a dictionary... The list looks something like this: ['key1: data1','key2: data2','key3: data3',' key4: ',' \tdata4.1',' \tdata4.2',' \tdata4.3','key5: data5'] and it's derived from output (via subprocess.Popen) that in a terminal would look like this: key1: data1 key2: data2 key3: data3 key4: data4.1 data4.2 data4.3 key5: data5 So what I want to do is turn this into a dictionary that looks like this: {'key1':'data1','key2':'data2','key3':'data3','key4':['data4.1','data4.2','data4.3'],'key5':'data5'] So the problem I am having is just with the key 4 stuff... right now, I'm looking at something like this (pseudocode because I'm still trying to work this out) loop through list if item is 'flags' make flags the key add every following item until item + 1 does not start with \t partition item where item[0] is key and item[2] is value Sorry for not having actual code yet... I am still trying to work out how to handle this on paper before actually writing code. And no, it's not a homework assignment ;-) just a small part of a project I'm working on. Cheers, Jeff -- Pablo Picasso - "Computers are useless. They can only give you answers." - http://www.brainyquote.com/quotes/authors/p/pablo_picasso.html From nobody at nowhere.com Wed Dec 16 16:54:59 2009 From: nobody at nowhere.com (Nobody) Date: Wed, 16 Dec 2009 21:54:59 +0000 Subject: read text file byte by byte References: <4519638f-c62b-46f6-ba1e-619035d48036@j14g2000yqm.googlegroups.com> <00ae1204$0$15654$c3e8da3@news.astraweb.com> Message-ID: On Mon, 14 Dec 2009 21:37:33 -0300, Gabriel Genellina wrote: >> There are no file objects in 3.x. The file() function no longer >> exists. The return value from open(), will be an instance of >> _io. depending upon the mode, e.g. _io.TextIOWrapper for 'r', >> _io.BufferedReader for 'rb', _io.BufferedRandom for 'w+b', etc. >> >> http://docs.python.org/3.1/library/io.html >> >> io.IOBase.read() doesn't exist, io.RawIOBase.read(n) reads n bytes, >> io.TextIOBase.read(n) reads n characters. > > So basically this section [1] should not exist, or be completely rewritten? It should probably be changed to refer to "the file interface" or similar, rather than removed altogether. The io documentation may be unnecessary detail for many users. It would be better to provide a more general overview, with a link to the io package for those interested in the precise details. Also, removing the section on "file objects" altogether is likely to be unhelpful for people migrating from 2.x to 3.x. From binet at cern.ch Wed Dec 16 16:57:37 2009 From: binet at cern.ch (Sebastien Binet) Date: Wed, 16 Dec 2009 22:57:37 +0100 Subject: race/deadlock when creating a multiprocessing.manager instance while =?iso-8859-1?q?=09importing_a_module?= ? In-Reply-To: <200912151157.19524.binet@cern.ch> References: <52ce8fe6-7b3a-43dd-94bb-5a57ee7ad9b4@c34g2000yqn.googlegroups.com> <4B26EB0C.9060600@ieee.org> <200912151157.19524.binet@cern.ch> Message-ID: <200912162257.37589.binet@cern.ch> hi there, > On Tuesday 15 December 2009 02:49:00 Dave Angel wrote: > > Since I don't see any other responses, I'll give my guess, even though > > I'm not very experienced with the multiprocessing module. > > > > It's my understanding that threads may not be created or destroyed > > during an import. So you need to find a way to defer the creation till > > the imports are done. > > yes, I figured this much and I already wrapped my module with a > ModuleFacade object which has lazy properties attributes [1]. > this solves the problem of import my module, but if the module importing my > module is itself being imported, I am back to square one. > > and my module is being used by many people. > > I guess I'd need at least a way to detect that somebody is trying to use > the lazy properties of my module facade while an import is "still active". > is there such a mechanism ? digging thru the imp.py module, I devised this simple snippet: import imp [...] if imp.lock_held(): raise RuntimeError('some crystal clear error message') thanks for the help :) cheers, sebastien. -- ######################################### # Dr. Sebastien Binet # Laboratoire de l'Accelerateur Lineaire # Universite Paris-Sud XI # Batiment 200 # 91898 Orsay ######################################### From owenzhang.chicago at gmail.com Wed Dec 16 17:01:56 2009 From: owenzhang.chicago at gmail.com (Jennifer) Date: Wed, 16 Dec 2009 14:01:56 -0800 (PST) Subject: ftplib retrlines timeout References: Message-ID: So you mean ftplib.FTP('xxxx.xxx.com',username,password,timeout) will timeout the retrlines as well, correct? Thanks. From tshrinivasan at gmail.com Wed Dec 16 17:04:32 2009 From: tshrinivasan at gmail.com (shrini) Date: Wed, 16 Dec 2009 14:04:32 -0800 (PST) Subject: webscrapping ringcentral.com using mechanize Message-ID: Hi, I am trying to scrap the website 'http://service.ringcentral.com' It has a form with three input boxes. When trying to get the form with mechanize, it is throwing the following error. mechanize._mechanize.FormNotFoundError: no form matching name 'login' but, the page has the form with name "login". This form is submitted by javascript. Need your help to fill the form and login to that site using python +mechanize. My code is pasted here. http://pastebin.com/f339461b4 Thanks. Regards, Shrinivasan From mensanator at aol.com Wed Dec 16 17:41:30 2009 From: mensanator at aol.com (Mensanator) Date: Wed, 16 Dec 2009 14:41:30 -0800 (PST) Subject: More stuff added to ch 2 of my programming intro References: Message-ID: <9127dff9-90eb-4a73-aa51-e644f5e4e5bf@r1g2000vbn.googlegroups.com> On Dec 14, 1:23?am, "Alf P. Steinbach" wrote: > * Alf P. Steinbach: > > > > > > > ? Format: PDF > > ? > > > The new stuff, section 2.7, is about programs as simulations and > > handling data, focusing on modeling things. It includes some Python GUI > > programming. The plan is to discuss containers like lists and > > dictionaries in perhaps two more subsections of 2.7, but I'm not quite > > sure about how to approach that or exactly how much to cover, since the > > intent of ch 2 is to introduce mostly general concepts and enable the > > reader to try out (more or less) interesting things. > > > Cheers, > > > - Alf > > > PS: comments welcome! > > Well, I posted the current doc. It has a not yet quite complete section 2.7.7 > about arrays, and that will be the last subsection of the chapter. ?I thought > using the Josephus circle problem as example was pretty neat... :-) > > But anyway, comments welcome, even if that last section's not yet finished. > > Cheers, > > - Alf > > PS: Oh, I changed the manuscript title to "Intelligent Person's Intro to > Programming" ?-- ?is that good? Sure. After all, "Idiot's Guide to Programming" and "Programming for Dummies" are probably already taken, albeit more appropriate. From emile at fenx.com Wed Dec 16 18:05:42 2009 From: emile at fenx.com (Emile van Sebille) Date: Wed, 16 Dec 2009 15:05:42 -0800 Subject: Help with parsing a list In-Reply-To: <36dec4ff0912161332y18233d1em8acf566ecf4356a@mail.gmail.com> References: <36dec4ff0912161332y18233d1em8acf566ecf4356a@mail.gmail.com> Message-ID: On 12/16/2009 1:32 PM J said... > Hi all, > > I need some help in turning a list into a dictionary... > > The list looks something like this: > > ['key1: data1','key2: data2','key3: data3',' key4: ',' \tdata4.1',' > \tdata4.2',' \tdata4.3','key5: data5'] > > and it's derived from output (via subprocess.Popen) that in a terminal > would look like this: > > key1: data1 > key2: data2 > key3: data3 > key4: > data4.1 > data4.2 > data4.3 > key5: data5 > > So what I want to do is turn this into a dictionary that looks like this: > > {'key1':'data1','key2':'data2','key3':'data3','key4':['data4.1','data4.2','data4.3'],'key5':'data5'] Sometimes brute force works fine... >>> data = ['key1: data1','key2: data2','key3: data3',' key4: ',' \tdata4.1','\tdata4.2',' \tdata4.3','key5: data5'] >>> >>> D = {} >>> >>> for datum in data: ... parts = [ d.strip() for d in datum.split(":") ] ... if len(parts) == 2: ... if not(parts[1]): ... priorList = [] ... D[parts[0]] = priorList ... else: ... D[parts[0]] = parts[1] ... else: ... priorList.append(parts[0]) ... >>> D {'key3': 'data3', 'key2': 'data2', 'key1': 'data1', 'key5': 'data5', 'key4': ['data4.1', 'data4.2', 'data4.3']} >>> Flavor to taste, Emile > > So the problem I am having is just with the key 4 stuff... right now, > I'm looking at something like this (pseudocode because I'm still > trying to work this out) > > loop through list > if item is 'flags' > make flags the key > add every following item until item + 1 does not start with \t > partition item where item[0] is key and item[2] is value > > Sorry for not having actual code yet... I am still trying to work out > how to handle this on paper before actually writing code. > > And no, it's not a homework assignment ;-) just a small part of a > project I'm working on. > > Cheers, > > Jeff > From mensanator at aol.com Wed Dec 16 18:07:23 2009 From: mensanator at aol.com (Mensanator) Date: Wed, 16 Dec 2009 15:07:23 -0800 (PST) Subject: More stuff added to ch 2 of my programming intro References: <9127dff9-90eb-4a73-aa51-e644f5e4e5bf@r1g2000vbn.googlegroups.com> Message-ID: <88bab2c0-d27c-4081-a703-26b353b9ed71@9g2000yqa.googlegroups.com> On Dec 16, 4:41?pm, Mensanator wrote: > On Dec 14, 1:23?am, "Alf P. Steinbach" wrote: > > > > > > > * Alf P. Steinbach: > > > > ? Format: PDF > > > ? > > > > The new stuff, section 2.7, is about programs as simulations and > > > handling data, focusing on modeling things. It includes some Python GUI > > > programming. The plan is to discuss containers like lists and > > > dictionaries in perhaps two more subsections of 2.7, but I'm not quite > > > sure about how to approach that or exactly how much to cover, since the > > > intent of ch 2 is to introduce mostly general concepts and enable the > > > reader to try out (more or less) interesting things. > > > > Cheers, > > > > - Alf > > > > PS: comments welcome! > > > Well, I posted the current doc. It has a not yet quite complete section 2.7.7 > > about arrays, and that will be the last subsection of the chapter. ?I thought > > using the Josephus circle problem as example was pretty neat... :-) > > > But anyway, comments welcome, even if that last section's not yet finished. > > > Cheers, > > > - Alf > > > PS: Oh, I changed the manuscript title to "Intelligent Person's Intro to > > Programming" ?-- ?is that good? > > Sure. After all, "Idiot's Guide to Programming" and "Programming for > Dummies" are probably already taken, albeit more appropriate Oh, and about Chapter 1. If you're going to use version 3.1.1 as your standard, shouldn't you also point out that 3.1.1 is NOT bundled with Mac OS X? How about devoting a section on downloading the source files and compiling it on a Mac? From vorticitywolfe at gmail.com Wed Dec 16 18:09:32 2009 From: vorticitywolfe at gmail.com (J Wolfe) Date: Wed, 16 Dec 2009 15:09:32 -0800 (PST) Subject: frames in toplevel Tkinter Message-ID: <26b8509c-921d-484b-bab3-e318ba95a73d@21g2000yqj.googlegroups.com> Probably a stupid question, but can you have a frames in a toplevel widget? Anything I try to put in a frame goes back to the main or root widget and not the toplevel or pop-up widget. Thanks for the help! Jonathan From tjreedy at udel.edu Wed Dec 16 18:10:19 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 16 Dec 2009 18:10:19 -0500 Subject: Where is PyMethod_GET_CLASS in Python 3? In-Reply-To: References: <1799a93b-5eb8-4818-ab94-7aa4108fcea1@j24g2000yqa.googlegroups.com> Message-ID: On 12/16/2009 3:37 AM, Infinity77 wrote: > Hi, > > On Dec 15, 9:22 pm, Terry Reedy wrote: >> On 12/15/2009 11:08 AM, Infinity77 wrote: >> >>> Hi All, >> >>> When building C extensions In Python 2.X, there was a magical >>> PyMethod_GET_CLASS implemented like this: >> >>> #define PyMethod_GET_CLASS(meth) \ >>> (((PyMethodObject *)meth) -> im_class) >> >>> It looks like Python 3 has wiped out the "im_class" attribute. >> >> For bound methods, renamed to __class__ to be consistent with other >> objects. Unbound methods were eliminated as extra cruft. What I said is true at the Python level. At the C level, check the appropriate .c or .h file for the structure definition. Sorry if they are not the same. > > First of all, thank you for your answer. However, being a complete > newbie in writing C extension, I couldn't seem to find a way to do > what I asked in the first place: > > Try 1: > > # define PyMethod_GET_CLASS(meth) \ > (((PyMethodObject *)meth) -> __class__) > > error C2039: '__class__' : is not a member of 'PyMethodObject' > > Try 2: > > PyObject * magicClass = method -> __class__ > > error C2039: '__class__' : is not a member of '_object' > > > I know I am doing something stupid, please be patient :-D . Any > suggestion is more than welcome. > > Andrea. From catphive at catphive.net Wed Dec 16 18:16:57 2009 From: catphive at catphive.net (Brendan Miller) Date: Wed, 16 Dec 2009 15:16:57 -0800 Subject: iterators and views of lists In-Reply-To: <89604fb4-9dfa-45f1-a3df-f676cd4353ea@x5g2000prf.googlegroups.com> References: <89604fb4-9dfa-45f1-a3df-f676cd4353ea@x5g2000prf.googlegroups.com> Message-ID: On Wed, Dec 16, 2009 at 12:38 PM, Anh Hai Trinh wrote: > On Dec 16, 2:48?pm, Brendan Miller wrote: > >> No, that's what I'm getting at... Most of the existing mutating >> algorithms in python (sort, reverse) operate over entire collections, >> not partial collections delimited by indexes... which would be really >> awkward anyway. > > Ok it can be done! The code is here: . > > ?>>> from listagent import listagent > ?>>> x = [22, 7, 2, -5, 8, 4] > ?>>> listagent(x)[1:].sort() > ?>>> x > ?[22, -5, 2, 4, 7, 8] > ?>>> listagent(x)[::2].reverse() > ?>>> x > ?[7, -5, 2, 4, 22, 8] > > Basically the agent refers to the original list only by "address > translation", and indeed made no copy of anything whatever! I > implemented Shell sort but I suppose others are possible. > > The implementation is incomplete, for now you cannot do slice > assignment, i.e. > > ?a = listagent(x)[::-2] > ?a[1:] = [4, 2] > > but it should be easy to implement, and I'm too sleepy. Very cool, that's more or less what I was thinking of. I have a couple of thoughts: 1. Since [:] by convention already creates a copy, it might violate people's expectations if that syntax were used. 2. I'd give the listagent the mutable sequence interface, but and then make new algorithms (except sort and reverse which are required by the mutable sequence) as functions that just expect an object that mutable sequence compatible. That way the algorithm is decoupled from the datastructure, and the same code can handle both lists and listagents, or even potentially other datastructures that can expose the same interface. For instance, I was coding up some stl algorithms in python including next_permutation. So, if you wanted to make a generic next_permutation in python, you wouldn't want to make it a member of listagent, because then regular lists couldn't use it conveniently. However, if it were just a function that accepted anything that implemented mutable sequence, it could operate both over lists and over listagent without any conversion. From python at mrabarnett.plus.com Wed Dec 16 18:21:05 2009 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 16 Dec 2009 23:21:05 +0000 Subject: Help with parsing a list In-Reply-To: <36dec4ff0912161332y18233d1em8acf566ecf4356a@mail.gmail.com> References: <36dec4ff0912161332y18233d1em8acf566ecf4356a@mail.gmail.com> Message-ID: <4B296B61.8000508@mrabarnett.plus.com> J wrote: > Hi all, > > I need some help in turning a list into a dictionary... > > The list looks something like this: > > ['key1: data1','key2: data2','key3: data3',' key4: ',' \tdata4.1',' > \tdata4.2',' \tdata4.3','key5: data5'] > > and it's derived from output (via subprocess.Popen) that in a terminal > would look like this: > > key1: data1 > key2: data2 > key3: data3 > key4: > data4.1 > data4.2 > data4.3 > key5: data5 > > So what I want to do is turn this into a dictionary that looks like this: > > {'key1':'data1','key2':'data2','key3':'data3','key4':['data4.1','data4.2','data4.3'],'key5':'data5'] > > So the problem I am having is just with the key 4 stuff... right now, > I'm looking at something like this (pseudocode because I'm still > trying to work this out) > > loop through list > if item is 'flags' > make flags the key > add every following item until item + 1 does not start with \t > partition item where item[0] is key and item[2] is value > > Sorry for not having actual code yet... I am still trying to work out > how to handle this on paper before actually writing code. > > And no, it's not a homework assignment ;-) just a small part of a > project I'm working on. > Speaking personally, I'd make all of the values lists, instead of some them lists and others strings. You could split each list item into a key/value pair. Some items would have a key and an empty value, eg. ['key4', ''], some only a value, eg. ['data4.1']. If there's a key then add the key and an empty list to the dict; if there's a value then add it to the list for the key; if there's no key then use the previous key. From thunderfoot at gmail.com Wed Dec 16 18:23:41 2009 From: thunderfoot at gmail.com (thunderfoot at gmail.com) Date: Wed, 16 Dec 2009 15:23:41 -0800 (PST) Subject: Help with parsing a list References: <36dec4ff0912161332y18233d1em8acf566ecf4356a@mail.gmail.com> Message-ID: not as slick as Emile's (didn't think about using strip() ), but seemingly functional: data = ['key1: data1','key2: data2','key3: data3',' key4: ',' \tdata4.1',' \tdata4.2',' \tdata4.3','key5: data5'] result = {} for item in data: if item.endswith(': '): currkey = item[:-2] result[currkey] = [] elif item.startswith(' \t'): result[currkey].append(item[2:]) else: key, val = item.split(': ') result[key] = val print 'data = %s' % data print 'result = %s' % result >>> data = ['key1: data1', 'key2: data2', 'key3: data3', ' key4: ', ' \tdata4.1', ' \tdata4.2', ' \tdata4.3', 'key5: data5'] result = {'key3': 'data3', 'key2': 'data2', 'key1': 'data1', 'key5': 'data5', ' key4': ['data4.1', 'data4.2', 'data4.3']} >>> From alfps at start.no Wed Dec 16 18:45:18 2009 From: alfps at start.no (Alf P. Steinbach) Date: Thu, 17 Dec 2009 00:45:18 +0100 Subject: More stuff added to ch 2 of my programming intro In-Reply-To: <88bab2c0-d27c-4081-a703-26b353b9ed71@9g2000yqa.googlegroups.com> References: <9127dff9-90eb-4a73-aa51-e644f5e4e5bf@r1g2000vbn.googlegroups.com> <88bab2c0-d27c-4081-a703-26b353b9ed71@9g2000yqa.googlegroups.com> Message-ID: * Mensanator: > On Dec 16, 4:41 pm, Mensanator wrote: >> On Dec 14, 1:23 am, "Alf P. Steinbach" wrote: >> >> >> >> >> >>> * Alf P. Steinbach: >>>> Format: PDF >>>> >>>> The new stuff, section 2.7, is about programs as simulations and >>>> handling data, focusing on modeling things. It includes some Python GUI >>>> programming. The plan is to discuss containers like lists and >>>> dictionaries in perhaps two more subsections of 2.7, but I'm not quite >>>> sure about how to approach that or exactly how much to cover, since the >>>> intent of ch 2 is to introduce mostly general concepts and enable the >>>> reader to try out (more or less) interesting things. >>>> Cheers, >>>> - Alf >>>> PS: comments welcome! >>> Well, I posted the current doc. It has a not yet quite complete section 2.7.7 >>> about arrays, and that will be the last subsection of the chapter. I thought >>> using the Josephus circle problem as example was pretty neat... :-) >>> But anyway, comments welcome, even if that last section's not yet finished. >>> Cheers, >>> - Alf >>> PS: Oh, I changed the manuscript title to "Intelligent Person's Intro to >>> Programming" -- is that good? >> Sure. After all, "Idiot's Guide to Programming" and "Programming for >> Dummies" are probably already taken, albeit more appropriate > > Oh, and about Chapter 1. > > If you're going to use version 3.1.1 as your standard, shouldn't > you also point out that 3.1.1 is NOT bundled with Mac OS X? > > How about devoting a section on downloading the source files > and compiling it on a Mac? Learn to read. At the top of every second page it tells you that this is an introduction based on Windows. Cheers & hth., - Alf From greg.ewing at canterbury.ac.nz Wed Dec 16 18:48:22 2009 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Thu, 17 Dec 2009 12:48:22 +1300 Subject: Dangerous behavior of list(generator) In-Reply-To: References: <20091213143521.2549.845539319.divmod.xquotient.731@localhost.localdomain> Message-ID: <7ot99gF3rbn2gU1@mid.individual.net> exarkun at twistedmatrix.com wrote: > Which is unfortunate, because it's not that hard to get StopIteration > without explicitly raising it yourself and this behavior makes it > difficult to debug such situations. It might not be hard if you set out to do it, but in my experience it's pretty rare to end up getting a StopIteration raised accidentally in an unexpected place. -- Greg From bigblueswope at gmail.com Wed Dec 16 19:02:06 2009 From: bigblueswope at gmail.com (BJ Swope) Date: Wed, 16 Dec 2009 19:02:06 -0500 Subject: ftplib retrlines timeout In-Reply-To: References: Message-ID: If it works like I've seen other python based network apps that have app timeouts, and Brandon's post seemed to indicate that his timed out during the readline portion of the FTP transfer. ---- Auburn fans are like slinkys... not really good for anything but they still bring a smile to your face when you push them down a flight of stairs. To argue that honorable conduct is only required against an honorable enemy degrades the Americans who must carry out the orders. -- Charles Krulak, Former Commandant of the Marine Corps 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 On Wed, Dec 16, 2009 at 5:01 PM, Jennifer wrote: > So you mean ftplib.FTP('xxxx.xxx.com',username,password,timeout) will > timeout the retrlines as well, correct? Thanks. > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From greg.ewing at canterbury.ac.nz Wed Dec 16 19:23:42 2009 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Thu, 17 Dec 2009 13:23:42 +1300 Subject: Seek support for new slice syntax PEP. In-Reply-To: References: <8e5054b1-8424-4633-a52e-1d9dcd1637b6@c34g2000yqn.googlegroups.com> Message-ID: <7otbbnF3rk92qU1@mid.individual.net> Terry Reedy wrote: > So it would be > MUCH more useful if that notation created a range object. > > for i in [1:n]: ... > > So I would oppose the slice proposal in favor of a range proposal. Another possibility would be to unify range and slice objects so that they're actually the same thing. Then the same notation could be used for both purposes. -- Greg From cjwilliams43 at gmail.com Wed Dec 16 20:00:05 2009 From: cjwilliams43 at gmail.com (Colin W.) Date: Wed, 16 Dec 2009 20:00:05 -0500 Subject: Seek support for new slice syntax PEP. In-Reply-To: <7otbbnF3rk92qU1@mid.individual.net> References: <8e5054b1-8424-4633-a52e-1d9dcd1637b6@c34g2000yqn.googlegroups.com> <7otbbnF3rk92qU1@mid.individual.net> Message-ID: On 16-Dec-09 19:23 PM, Gregory Ewing wrote: > Terry Reedy wrote: >> So it would be MUCH more useful if that notation created a range object. >> >> for i in [1:n]: ... >> >> So I would oppose the slice proposal in favor of a range proposal. > > Another possibility would be to unify range and slice > objects so that they're actually the same thing. Then > the same notation could be used for both purposes. > This would be good if the increment could also be handled. Terry Reedy suggested:- for i in [1:n]: ... Are the brackets really needed? Colin W. From mensanator at aol.com Wed Dec 16 20:02:07 2009 From: mensanator at aol.com (Mensanator) Date: Wed, 16 Dec 2009 17:02:07 -0800 (PST) Subject: More stuff added to ch 2 of my programming intro References: <9127dff9-90eb-4a73-aa51-e644f5e4e5bf@r1g2000vbn.googlegroups.com> <88bab2c0-d27c-4081-a703-26b353b9ed71@9g2000yqa.googlegroups.com> Message-ID: On Dec 16, 5:45?pm, "Alf P. Steinbach" wrote: > * Mensanator: > > > > > > > On Dec 16, 4:41 pm, Mensanator wrote: > >> On Dec 14, 1:23 am, "Alf P. Steinbach" wrote: > > >>> * Alf P. Steinbach: > >>>> ? Format: PDF > >>>> ? > >>>> The new stuff, section 2.7, is about programs as simulations and > >>>> handling data, focusing on modeling things. It includes some Python GUI > >>>> programming. The plan is to discuss containers like lists and > >>>> dictionaries in perhaps two more subsections of 2.7, but I'm not quite > >>>> sure about how to approach that or exactly how much to cover, since the > >>>> intent of ch 2 is to introduce mostly general concepts and enable the > >>>> reader to try out (more or less) interesting things. > >>>> Cheers, > >>>> - Alf > >>>> PS: comments welcome! > >>> Well, I posted the current doc. It has a not yet quite complete section 2.7.7 > >>> about arrays, and that will be the last subsection of the chapter. ?I thought > >>> using the Josephus circle problem as example was pretty neat... :-) > >>> But anyway, comments welcome, even if that last section's not yet finished. > >>> Cheers, > >>> - Alf > >>> PS: Oh, I changed the manuscript title to "Intelligent Person's Intro to > >>> Programming" ?-- ?is that good? > >> Sure. After all, "Idiot's Guide to Programming" and "Programming for > >> Dummies" are probably already taken, albeit more appropriate > > > Oh, and about Chapter 1. > > > If you're going to use version 3.1.1 as your standard, shouldn't > > you also point out that 3.1.1 is NOT bundled with Mac OS X? > > > How about devoting a section on downloading the source files > > and compiling it on a Mac? > > Learn to read. > > At the top of every second page it tells you that this is an introduction based > on Windows. Still, no excuse for giving out mis-information. It's just as easy to get these things right. > > Cheers & hth., > > - Alf- Hide quoted text - > > - Show quoted text - From afriere at yahoo.co.uk Wed Dec 16 21:25:12 2009 From: afriere at yahoo.co.uk (Asun Friere) Date: Wed, 16 Dec 2009 18:25:12 -0800 (PST) Subject: Apple Mac OS X 10.6 support & compatability with Python 3 ? References: Message-ID: On Dec 17, 4:41?am, pdlem... at earthlink.net wrote: > Does anyone have experience with OS X ? Could I use WConio in a > Windows emulator ? ?I have no experience with MACs and am debating > whether to send this back before opening. You don't need an emulator per se. You can reboot a Mac into Windows using 'BootCamp' (comes with OSX, you supply the copy of XP), alternatively you can run Windows in a Virtual Machine using 3rd party software such as 'Parallels' (which I use to run Xubuntu on an iMac) or 'VMWare' which is nice because you can use multiple OSen simulatneously (and get them to talk to each other). Yes, you can have it all! From wolftracks at invalid.com Wed Dec 16 21:31:46 2009 From: wolftracks at invalid.com (W. eWatson) Date: Wed, 16 Dec 2009 18:31:46 -0800 Subject: Either IDLE Can't Start a subprocess or a firewall software firewall is blocking the connection (Win)--Battlin McAfee Message-ID: See Subject msg from Python 2.5 Win XP. It is preceded by a "Socket Error". It happened while I had a simple program displayed, and I wanted to see the shell. The msg occurred when I pressed Shell on Run from the menu. I played around for awhile, but got nowhere. Same msg. I did remove my McAfee firewall protection, and it worked once, but reverted to not working. I rebooted and the first time I could use Shell, it succeeded. After that it failed. Comments? Geeze! Mcaffe turned on the firewall again after the reboot. All seems well now. Nope. McAfee turned the firewall back on. It decided to warn me it was off, but now has allowed me to ignore the fact it is "no longer protecting me". I'll just let Win firewall do that, thank you. Nope it's back. I'll just stop here and let anyone who wants to just chime in. If I get it to stop, I'll be back. From wolftracks at invalid.com Wed Dec 16 21:41:37 2009 From: wolftracks at invalid.com (W. eWatson) Date: Wed, 16 Dec 2009 18:41:37 -0800 Subject: Using Python to Execute a C or FORTRAN Program (Windows) In-Reply-To: References: Message-ID: Mensanator wrote: > On Dec 14, 8:14?pm, "W. eWatson" wrote: >> I think Python is capable of executing a compiled C or FORTRAN program, > > Sure, if it was compiled to an .exe file. > >> and maybe even getting some parameters passed back. > > Sure, if the program prints to stdout. > >> Does anyone have a >> example of how this might be done? I'm running under Win XP Pro. > > Here's one. The test program is factor.exe (included in > the MIRACL library). I recompiled it (factor!.exe) to > produce consitent output. ... Thanks. OK, I think I can follow that. I want to pass it along to someone who either missed this possibility in some coding, ignored it, or felt more comfortable about just writing the whole program from scratch in c++. His program was originally written in Python, but a new hardware device (capture card) had no good interface with Python, so he wrote it in C++, which does. From my knowledge of the Python program before the entry of c++, it seems he could have farmed out the hardware interface in much the same way he had done it before with a capture card well know to him. Would the same Python interface work for a compiled C++ program? From nad at acm.org Wed Dec 16 21:45:31 2009 From: nad at acm.org (Ned Deily) Date: Wed, 16 Dec 2009 18:45:31 -0800 Subject: More stuff added to ch 2 of my programming intro References: <9127dff9-90eb-4a73-aa51-e644f5e4e5bf@r1g2000vbn.googlegroups.com> <88bab2c0-d27c-4081-a703-26b353b9ed71@9g2000yqa.googlegroups.com> Message-ID: In article <88bab2c0-d27c-4081-a703-26b353b9ed71 at 9g2000yqa.googlegroups.com>, Mensanator wrote: > Oh, and about Chapter 1. > > If you're going to use version 3.1.1 as your standard, shouldn't > you also point out that 3.1.1 is NOT bundled with Mac OS X? > > How about devoting a section on downloading the source files > and compiling it on a Mac? Why would you do that? http://www.python.org/download/releases/3.1.1/ http://www.python.org/ftp/python/3.1.1/python-3.1.1.dmg or (for MacPorts fans): $ sudo port install python31 -- Ned Deily, nad at acm.org From james at agentultra.com Wed Dec 16 23:17:23 2009 From: james at agentultra.com (J Kenneth King) Date: Wed, 16 Dec 2009 23:17:23 -0500 Subject: Object Relational Mappers are evil (a meditation) References: <06532563-3f2b-4cca-802f-34cb326e6d9f@v20g2000vbs.googlegroups.com> <16a44521-1f07-454a-ace7-9ba5d5db4b9c@y28g2000prd.googlegroups.com> <50f98a4c0910060810k3a4fa910vabc5bf51381d00f9@mail.gmail.com> <00ac7cf3$0$15654$c3e8da3@news.astraweb.com> <85hbrrxaf9.fsf@agentultra.com> <85d42eyag8.fsf@agentultra.com> <7osvd9F3r79lcU1@mid.individual.net> Message-ID: <858wd2xmi4.fsf@agentultra.com> Neil Cerutti writes: > On 2009-12-16, J Kenneth King wrote: >> The language doesn't encourage anything. It's just a medium >> like oil paints and canvas. A painting can be good or bad >> despite the medium it is constructed on. The skill of the >> painter is what matters. > > Technically, oil paints do encourage a certain kind of painting. > They can be layered on top of old paint easily, and they dry > slowly, allowing you to slowly "build up" a painting in layers, > and create effects with texture. If you try doing thse things > with watercolors, and you'll probably be discouraged. > > I think a programming language does encourage a certain kind of > code. Good code in one language can be poor in another. It's a weak analogy on my part, but I think I do understand what you mean here. In regards to my original point, I think I just came up with a clearer way to express it: A language is a thing. It may have syntax and semantics that bias it towards the conventions and philosophies of its designers. But in the end, a language by itself would have a hard time convincing a human being to adopt bad practises. I believe it's the fault of the programmer who adopts those poor practises. Surely their acceptance of GOTO statements and prototype-overloading are signs of their own preferences and ignorance? It suggests to me that they learnt enough of one language to get by and stopped thinking critically as soon as they sat in front of their keyboard. Throw an idiot behind a Python interpreter and it won't teach them a damn thing unless they're capable of learning it on their own. No matter how well you manage to hard code your conventions into the language. Bad code is written by bad programmers, not bad programming languages. From sturlamolden at yahoo.no Wed Dec 16 23:40:49 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Wed, 16 Dec 2009 20:40:49 -0800 (PST) Subject: Using Python to Execute a C or FORTRAN Program (Windows) References: Message-ID: <65974b45-3e9c-4a18-86a3-915cbfb3a2e8@26g2000yqo.googlegroups.com> On 17 Des, 03:41, "W. eWatson" wrote: > His program was originally written in Python, but a new > hardware device (capture card) had no good interface with Python, so he > wrote it in C++, which does. From my knowledge of the Python program > before the entry of c++, it seems he could have farmed out the hardware > interface in much the same way he had done it before with a capture card > well know to him. This sounds a bit incompetent. Why didn't he just write an extension module in C++? Also, if you don't know how to spawn a subprocess, I'd question your competence as well. From mensanator at aol.com Wed Dec 16 23:42:08 2009 From: mensanator at aol.com (Mensanator) Date: Wed, 16 Dec 2009 20:42:08 -0800 (PST) Subject: Using Python to Execute a C or FORTRAN Program (Windows) References: Message-ID: On Dec 16, 8:41?pm, "W. eWatson" wrote: > Mensanator wrote: > > On Dec 14, 8:14 pm, "W. eWatson" wrote: > >> I think Python is capable of executing a compiled C or FORTRAN program, > > > Sure, if it was compiled to an .exe file. > > >> and maybe even getting some parameters passed back. > > > Sure, if the program prints to stdout. > > >> Does anyone have a > >> example of how this might be done? I'm running under Win XP Pro. > > > Here's one. The test program is factor.exe (included in > > the MIRACL library). I recompiled it (factor!.exe) to > > produce consitent output. > > ... > Thanks. OK, I think I can follow that. I want to pass it along to > someone who either missed this possibility in some coding, ignored it, > or felt more comfortable about just writing the whole program from > scratch in c++. His program was originally written in Python, but a new > hardware device (capture card) had no good interface with Python, so he > wrote it in C++, which does. From my knowledge of the Python program > before the entry of c++, it seems he could have farmed out the hardware > interface in much the same way he had done it before with a capture card > well know to him. > > Would the same Python interface work for a compiled C++ program? If it runs from the command line and writes to stdout, I don't why it wouldn't. From tanix at mongo.net Wed Dec 16 23:59:02 2009 From: tanix at mongo.net (tanix) Date: Thu, 17 Dec 2009 04:59:02 GMT Subject: Python Goldmine has been updated: http://preciseinfo.org/Convert/index_Convert_Python.html Message-ID: Python Goldmine has been updated as of dec 15 2009. http://preciseinfo.org/Convert/index_Convert_Python.html Mirrors: http://pythongoldmine.vndv.com. From alfps at start.no Thu Dec 17 00:17:37 2009 From: alfps at start.no (Alf P. Steinbach) Date: Thu, 17 Dec 2009 06:17:37 +0100 Subject: More stuff added to ch 2 of my programming intro In-Reply-To: References: <9127dff9-90eb-4a73-aa51-e644f5e4e5bf@r1g2000vbn.googlegroups.com> <88bab2c0-d27c-4081-a703-26b353b9ed71@9g2000yqa.googlegroups.com> Message-ID: * Mensanator: > On Dec 16, 5:45 pm, "Alf P. Steinbach" wrote: >> * Mensanator: >> >> >> >> >> >>> On Dec 16, 4:41 pm, Mensanator wrote: >>>> On Dec 14, 1:23 am, "Alf P. Steinbach" wrote: >>>>> * Alf P. Steinbach: >>>>>> Format: PDF >>>>>> >>>>>> The new stuff, section 2.7, is about programs as simulations and >>>>>> handling data, focusing on modeling things. It includes some Python GUI >>>>>> programming. The plan is to discuss containers like lists and >>>>>> dictionaries in perhaps two more subsections of 2.7, but I'm not quite >>>>>> sure about how to approach that or exactly how much to cover, since the >>>>>> intent of ch 2 is to introduce mostly general concepts and enable the >>>>>> reader to try out (more or less) interesting things. >>>>>> Cheers, >>>>>> - Alf >>>>>> PS: comments welcome! >>>>> Well, I posted the current doc. It has a not yet quite complete section 2.7.7 >>>>> about arrays, and that will be the last subsection of the chapter. I thought >>>>> using the Josephus circle problem as example was pretty neat... :-) >>>>> But anyway, comments welcome, even if that last section's not yet finished. >>>>> Cheers, >>>>> - Alf >>>>> PS: Oh, I changed the manuscript title to "Intelligent Person's Intro to >>>>> Programming" -- is that good? >>>> Sure. After all, "Idiot's Guide to Programming" and "Programming for >>>> Dummies" are probably already taken, albeit more appropriate >>> Oh, and about Chapter 1. >>> If you're going to use version 3.1.1 as your standard, shouldn't >>> you also point out that 3.1.1 is NOT bundled with Mac OS X? >>> How about devoting a section on downloading the source files >>> and compiling it on a Mac? >> Learn to read. >> >> At the top of every second page it tells you that this is an introduction based >> on Windows. > > Still, no excuse for giving out mis-information. It's just as easy > to get these things right. Why are you not concrete? I'd be glad to hear of any concrete mis-information or inaccuracy; that's much of the point of asking for public feedback (did you even think about that?). Unfortunately one then also get responses from trolls, small kids, idiots, etc.. Cheers, - Alf From pianomaestro at gmail.com Thu Dec 17 01:04:34 2009 From: pianomaestro at gmail.com (simon) Date: Wed, 16 Dec 2009 22:04:34 -0800 (PST) Subject: Wrapping paper, anyone ? References: Message-ID: On Dec 17, 2:18?am, Peter Otten <__pete... at web.de> wrote: > simon wrote: > > On Dec 16, 9:00 pm, Peter Otten <__pete... at web.de> wrote: > >> simon wrote: > > >> Nice :) > > >> --- stars.py ? ?2009-12-16 10:52:49.553505036 +0100 > >> +++ stars_fixed.py ? ? ?2009-12-16 10:53:32.545786454 +0100 > >> @@ -48,7 +48,9 @@ > >> def __init__(self): > >> self.calls = [] > > >> - ? ?__getattr__ = ScribeCall > >> + ? ?def __getattr__(self, name): > >> + ? ? ? ?return ScribeCall(self, name) > >> + > >> def run(self, ctx): > >> for call in self.calls: > >> #print "ctx.%s(%s)" % (call.name, ', '.join(str(x) for x in > >> call.args)) > > >> Peter > > > Oh.. I'm on py2.5.. does this not work for you ? > > You mean 2.4? Here's a little demo: > > $ cat scribecall.py > class ScribeCall(object): > ? ? def __init__(self, scribe, name): > ? ? ? ? print "init", scribe, name > ? ? def __call__(self, *args, **kw): > ? ? ? ? print "call", args, kw > > class Scribe(object): > ? ? __getattr__ = ScribeCall > > if __name__ == "__main__": > ? ? scribe = Scribe() > ? ? scribe.yadda(42) > > $ python2.4 scribecall.py > init <__main__.Scribe object at 0x7fc87b9a1450> yadda > call (42,) {} > > $ python2.5 scribecall.py > Traceback (most recent call last): > ? File "scribecall.py", line 12, in > ? ? scribe.yadda(42) > TypeError: __init__() takes exactly 3 arguments (2 given) > > $ python2.5 -V > Python 2.5.4 > > $ python2.6 scribecall.py > Traceback (most recent call last): > ? File "scribecall.py", line 12, in > ? ? scribe.yadda(42) > TypeError: __init__() takes exactly 3 arguments (2 given) > > Peter Oh wow, it works on python 2.5.2 ! Simon. From donn.ingle at gmail.com Thu Dec 17 01:34:10 2009 From: donn.ingle at gmail.com (Donn) Date: Thu, 17 Dec 2009 08:34:10 +0200 Subject: pyZui - anyone know about this? In-Reply-To: References: <948af6e4-ab38-4d6d-a296-40bccffa7083@2g2000prl.googlegroups.com> Message-ID: <200912170834.11096.donn.ingle@gmail.com> On Wednesday 16 December 2009 09:42:14 David Roberts wrote: > PyZUI 0.1 has been released: Magic! Grabbed a tarball yesterday. \d -- \/\/ave: donn.ingle at googlewave.com home: http://otherwise.relics.co.za/ 2D vector animation : https://savannah.nongnu.org/projects/things/ Font manager : https://savannah.nongnu.org/projects/fontypython/ From tjreedy at udel.edu Thu Dec 17 01:48:11 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 17 Dec 2009 01:48:11 -0500 Subject: Either IDLE Can't Start a subprocess or a firewall software firewall is blocking the connection (Win)--Battlin McAfee In-Reply-To: References: Message-ID: On 12/16/2009 9:31 PM, W. eWatson wrote: > See Subject msg from Python 2.5 Win XP. It is preceded by a "Socket > Error". It happened while I had a simple program displayed, and I wanted > to see the shell. The msg occurred when I pressed Shell on Run from the > menu. I played around for awhile, but got nowhere. Same msg. I did > remove my McAfee firewall protection, and it worked once, but reverted > to not working. > > I rebooted and the first time I could use Shell, it succeeded. After > that it failed. Comments? Geeze! Mcaffe turned on the firewall again > after the reboot. > > All seems well now. Nope. McAfee turned the firewall back on. It decided > to warn me it was off, but now has allowed me to ignore the fact it is > "no longer protecting me". I'll just let Win firewall do that, thank you. > > Nope it's back. I'll just stop here and let anyone who wants to just > chime in. If I get it to stop, I'll be back. Works fine for me with xp and some version of McAfee, but I may have had to tell Windows Defender some years ago, as admin, to allow IDLE to run. Don't remember for sure now. From alfps at start.no Thu Dec 17 02:02:39 2009 From: alfps at start.no (Alf P. Steinbach) Date: Thu, 17 Dec 2009 08:02:39 +0100 Subject: Either IDLE Can't Start a subprocess or a firewall software firewall is blocking the connection (Win)--Battlin McAfee In-Reply-To: References: Message-ID: * W. eWatson: > See Subject msg from Python 2.5 Win XP. It is preceded by a "Socket > Error". It happened while I had a simple program displayed, and I wanted > to see the shell. The msg occurred when I pressed Shell on Run from the > menu. I played around for awhile, but got nowhere. Same msg. I did > remove my McAfee firewall protection, and it worked once, but reverted > to not working. > > I rebooted and the first time I could use Shell, it succeeded. After > that it failed. Comments? Geeze! Mcaffe turned on the firewall again > after the reboot. > > All seems well now. Nope. McAfee turned the firewall back on. It decided > to warn me it was off, but now has allowed me to ignore the fact it is > "no longer protecting me". I'll just let Win firewall do that, thank you. > > Nope it's back. I'll just stop here and let anyone who wants to just > chime in. If I get it to stop, I'll be back. I recall vaguely some similar problem caused by a program attempting to connect to localhost, and the solution then was to edit the hosts file (don't ask me for details, but perhaps that'll help you search: that problem had entirely to do with Windows' very over-zealous "security" measures). Cheers & hth., - Alf From martin.hellwig at dcuktec.org Thu Dec 17 02:09:03 2009 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Thu, 17 Dec 2009 07:09:03 +0000 Subject: How to create a self-destructing Tkinter dialog box? In-Reply-To: References: Message-ID: mrstevegross wrote: > Ok, I would like to put together a Python/Tkinter dialog box that > displays a simple message and self-destructs after N seconds. Is there > a simple way to do this? > > Thanks, > > --Steve Just, thinking aloud, I probably would do something like registering the [place|grid|pack]_forget() function by using the alarm callback 'after()' function of that frame. -- MPH http://blog.dcuktec.com 'If consumed, best digested with added seasoning to own preference.' From ensoul.magazine at gmail.com Thu Dec 17 02:10:26 2009 From: ensoul.magazine at gmail.com (Enchanter) Date: Wed, 16 Dec 2009 23:10:26 -0800 (PST) Subject: Print Options of optparse Message-ID: <6fc3a276-33a8-4891-bfb0-4b362fe5aec1@u16g2000pru.googlegroups.com> I am learning Python and uising optparse to handle command-line options. But I am not sure who to print the options' content below: ..... options, args = parser.parse_args() From rjh at see.sig.invalid Thu Dec 17 02:10:48 2009 From: rjh at see.sig.invalid (Richard Heathfield) Date: Thu, 17 Dec 2009 07:10:48 +0000 Subject: More stuff added to ch 2 of my programming intro References: Message-ID: In , Alf P. Steinbach wrote: > * Mensanator: >> On Dec 16, 5:45 pm, "Alf P. Steinbach" wrote: >>> Learn to read. >>> >>> At the top of every second page it tells you that this is an >>> introduction based on Windows. >> >> Still, no excuse for giving out mis-information. It's just as easy >> to get these things right. > > Why are you not concrete? > > I'd be glad to hear of any concrete mis-information or inaccuracy; > that's much of the point of asking for public feedback (did you even > think about that?). > > Unfortunately one then also get responses from trolls, small kids, > idiots, etc.. In my experience, mensanator doesn't usually behave trollishly. Perhaps he's just rubbing you up the wrong way accidentally. It might be worth it for both you guys to chill a little, and cut each other some slack. -- Richard Heathfield Email: -http://www. +rjh@ "Usenet is a strange place" - dmr 29 July 1999 Sig line vacant - apply within From steven at REMOVE.THIS.cybersource.com.au Thu Dec 17 02:13:54 2009 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 17 Dec 2009 07:13:54 GMT Subject: Print Options of optparse References: <6fc3a276-33a8-4891-bfb0-4b362fe5aec1@u16g2000pru.googlegroups.com> Message-ID: On Wed, 16 Dec 2009 23:10:26 -0800, Enchanter wrote: > I am learning Python and uising optparse to handle command-line options. > But I am not sure who to print the options' content below: > > ..... > > options, args = parser.parse_args() Is there a reason why print options doesn't do what you want? -- Steven From donn.ingle at gmail.com Thu Dec 17 02:14:00 2009 From: donn.ingle at gmail.com (Donn) Date: Thu, 17 Dec 2009 09:14:00 +0200 Subject: pyZui - anyone know about this? In-Reply-To: <8b6746a9-e4d9-4a47-a11b-e2fd70e61bbc@y10g2000prg.googlegroups.com> References: <8b6746a9-e4d9-4a47-a11b-e2fd70e61bbc@y10g2000prg.googlegroups.com> Message-ID: <200912170914.00705.donn.ingle@gmail.com> On Wednesday 16 December 2009 07:03:19 David Roberts wrote: > It involves scaling an image to various resolutions, and partitioning > them into fixed-size tiles. It's roughly the same technique used by > Google Maps/Earth. Thanks. That gives me something to go on. Wikipedia didn't like my search terms. > > ZUIs are useful for particular types of data - images & mapping > > especially - but I'd hate to have to navigate my desktop using its > > approach. Ever since Corel Draw in the 90's zoomed into my life I have been in love with the idea of an endless canvas that makes me feel like a satellite on a bungee cord. I think it would fit the desktop very well. Personally I see a merging of normal app windows and a zui: some kind of new window manager. If I planned it out it would look something like this: Your apps all run as they do now*, but they live on this endless plain. Perhaps it can be divided up into 'zones' or 'galaxies' or something. I would have a 'hyperspace' or 'hyperlink' or 'jump' facility (like alt-tab, I guess) to make transits from one custom-defined area to another quick. I would have a home position for the view -- like Inkscape does in terms of show all, zoom to selected, zoom to last, etc. I would have rules about traversing. Things like file-managers need some kind of static display - like the bread crumbs and up, back, home etc. Each app would only be active when 'locked-in', beyond that it's a bitmap of the last paint. You could drag apps around when you zoom out, and you can resize them at any time too. (Just imagine OOCalc in a zui! Super/Capslock and mouse wheel for scroll/pan) The other cool idea I had was to (handwavium here) graphically convey the notion of pipes and import/export between apps. Also between any nodes across the Universe of the zui. Perhaps a special 'node view' that overlays and shows all the conduits between them -- sharp where your mouse is, faded away from that so the whole thing is not too complex. Imagine the flow from Inkscape to Gimp and back. Instead of File -> Export and then File -> Import, you connect pipes along the side of each app. Inkscape, [save selected as png (properties preset)] goes to Gimp [import to layers by names (a script perhaps)] Now as you work in Inkscape and hit a hotkey, all your selected vectors are sent to Gimp which reacts as if you were there and places the new pngs into layers. This can work both ways and between multiple programs. Mix-in Blender and Scribus and Lyx and some grep and a loop or two and some imagemagick... Ah, I better stop. I can ramble on sometimes :) *I have many issues with the endless variety of re-invented wheels afa gui toolkits go. This is another whole can of shai-Hulud... I wrote some stuff about this a while back, if anyone wants to be put to sleep: http://otherwise.relics.co.za/wiki/Particles/DreamDesignApp/ :) \d -- \/\/ave: donn.ingle at googlewave.com home: http://otherwise.relics.co.za/ 2D vector animation : https://savannah.nongnu.org/projects/things/ Font manager : https://savannah.nongnu.org/projects/fontypython/ From mensanator at aol.com Thu Dec 17 02:25:24 2009 From: mensanator at aol.com (Mensanator) Date: Wed, 16 Dec 2009 23:25:24 -0800 (PST) Subject: More stuff added to ch 2 of my programming intro References: <9127dff9-90eb-4a73-aa51-e644f5e4e5bf@r1g2000vbn.googlegroups.com> <88bab2c0-d27c-4081-a703-26b353b9ed71@9g2000yqa.googlegroups.com> Message-ID: <183af5d2-e157-4cd6-bec6-8997809e1f51@d21g2000yqn.googlegroups.com> On Dec 16, 8:45?pm, Ned Deily wrote: > In article > <88bab2c0-d27c-4081-a703-26b353b9e... at 9g2000yqa.googlegroups.com>, > > ?Mensanator wrote: > > Oh, and about Chapter 1. > > > If you're going to use version 3.1.1 as your standard, shouldn't > > you also point out that 3.1.1 is NOT bundled with Mac OS X? > > > How about devoting a section on downloading the source files > > and compiling it on a Mac? > > Why would you do that? Oh, I don't know, maybe because I'm thinking about buying one and seeing 2.3, 2.4 and 2.5 directories on the model in the store made me wary. > > http://www.python.org/download/releases/3.1.1/http://www.python.org/ftp/python/3.1.1/python-3.1.1.dmg This tells me nothing. > > or (for MacPorts fans): > > $ sudo port install python31 And since I haven't got one, this also tells me nothing. > > -- > ?Ned Deily, > ?n... at acm.org From victorsubervi at gmail.com Thu Dec 17 02:26:46 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Thu, 17 Dec 2009 02:26:46 -0500 Subject: Can't Iterate Message-ID: <4dc0cfea0912162326s2e9ab2p9d33c2662d03d10b@mail.gmail.com> Hi; I have this line of code: for store in ourStores(): which is called from the statement: from particulars import ourStores The latter file has the following: def ourStores(): return ['prescriptions', 'products'] Yet, the above iteration only iterates the last of these items ('products'). Why? TIA, Victor -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Thu Dec 17 02:32:16 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Wed, 16 Dec 2009 23:32:16 -0800 Subject: Can't Iterate In-Reply-To: <4dc0cfea0912162326s2e9ab2p9d33c2662d03d10b@mail.gmail.com> References: <4dc0cfea0912162326s2e9ab2p9d33c2662d03d10b@mail.gmail.com> Message-ID: <50697b2c0912162332k7269d530jb1b93c4cb8b64547@mail.gmail.com> On Wed, Dec 16, 2009 at 11:26 PM, Victor Subervi wrote: > Hi; > I have this line of code: > > for store in ourStores(): > > which is called from the statement: > > from particulars import ourStores > > The latter file has the following: > > def ourStores(): > ? return ['prescriptions', 'products'] > > Yet, the above iteration only iterates the last of these items ('products'). > Why? To put it mildly: Unable to reproduce the problem. Post a more complete code sample. For instance, include whatever debugging code is leading you to believe that only "products" is being yielded by the iteration. Cheers, Chris -- http://blog.rebertia.com From debatem1 at gmail.com Thu Dec 17 02:40:24 2009 From: debatem1 at gmail.com (geremy condra) Date: Thu, 17 Dec 2009 02:40:24 -0500 Subject: More stuff added to ch 2 of my programming intro In-Reply-To: <183af5d2-e157-4cd6-bec6-8997809e1f51@d21g2000yqn.googlegroups.com> References: <9127dff9-90eb-4a73-aa51-e644f5e4e5bf@r1g2000vbn.googlegroups.com> <88bab2c0-d27c-4081-a703-26b353b9ed71@9g2000yqa.googlegroups.com> <183af5d2-e157-4cd6-bec6-8997809e1f51@d21g2000yqn.googlegroups.com> Message-ID: On Thu, Dec 17, 2009 at 2:25 AM, Mensanator wrote: > On Dec 16, 8:45?pm, Ned Deily wrote: >> In article >> <88bab2c0-d27c-4081-a703-26b353b9e... at 9g2000yqa.googlegroups.com>, >> >> ?Mensanator wrote: >> > Oh, and about Chapter 1. >> >> > If you're going to use version 3.1.1 as your standard, shouldn't >> > you also point out that 3.1.1 is NOT bundled with Mac OS X? >> >> > How about devoting a section on downloading the source files >> > and compiling it on a Mac? >> >> Why would you do that? > > Oh, I don't know, maybe because I'm thinking about > buying one and seeing 2.3, 2.4 and 2.5 directories > on the model in the store made me wary. > >> >> http://www.python.org/download/releases/3.1.1/http://www.python.org/ftp/python/3.1.1/python-3.1.1.dmg > > This tells me nothing. > >> >> or (for MacPorts fans): >> >> $ sudo port install python31 > > > And since I haven't got one, this also tells me nothing. He just told you what it meant, as if it weren't already obvious. Geremy Condra From ekh.johan at gmail.com Thu Dec 17 03:50:00 2009 From: ekh.johan at gmail.com (Johan Ekh) Date: Thu, 17 Dec 2009 09:50:00 +0100 Subject: Multiple python installations on opensuse? Message-ID: <417457b50912170050w610574a2m6edfb31778d22516@mail.gmail.com> Hi all, I use the finite element package ABAQUS that is partly built around python 2.4.3. ABAQUS ships with its own version of python 2.4.3 but it comes without third party libraries, e.g. numpy and scipy. In order to load these modules into ABAQUS python I must install python 2.4.3. on my opensuse laptop. How can I do this without interference with my python 2.6 installation that I use for all my non-ABAQUS python work? Best regards, Johan -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at vidr.cc Thu Dec 17 03:51:03 2009 From: d at vidr.cc (David Roberts) Date: Thu, 17 Dec 2009 00:51:03 -0800 (PST) Subject: pyZui - anyone know about this? References: <948af6e4-ab38-4d6d-a296-40bccffa7083@2g2000prl.googlegroups.com> Message-ID: > /home/fetchinson/pyzui/pyzui/tilestore.py:22: DeprecationWarning: the > sha module is deprecated; use the hashlib module instead > ? import sha Yeah, I'd noticed that. It's fixed in the repository now. On Dec 16, 10:55?pm, Daniel Fetchinson wrote: > > PyZUI 0.1 has been released: > > >http://da.vidr.cc/projects/pyzui/ > > Cool, thanks very much! > > I'm using python 2.6 these days and noticed that you use the sha > module which makes py2.6 spit out a deprecation warning: > > /home/fetchinson/pyzui/pyzui/tilestore.py:22: DeprecationWarning: the > sha module is deprecated; use the hashlib module instead > ? import sha > > It's no big deal but if you want to be future proof maybe you can > switch to hashlib for py2.6 and stay with sha for py2.5 and before (a > try/except block would suffice). > > Cheers, > Daniel > > -- > Psss, psss, put it down! -http://www.cafepress.com/putitdown From d at vidr.cc Thu Dec 17 03:54:59 2009 From: d at vidr.cc (David Roberts) Date: Thu, 17 Dec 2009 00:54:59 -0800 (PST) Subject: pyZui - anyone know about this? References: <8b6746a9-e4d9-4a47-a11b-e2fd70e61bbc@y10g2000prg.googlegroups.com> Message-ID: <8d9ea943-99b5-4180-b7e7-2b8ab9f277f5@r24g2000prf.googlegroups.com> > Personally I see a merging of normal app windows and a zui: some kind of new > window manager. Have you seen Eagle Mode[1]? [1] http://eaglemode.sourceforge.net/ On Dec 17, 5:14?pm, Donn wrote: > On Wednesday 16 December 2009 07:03:19 David Roberts wrote:> It involves scaling an image to various resolutions, and partitioning > > them into fixed-size tiles. It's roughly the same technique used by > > Google Maps/Earth. > > Thanks. That gives me something to go on. Wikipedia didn't like my search > terms. > > > > ZUIs are useful for particular types of data - images & mapping > > > especially - but I'd hate to have to navigate my desktop using its > > > approach. > > Ever since Corel Draw in the 90's zoomed into my life I have been in love with > the idea of an endless canvas that makes me feel like a satellite on a bungee > cord. I think it would fit the desktop very well. > > Personally I see a merging of normal app windows and a zui: some kind of new > window manager. > If I planned it out it would look something like this: > Your apps all run as they do now*, but they live on this endless plain. > Perhaps it can be divided up into 'zones' or 'galaxies' or something. I would > have a 'hyperspace' or 'hyperlink' or 'jump' facility (like alt-tab, I guess) > to make transits from one custom-defined area to another quick. > > I would have a home position for the view -- like Inkscape does in terms of > show all, zoom to selected, zoom to last, etc. > > I would have rules about traversing. Things like file-managers need some kind > of static display - like the bread crumbs and up, back, home etc. > > Each app would only be active when 'locked-in', beyond that it's a bitmap of > the last paint. You could drag apps around when you zoom out, and you can > resize them at any time too. > (Just imagine OOCalc in a zui! Super/Capslock and mouse wheel for scroll/pan) > > The other cool idea I had was to (handwavium here) graphically convey the > notion of pipes and import/export between apps. Also between any nodes across > the Universe of the zui. Perhaps a special 'node view' that overlays and shows > all the conduits between them -- sharp where your mouse is, faded away from > that so the whole thing is not too complex. > Imagine the flow from Inkscape to Gimp and back. Instead of File -> Export and > then File -> Import, you connect pipes along the side of each app. > Inkscape, [save selected as png (properties preset)] goes to Gimp [import to > layers by names (a script perhaps)] Now as you work in Inkscape and hit a > hotkey, all your selected vectors are sent to Gimp which reacts as if you were > there and places the new pngs into layers. > This can work both ways and between multiple programs. Mix-in Blender and > Scribus and Lyx and some grep and a loop or two and some imagemagick... > > Ah, I better stop. I can ramble on sometimes :) > > *I have many issues with the endless variety of re-invented wheels afa gui > toolkits go. This is another whole can of shai-Hulud... > > I wrote some stuff about this a while back, if anyone wants to be put to sleep:http://otherwise.relics.co.za/wiki/Particles/DreamDesignApp/ > :) > > \d > > -- > \/\/ave: donn.in... at googlewave.com > home:http://otherwise.relics.co.za/ > 2D vector animation :https://savannah.nongnu.org/projects/things/ > Font manager :https://savannah.nongnu.org/projects/fontypython/ From donn.ingle at gmail.com Thu Dec 17 04:13:02 2009 From: donn.ingle at gmail.com (Donn) Date: Thu, 17 Dec 2009 11:13:02 +0200 Subject: pyZui - anyone know about this? In-Reply-To: <8d9ea943-99b5-4180-b7e7-2b8ab9f277f5@r24g2000prf.googlegroups.com> References: <8d9ea943-99b5-4180-b7e7-2b8ab9f277f5@r24g2000prf.googlegroups.com> Message-ID: <200912171113.03039.donn.ingle@gmail.com> On Thursday 17 December 2009 10:54:59 David Roberts wrote: > Have you seen Eagle Mode[1]? > Yes. It's a strange beast. Good start I think; but addicted to zooming, to the detriment of the managing aspects I think. Still, here I sit writing no code and pontificating! \d -- \/\/ave: donn.ingle at googlewave.com home: http://otherwise.relics.co.za/ 2D vector animation : https://savannah.nongnu.org/projects/things/ Font manager : https://savannah.nongnu.org/projects/fontypython/ From nicogrubert at gmail.com Thu Dec 17 04:21:25 2009 From: nicogrubert at gmail.com (Nico Grubert) Date: Thu, 17 Dec 2009 10:21:25 +0100 Subject: ftplib timeout in Python 2.4 Message-ID: <4B29F815.1090106@gmail.com> Hi there, The ftplib has a timeout parameter in Python 2.6 and above. Is there a way to set a timeout in Python 2.4? Regards Nico From s.selvamsiva at gmail.com Thu Dec 17 05:27:44 2009 From: s.selvamsiva at gmail.com (S.Selvam) Date: Thu, 17 Dec 2009 15:57:44 +0530 Subject: webscrapping ringcentral.com using mechanize In-Reply-To: References: Message-ID: On Thu, Dec 17, 2009 at 3:34 AM, shrini wrote: > Hi, > > I am trying to scrap the website 'http://service.ringcentral.com' > > It has a form with three input boxes. > > When trying to get the form with mechanize, it is throwing the > following error. > > mechanize._mechanize.FormNotFoundError: no form matching name 'login' > > but, the page has the form with name "login". > > This form is submitted by javascript. > Though i am not sure,i think posting values via urllib could help . Also you may find it useful, http://stackoverflow.com/questions/1806238/mechanize-python-click-a-button -- Regards, S.Selvam -------------- next part -------------- An HTML attachment was scrubbed... URL: From nad at acm.org Thu Dec 17 05:33:32 2009 From: nad at acm.org (Ned Deily) Date: Thu, 17 Dec 2009 02:33:32 -0800 Subject: More stuff added to ch 2 of my programming intro References: <9127dff9-90eb-4a73-aa51-e644f5e4e5bf@r1g2000vbn.googlegroups.com> <88bab2c0-d27c-4081-a703-26b353b9ed71@9g2000yqa.googlegroups.com> <183af5d2-e157-4cd6-bec6-8997809e1f51@d21g2000yqn.googlegroups.com> Message-ID: In article <183af5d2-e157-4cd6-bec6-8997809e1f51 at d21g2000yqn.googlegroups.com>, Mensanator wrote: > Oh, I don't know, maybe because I'm thinking about > buying one and seeing 2.3, 2.4 and 2.5 directories > on the model in the store made me wary. That's odd since, AFAIK, Apple has never released an OS X with Python 2.4. Current Apple systems ship with OS X 10.6, aka Snow Leopard. 10.6 includes a Python 2.6.1 (64-bit/32-bit) and a Python 2.5.4 (32-bit only). The previous release, 10.5, shipped with 2.5 and 2.3. But, not to worry, if you need other versions, you can download OS X installers from python.org. > > http://www.python.org/download/releases/3.1.1/http://www.python.org/ftp/pyth > > on/3.1.1/python-3.1.1.dmg > > This tells me nothing. That's the disk image for the OS X Python 3.1.1 installer. Official binary installers for OS X are provided on python.org for every final Python release. > > or (for MacPorts fans): > > > > $ sudo port install python31 > > > And since I haven't got one, this also tells me nothing. http://www.macports.org/ "The MacPorts Project is an open-source community initiative to design an easy-to-use system for compiling, installing, and upgrading either command-line, X11 or Aqua based open-source software on the Mac OS X operating system." -- Ned Deily, nad at acm.org From ishwor.gurung at gmail.com Thu Dec 17 06:01:03 2009 From: ishwor.gurung at gmail.com (Ishwor Gurung) Date: Thu, 17 Dec 2009 21:31:03 +1030 Subject: Multiple python installations on opensuse? In-Reply-To: <417457b50912170050w610574a2m6edfb31778d22516@mail.gmail.com> References: <417457b50912170050w610574a2m6edfb31778d22516@mail.gmail.com> Message-ID: <34534aed0912170301t121f975bp68f94174ab79be4e@mail.gmail.com> 2009/12/17 Johan Ekh : > Hi all, > I use the finite element package ABAQUS that is partly built around python > 2.4.3. > ABAQUS ships with its own version of python 2.4.3 but it comes without third > party > libraries, e.g. numpy and scipy. In order to load these modules into ABAQUS > python > I must install python 2.4.3. on my opensuse laptop. How can I do this > without interference > with my python 2.6 installation that I use for all my non-ABAQUS python > work? Go to python.org, and download appropriate source (shjould be one for 2.4 final release). $ mkdir $HOME/my2.4build/ $ ./configure --prefix=$HOME/my2.4build && make && make install; To run- $ cd $HOME/my2.4build/bin $ ./python I am assuming you've got the C/C++ libraries installed. -- Regards, Ishwor Gurung From ishwor.gurung at gmail.com Thu Dec 17 06:27:27 2009 From: ishwor.gurung at gmail.com (Ishwor Gurung) Date: Thu, 17 Dec 2009 21:57:27 +1030 Subject: Fwd: Multiple python installations on opensuse? In-Reply-To: <417457b50912170315q741304e3l5a05b46204c1e839@mail.gmail.com> References: <417457b50912170050w610574a2m6edfb31778d22516@mail.gmail.com> <34534aed0912170249w8223eaax2bafd2181aa8ad60@mail.gmail.com> <34534aed0912170259p4603a351n17deffb878c77efc@mail.gmail.com> <417457b50912170315q741304e3l5a05b46204c1e839@mail.gmail.com> Message-ID: <34534aed0912170327v446e08an6e5043c7f1d21f43@mail.gmail.com> Scipy needs various libraries. On Ubuntu (which I use) - Depends: python (< 2.7), python (>= 2.5), python-central (>= 0.6.11), python-numpy (>= 1:1.2.0), libblas3gf | libblas.so.3gf | libatlas3gf-base, libc6 (>= 2.4), libgcc1 (>= 1:4.1.1), libgfortran3 (>= 4.3), liblapack3gf | liblapack.so.3gf | libatlas3gf-base, libstdc++6 (>= 4.1.1), libsuitesparse-3.2.0 (>= 1:3.2.0) So, doing a source/binary install similarly and then install Scipy again. ---------- Forwarded message ---------- From: Johan Ekh Date: 2009/12/17 Subject: Re: Multiple python installations on opensuse? To: Ishwor Gurung Thanks guys, I installed it as root without the --prefix option using "make altinstall" instead of "make install". It worked and I can now execute python2.4.6 with "python2.4 while python2.6 is still executed with "python". I also managed to install numpy with "python2.4 setup.py install". However, installing scipy in the same way failed with the error below. Most of my libraries appears to be in /usr/lib64/ or /usr/local/lib64 and the install script can't find them because it searched /usr/lib/ and /usr/local/lib/. How can I fix this? Sorry for newbiesh questions... //Johan == Output from "python2.4 setup.py install" Warning: No configuration returned, assuming unavailable. blas_opt_info: blas_mkl_info: ? libraries mkl,vml,guide not found in /usr/local/lib ? libraries mkl,vml,guide not found in /usr/lib ? NOT AVAILABLE atlas_blas_threads_info: Setting PTATLAS=ATLAS ? libraries ptf77blas,ptcblas,atlas not found in /usr/local/lib ? libraries ptf77blas,ptcblas,atlas not found in /usr/lib ? NOT AVAILABLE atlas_blas_info: ? libraries f77blas,cblas,atlas not found in /usr/local/lib ? libraries f77blas,cblas,atlas not found in /usr/lib ? NOT AVAILABLE /usr/local/lib/python2.4/site-packages/numpy/distutils/system_info.py:1340: UserWarning: ??? Atlas (http://math-atlas.sourceforge.net/) libraries not found. ??? Directories to search for the libraries can be specified in the ??? numpy/distutils/site.cfg file (section [atlas]) or by setting ??? the ATLAS environment variable. ? warnings.warn(AtlasNotFoundError.__doc__) blas_info: ? libraries blas not found in /usr/local/lib ? libraries blas not found in /usr/lib ? NOT AVAILABLE /usr/local/lib/python2.4/site-packages/numpy/distutils/system_info.py:1349: UserWarning: ??? Blas (http://www.netlib.org/blas/) libraries not found. ??? Directories to search for the libraries can be specified in the ??? numpy/distutils/site.cfg file (section [blas]) or by setting ??? the BLAS environment variable. ? warnings.warn(BlasNotFoundError.__doc__) blas_src_info: ? NOT AVAILABLE /usr/local/lib/python2.4/site-packages/numpy/distutils/system_info.py:1352: UserWarning: ??? Blas (http://www.netlib.org/blas/) sources not found. ??? Directories to search for the sources can be specified in the ??? numpy/distutils/site.cfg file (section [blas_src]) or by setting ??? the BLAS_SRC environment variable. ? warnings.warn(BlasSrcNotFoundError.__doc__) Traceback (most recent call last): ? File "setup.py", line 92, in ? ??? setup_package() ? File "setup.py", line 84, in setup_package ??? configuration=configuration ) ? File "/usr/local/lib/python2.4/site-packages/numpy/distutils/core.py", line 150, in setup ??? config = configuration() ? File "setup.py", line 54, in configuration ??? config.add_subpackage('scipy') ? File "/usr/local/lib/python2.4/site-packages/numpy/distutils/misc_util.py", line 851, in add_subpackage ??? caller_level = 2) ? File "/usr/local/lib/python2.4/site-packages/numpy/distutils/misc_util.py", line 834, in get_subpackage ??? caller_level = caller_level + 1) ? File "/usr/local/lib/python2.4/site-packages/numpy/distutils/misc_util.py", line 781, in _get_configuration_from_setup_py ??? config = setup_module.configuration(*args) ? File "scipy/setup.py", line 8, in configuration ??? config.add_subpackage('integrate') ? File "/usr/local/lib/python2.4/site-packages/numpy/distutils/misc_util.py", line 851, in add_subpackage ??? caller_level = 2) ? File "/usr/local/lib/python2.4/site-packages/numpy/distutils/misc_util.py", line 834, in get_subpackage ??? caller_level = caller_level + 1) ? File "/usr/local/lib/python2.4/site-packages/numpy/distutils/misc_util.py", line 781, in _get_configuration_from_setup_py ??? config = setup_module.configuration(*args) ? File "scipy/integrate/setup.py", line 10, in configuration ??? blas_opt = get_info('blas_opt',notfound_action=2) ? File "/usr/local/lib/python2.4/site-packages/numpy/distutils/system_info.py", line 267, in get_info ??? return cl().get_info(notfound_action) ? File "/usr/local/lib/python2.4/site-packages/numpy/distutils/system_info.py", line 416, in get_info ??? raise self.notfounderror,self.notfounderror.__doc__ numpy.distutils.system_info.BlasNotFoundError: ??? Blas (http://www.netlib.org/blas/) libraries not found. ??? Directories to search for the libraries can be specified in the ??? numpy/distutils/site.cfg file (section [blas]) or by setting ??? the BLAS environment variable. On Thu, Dec 17, 2009 at 11:59 AM, Ishwor Gurung wrote: > > > As root- > PEBKAC :> > > No need to be root to install in your home dir. > > [...] > -- > Regards, > Ishwor Gurung -- Regards, Ishwor Gurung From lie.1296 at gmail.com Thu Dec 17 06:40:39 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Thu, 17 Dec 2009 22:40:39 +1100 Subject: (OT) Where Are Cookies Stored? In-Reply-To: References: <4dc0cfea0912150730w1d0c131agb258029b3e9a21ca@mail.gmail.com> <4dc0cfea0912160530l5c7a66f0ia23ff98fbafb99e8@mail.gmail.com> Message-ID: <4b2a18cb$1@dnews.tpgi.com.au> On 12/17/2009 2:33 AM, Dave Angel wrote: > > > Victor Subervi wrote: >> On Tue, Dec 15, 2009 at 6:57 PM, r0g wrote: >> >> >>> Cookies in FF for Windows are stored in an sqlite database in here... >>> >>> ~\Application Data\Mozilla\Firefox\Profiles\%XYZ%\firefox_profile\ >>> >> >> Man, I searched C drive (the only drive) on this computer where I'm >> working >> (Internet cafe) for "Application Data" and nuttin. >> V >> > How are you searching? Microsoft is so sure we don't want to see the > gory details that they hide all sorts of things, by default. And > especially on a public computer, you shouldn't even look with Explorer. > As for searching with Explorer, there are not only design problems, but > bugs as well. Get a command line, and do something like: > Or, you can just open Internet Explorer, type at the address bar "www.google.com"; then wait for a few seconds. After the page loads, type "windows {VERSION} application data" where you substitute {VERSION} with the windows version you're using. Press "I'm feeling lucky" and skim the page for something that looks like pathnames. From praveen.sunsetpoint at gmail.com Thu Dec 17 07:05:13 2009 From: praveen.sunsetpoint at gmail.com (Sallu) Date: Thu, 17 Dec 2009 04:05:13 -0800 (PST) Subject: Help with parsing a list References: <36dec4ff0912161332y18233d1em8acf566ecf4356a@mail.gmail.com> Message-ID: <26bc9fdf-2e59-4949-9e17-c1780ca083cb@m26g2000yqb.googlegroups.com> On Dec 17, 4:23?am, "thunderf... at gmail.com" wrote: > not as slick as Emile's (didn't think about using strip() ), but > seemingly functional: > > data = ['key1: data1','key2: data2','key3: data3',' key4: ',' > \tdata4.1',' \tdata4.2',' \tdata4.3','key5: data5'] > result = {} > > for item in data: > ? ? if item.endswith(': '): > ? ? ? ? currkey = item[:-2] > ? ? ? ? result[currkey] = [] > ? ? elif item.startswith(' \t'): > ? ? ? ? result[currkey].append(item[2:]) > ? ? else: > ? ? ? ? key, val = item.split(': ') > ? ? ? ? result[key] = val > > print 'data = %s' % data > print 'result = %s' % result > > > > data = ['key1: data1', 'key2: data2', 'key3: data3', ' key4: ', ' > \tdata4.1', ' \tdata4.2', ' \tdata4.3', 'key5: data5'] > result = {'key3': 'data3', 'key2': 'data2', 'key1': 'data1', 'key5': > 'data5', ' key4': ['data4.1', 'data4.2', 'data4.3']} > > > > Hi i tried with thunderfoot code error: Traceback (most recent call last): File "", line 8, in ? ValueError: need more than 1 value to unpack From sverreodegard at gmail.com Thu Dec 17 07:14:20 2009 From: sverreodegard at gmail.com (Sverre) Date: Thu, 17 Dec 2009 04:14:20 -0800 (PST) Subject: PIL: problem to convert an image array to PIL format Message-ID: <6d4cfad1-384c-4c4b-a16b-5947fc4ec90a@m26g2000yqb.googlegroups.com> After converting a PIL image in memory to an array with numpy.asarray (), I make a adthreshold() with pymorph() with the result, that all pixels in the array are either false or true (boolean). But my try to convert this back into PIL format is failing img = Image.fromarray(rawimg, '1') because a true will be interpreted as integer 1 ), so that 7 pixels are black and one white. Has someone a solution, so that a picture inly with "true" values doesn't look like this? http://img707.imageshack.us/img707/6051/p012.jpg From franke.rob at googlemail.com Thu Dec 17 07:45:59 2009 From: franke.rob at googlemail.com (Robert Franke) Date: Thu, 17 Dec 2009 13:45:59 +0100 Subject: PIL: problem to convert an image array to PIL format In-Reply-To: <6d4cfad1-384c-4c4b-a16b-5947fc4ec90a@m26g2000yqb.googlegroups.com> References: <6d4cfad1-384c-4c4b-a16b-5947fc4ec90a@m26g2000yqb.googlegroups.com> Message-ID: Hi, On Thu, Dec 17, 2009 at 1:14 PM, Sverre wrote: > After converting a PIL image in memory to an array with numpy.asarray > (), I make a adthreshold() with pymorph() with the result, that all > pixels in the array are either false or true (boolean). But my try to > convert this back into PIL format is failing > > img = Image.fromarray(rawimg, '1') > > because a true will be interpreted as integer 1 ), so that 7 pixels > are black and one white. Has someone a solution, so that a picture > inly with "true" values doesn't look like this? > > http://img707.imageshack.us/img707/6051/p012.jpg > > I am not 100% sure this is what you want, but this is how I apply a simple threshold to a picture: threshold = 145 img = Image.open("gray.jpg") arr = numpy.asarray(img) filtered = arr * (arr < threshold) new_img = Image.fromarray(filtered,"L") Cheers, Robert -------------- next part -------------- An HTML attachment was scrubbed... URL: From daninanz at gmail.com Thu Dec 17 07:54:36 2009 From: daninanz at gmail.com (Dani) Date: Thu, 17 Dec 2009 04:54:36 -0800 (PST) Subject: file.close() does not really close under Windows? Message-ID: Is it correct that low-level file handles are not being closed after doing fd = open(filepath) fd.close() If so, what is the rationale? This seems to result in system errors when trying to (re-)move or reopen "closed" files, as well as when opening (and closing) too many files under Windows. A workaround seems to be os_fd = os.open(filepath) fd = os.fdopen(os_fd) os.close(os_fd) From aioe.org at technicalbloke.com Thu Dec 17 08:02:20 2009 From: aioe.org at technicalbloke.com (r0g) Date: Thu, 17 Dec 2009 13:02:20 +0000 Subject: ftplib timeout in Python 2.4 References: Message-ID: Nico Grubert wrote: > Hi there, > > The ftplib has a timeout parameter in Python 2.6 and above. > Is there a way to set a timeout in Python 2.4? > > Regards > Nico I don't know of one so you may need a workaround. What platforms do you need to support? Roger. From aioe.org at technicalbloke.com Thu Dec 17 08:21:42 2009 From: aioe.org at technicalbloke.com (r0g) Date: Thu, 17 Dec 2009 13:21:42 +0000 Subject: webscrapping ringcentral.com using mechanize References: Message-ID: shrini wrote: > Hi, > > I am trying to scrap the website 'http://service.ringcentral.com' > > It has a form with three input boxes. > > When trying to get the form with mechanize, it is throwing the > following error. > > mechanize._mechanize.FormNotFoundError: no form matching name 'login' > > but, the page has the form with name "login". > > This form is submitted by javascript. > > Need your help to fill the form and login to that site using python > +mechanize. > > My code is pasted here. > > http://pastebin.com/f339461b4 > > Thanks. > > Regards, > Shrinivasan You wouldn't be trying to crack their customers account logins would you? Coz it would be highly illegal if you were. Just sayin. Roger. From sraji.me at gmail.com Thu Dec 17 08:50:36 2009 From: sraji.me at gmail.com (Raji Seetharaman) Date: Thu, 17 Dec 2009 19:20:36 +0530 Subject: When to use mechanize and Windmill library during WebScraping ? Message-ID: <23e3fbb60912170550p6b6686d7n7e50aa793703989f@mail.gmail.com> > > ---------- Forwarded message ---------- > From: Javier Collado > To: Raji Seetharaman > Date: Sat, 12 Dec 2009 12:52:27 +0100 > Subject: Re: When to use mechanize and Windmill library during WebScraping > ? > Hello, > > If a script that uses mechanize fails to find an html node that has > been identified with Firebug, this is probably because that node has > been autogenerated (provided that the expression to get the node is > correct). > > As an alternative to verify this, you can try to download the html > page and open it in your favourite editor. If some of the nodes that > you can see in your browser are missing or empty, then one of the > JavaScript scripts in the page should have created/populated it. > > If you're in doubt, you can try to use mechanize and, if you have > problems such as the described above, then you can move to windmill or > some other tool that executes JavaScript code before trying to get the > desired data. > > Best regards, > Javier > > Thanks for your help Raji. S -------------- next part -------------- An HTML attachment was scrubbed... URL: From sraji.me at gmail.com Thu Dec 17 08:54:54 2009 From: sraji.me at gmail.com (Raji Seetharaman) Date: Thu, 17 Dec 2009 19:24:54 +0530 Subject: When to use mechanize and Windmill library during WebScraping ? Message-ID: <23e3fbb60912170554r28974649uac2da629e4912b09@mail.gmail.com> > Be sure to look at Scrapy too: http://scrapy.org > > > Thank U Raji. S -------------- next part -------------- An HTML attachment was scrubbed... URL: From fetchinson at googlemail.com Thu Dec 17 08:56:47 2009 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Thu, 17 Dec 2009 14:56:47 +0100 Subject: pyZui - anyone know about this? In-Reply-To: References: <948af6e4-ab38-4d6d-a296-40bccffa7083@2g2000prl.googlegroups.com> Message-ID: >> /home/fetchinson/pyzui/pyzui/tilestore.py:22: DeprecationWarning: the >> sha module is deprecated; use the hashlib module instead >> import sha > Yeah, I'd noticed that. It's fixed in the repository now. Great, thanks, pulled it and all looks good. Cheers, Daniel >> > PyZUI 0.1 has been released: >> >> >http://da.vidr.cc/projects/pyzui/ >> >> Cool, thanks very much! >> >> I'm using python 2.6 these days and noticed that you use the sha >> module which makes py2.6 spit out a deprecation warning: >> >> /home/fetchinson/pyzui/pyzui/tilestore.py:22: DeprecationWarning: the >> sha module is deprecated; use the hashlib module instead >> import sha >> >> It's no big deal but if you want to be future proof maybe you can >> switch to hashlib for py2.6 and stay with sha for py2.5 and before (a >> try/except block would suffice). >> >> Cheers, >> Daniel >> >> -- >> Psss, psss, put it down! -http://www.cafepress.com/putitdown > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From ishwor.gurung at gmail.com Thu Dec 17 09:21:15 2009 From: ishwor.gurung at gmail.com (Ishwor Gurung) Date: Fri, 18 Dec 2009 00:51:15 +1030 Subject: Multiple python installations on opensuse? In-Reply-To: <417457b50912170525t4d77c9b8te7ad241a2c8645f9@mail.gmail.com> References: <417457b50912170050w610574a2m6edfb31778d22516@mail.gmail.com> <34534aed0912170249w8223eaax2bafd2181aa8ad60@mail.gmail.com> <34534aed0912170259p4603a351n17deffb878c77efc@mail.gmail.com> <417457b50912170315q741304e3l5a05b46204c1e839@mail.gmail.com> <34534aed0912170327v446e08an6e5043c7f1d21f43@mail.gmail.com> <417457b50912170525t4d77c9b8te7ad241a2c8645f9@mail.gmail.com> Message-ID: <34534aed0912170621g4774c6f3q25f18f68aed259f4@mail.gmail.com> 2009/12/17 Johan Ekh : > But I have them installed already! I have scipy installed under python 2.6 > and everything runs perfect. ok > It is only under python 2.4 that the install script can not find the > libraries. I need to tell the script to > lookin /usr/lib64 instead /usr/lib, how can I do this? As root, tell linker to look for libraries in /usr/lib64: $ echo /usr/lib64 >> /etc/ld.so.conf $ ldconfig $ ./configure Please send email to the mailing list. I am subscribed to it :> [...] -- Regards, Ishwor Gurung From nosklo at gmail.com Thu Dec 17 09:25:17 2009 From: nosklo at gmail.com (Clovis Fabricio) Date: Thu, 17 Dec 2009 12:25:17 -0200 Subject: file.close() does not really close under Windows? In-Reply-To: References: Message-ID: <9187a60d0912170625w361acef5mf76a2e1939322d9f@mail.gmail.com> Hello Dani, 2009/12/17 Dani : > Is it correct that low-level file handles are not being closed after > doing > fd = open(filepath) > fd.close() > If so, what is the rationale? No, it is incorrect. I tested that exact snippet here and it correctly closes the file. I can move the file around just after that. There must be something wrong elsewhere on your code. That said, you could use the "with" statement in python >2.5 to make it clearer: with open(filepath) as fd: # ... do stuff with fd ... The file will be closed at the end of the with block. nosklo From python.list at tim.thechases.com Thu Dec 17 09:33:08 2009 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 17 Dec 2009 08:33:08 -0600 Subject: file.close() does not really close under Windows? In-Reply-To: References: Message-ID: <4B2A4124.3050607@tim.thechases.com> Dani wrote: > Is it correct that low-level file handles are not being closed after > doing > > fd = open(filepath) > fd.close() no, you are not correct. Demonstration: Cmd window #1: c:\temp> echo hello world > x.txt Cmd window #2 c:\temp> python Python 2.4.3 (#69, Mar 29 2006, 17:35:34) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> f = file('x.txt') >>> f.close() >>> # remaining in an open python session back to Cmd window #1 C:\temp> del x.txt C:\temp> rem note...no error here. C:\temp> exit back to Cmd window #2 >>> # quit python >>> ^Z C:\temp> exit > If so, what is the rationale? it's not because there is no good rationale for wanting that behavior :) The above was performed on XP (SP2 & SP3) with no issues. I can't guarantee that MS hasn't borked something in Vista or Win7, but if they did, that's *their* issue, not Python's. > This seems to result in system errors when trying to (re-)move or > reopen "closed" files, as well as when opening (and closing) too many > files under Windows. As always, check your own code/environment before assuming the problem is with Python. In all likelihood, you had the file open in another window/process and didn't remember. Perhaps some background indexing process happened to hold the file open for a brief spell? -tkc From nicogrubert at gmail.com Thu Dec 17 09:34:31 2009 From: nicogrubert at gmail.com (Nico Grubert) Date: Thu, 17 Dec 2009 15:34:31 +0100 Subject: ftplib timeout in Python 2.4 In-Reply-To: References: Message-ID: <4B2A4177.7090309@gmail.com> > I don't know of one so you may need a workaround. What platforms do you > need to support? Suse Linux Enterprise 10, 64 Bit with Python 2.4.4. I need the Python 2.4.4 for a running application Server (Zope). From __peter__ at web.de Thu Dec 17 09:45:34 2009 From: __peter__ at web.de (Peter Otten) Date: Thu, 17 Dec 2009 15:45:34 +0100 Subject: PIL: problem to convert an image array to PIL format References: <6d4cfad1-384c-4c4b-a16b-5947fc4ec90a@m26g2000yqb.googlegroups.com> Message-ID: Sverre wrote: > After converting a PIL image in memory to an array with numpy.asarray > (), I make a adthreshold() with pymorph() with the result, that all > pixels in the array are either false or true (boolean). But my try to > convert this back into PIL format is failing > > img = Image.fromarray(rawimg, '1') > > because a true will be interpreted as integer 1 ), so that 7 pixels > are black and one white. Has someone a solution, so that a picture > inly with "true" values doesn't look like this? > > http://img707.imageshack.us/img707/6051/p012.jpg This has come up before, see http://mail.python.org/pipermail/python-list/2009-October/1221578.html Image.fromarray() expects one bit per pixel but actually gets one byte. One possible workaround: introduce an intermediate array with a format understood by fromarray(): >>> import numpy >>> from PIL import Image >>> rawimg = numpy.zeros((20, 20), bool) >>> rawimg[:10, :10] = rawimg[10:, 10:] = True >>> b = numpy.array(rawimg, numpy.uint8) >>> b *= 255 >>> Image.fromarray(b).save("tmp.jpg") Peter From daninanz at gmail.com Thu Dec 17 09:49:52 2009 From: daninanz at gmail.com (Dani) Date: Thu, 17 Dec 2009 06:49:52 -0800 (PST) Subject: file.close() does not really close under Windows? References: Message-ID: <75d4c6f2-25e7-428d-a9c2-526b34820c42@o28g2000yqh.googlegroups.com> > No, it is incorrect. I tested that exact snippet here and it correctly > closes the file. I can move the file around just after that. Yes, indeed. Sorry for not getting my facts straight and thank you for testing. Part of the code *was* holding a low-level file handle. From alan.isaac at gmail.com Thu Dec 17 10:08:00 2009 From: alan.isaac at gmail.com (Alan G Isaac) Date: Thu, 17 Dec 2009 10:08:00 -0500 Subject: Raw string substitution problem In-Reply-To: References: <931375.44828.qm@web58902.mail.re1.yahoo.com> Message-ID: > En Wed, 16 Dec 2009 11:09:32 -0300, Ed Keith escribi?: > >> I am having a problem when substituting a raw string. When I do the >> following: >> >> re.sub('abc', r'a\nb\nc', '123abcdefg') >> >> I get >> >> """ >> 123a >> b >> cdefg >> """ >> >> what I want is >> >> r'123a\nb\ncdefg' On 12/16/2009 9:35 AM, Gabriel Genellina wrote: > From http://docs.python.org/library/re.html#re.sub > > re.sub(pattern, repl, string[, count]) > > ...repl can be a string or a function; if > it is a string, any backslash escapes in > it are processed. That is, \n is converted > to a single newline character, \r is > converted to a linefeed, and so forth. > > So you'll have to double your backslashes: I'm not persuaded that the docs are clear. Consider: >>> 'ab\\ncd' == r'ab\ncd' True Naturally enough. So I think the right answer is: 1. this is a documentation bug (i.e., the documentation fails to specify unexpected behavior for raw strings), or 2. this is a bug (i.e., raw strings are not handled correctly when used as replacements) I vote for 2. Peter's use of a function highlights just how odd this is: getting the raw string via a function produces a different result than providing it directly. If this is really the way things ought to be, I'd appreciate a clear explanation of why. Alan Isaac From python at bdurham.com Thu Dec 17 11:08:17 2009 From: python at bdurham.com (python at bdurham.com) Date: Thu, 17 Dec 2009 11:08:17 -0500 Subject: Which version of MSVC?90.DLL's to distribute with Python 2.6 based Py2exe executables? Message-ID: <1261066097.3228.1350592605@webmail.messagingengine.com> Does anyone have any recommendations on which version of the MSVC?90.DLL's need to be distributed with a Python 2.6.4 PY2EXE (0.6.9) based executable? (I assume I need just a matching pair of MSVCR90.DLL and MSVCP90.DLL?) My understanding is that I need to match the version of the DLL's that my version of Python 2.6.4 was compiled against? On my Windows 7 Professional (64-bit) workstation, I have the following sets of MSVC?9.DLL files to choose from. Directory of C:\Program Files\Sony\VAIO Care 07/14/2009 01:18 PM 245,248 msvcm90.dll 07/14/2009 01:18 PM 851,456 msvcp90.dll 07/14/2009 01:18 PM 627,200 msvcr90.dll 3 File(s) 1,723,904 bytes Directory of C:\Program Files\Sony\VAIO Care\plugins\Microsoft.VC90.CRT 07/14/2009 01:18 PM 245,248 msvcm90.dll 07/14/2009 01:18 PM 851,456 msvcp90.dll 07/14/2009 01:18 PM 627,200 msvcr90.dll 3 File(s) 1,723,904 bytes Directory of C:\Program Files (x86)\Sony\VAIOData Restore Tool 11/26/2008 10:26 AM 568,832 msvcp90.dll 11/26/2008 08:57 AM 655,872 msvcr90.dll 2 File(s) 1,224,704 bytes Directory of C:\Program Files (x86)\Sony\VAIO Recovery\plugins 07/15/2009 05:21 PM 224,768 msvcm90.dll 07/15/2009 05:21 PM 568,832 msvcp90.dll 07/15/2009 05:21 PM 655,872 msvcr90.dll 3 File(s) 1,449,472 bytes Directory of C:\Program Files (x86)\Sony\VAIO Recovery\plugins\x64 07/15/2009 05:21 PM 627,200 msvcr90.dll 1 File(s) 627,200 bytes Directory of C:\Program Files (x86)\Sony\VAIO VP Utilities 04/02/2009 07:12 PM 568,832 msvcp90.dll 04/02/2009 07:12 PM 655,872 msvcr90.dll 2 File(s) 1,224,704 bytes Directory of C:\Windows\winsxs\amd64_microsoft.vc90.crt_1fc8b3b9a1e18e3b_9.0.2 1022.8_none_750b37ff97f4f68b 09/04/2009 04:35 AM 245,248 msvcm90.dll 09/04/2009 04:35 AM 851,456 msvcp90.dll 09/04/2009 04:35 AM 627,200 msvcr90.dll 3 File(s) 1,723,904 bytes Directory of C:\Windows\winsxs\amd64_microsoft.vc90.crt_1fc8b3b9a1e18e3b_9.0.3 0729.4926_none_08e1a05ba83fe554 06/10/2009 03:31 PM 245,760 msvcm90.dll 06/10/2009 03:31 PM 853,328 msvcp90.dll 06/10/2009 03:31 PM 623,440 msvcr90.dll 3 File(s) 1,722,528 bytes Directory of C:\Windows\winsxs\x86_microsoft.vc90.crt_1fc8b3b9a1e18e3b_9.0.210 22.8_none_bcb86ed6ac711f91 09/04/2009 04:35 AM 224,768 msvcm90.dll 09/04/2009 04:35 AM 568,832 msvcp90.dll 09/04/2009 04:35 AM 655,872 msvcr90.dll 3 File(s) 1,449,472 bytes Directory of C:\Windows\winsxs\x86_microsoft.vc90.crt_1fc8b3b9a1e18e3b_9.0.307 29.1_none_e163563597edeada 09/04/2009 04:19 AM 225,280 msvcm90.dll 09/04/2009 04:19 AM 572,928 msvcp90.dll 09/04/2009 04:19 AM 655,872 msvcr90.dll 3 File(s) 1,454,080 bytes Directory of C:\Windows\winsxs\x86_microsoft.vc90.crt_1fc8b3b9a1e18e3b_9.0.307 29.4926_none_508ed732bcbc0e5a 06/10/2009 04:14 PM 225,280 msvcm90.dll 06/10/2009 04:14 PM 569,664 msvcp90.dll 06/10/2009 04:14 PM 652,608 msvcr90.dll 3 File(s) 1,447,552 bytes Thank you, Malcolm From solipsis at pitrou.net Thu Dec 17 11:11:00 2009 From: solipsis at pitrou.net (Antoine Pitrou) Date: Thu, 17 Dec 2009 16:11:00 +0000 (UTC) Subject: Where is PyMethod_GET_CLASS in Python 3? References: <1799a93b-5eb8-4818-ab94-7aa4108fcea1@j24g2000yqa.googlegroups.com> Message-ID: Le Tue, 15 Dec 2009 08:08:01 -0800, Infinity77 a ?crit?: > > When building C extensions In Python 2.X, there was a magical > PyMethod_GET_CLASS implemented like this: > > #define PyMethod_GET_CLASS(meth) \ > (((PyMethodObject *)meth) -> im_class) > > It looks like Python 3 has wiped out the "im_class" attribute. Which is > the alternative was to handle this case in Python 3? First, is it a bound method? Unbound methods are just function objects in py3k. Check that PyMethod_Check() returns true. Second, have you tried Py_TYPE(PyMethod_GET_SELF(meth))? > BTW, it's very, very, > *very* hard to find any possible reference to help migrating existing C > extensions from Python 2.X to Python 3. There's http://docs.python.org/3.1/howto/cporting.html You are encouraged to post any suggestions or corrections on the bug tracker: http://bugs.python.org Finally, there's also a dedicated mailing-list for porting to py3k: http://mail.python.org/mailman/listinfo/python-porting While it hasn't seen a lot of activity lately, I'm sure there are people there willing to answer any questions you have! Regards Antoine. From benjamin.kaplan at case.edu Thu Dec 17 11:12:37 2009 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Thu, 17 Dec 2009 11:12:37 -0500 Subject: More stuff added to ch 2 of my programming intro In-Reply-To: References: <9127dff9-90eb-4a73-aa51-e644f5e4e5bf@r1g2000vbn.googlegroups.com> <88bab2c0-d27c-4081-a703-26b353b9ed71@9g2000yqa.googlegroups.com> <183af5d2-e157-4cd6-bec6-8997809e1f51@d21g2000yqn.googlegroups.com> Message-ID: On Thu, Dec 17, 2009 at 5:33 AM, Ned Deily wrote: > >> > or (for MacPorts fans): >> > >> > $ sudo port install python31 >> >> >> And since I haven't got one, this also tells me nothing. > > http://www.macports.org/ > > "The MacPorts Project is an open-source community initiative to design > an easy-to-use system for compiling, installing, and upgrading either > command-line, X11 or Aqua based open-source software on the Mac OS X > operating system." Description sans marketing fluff: It's a Mac package manager. It's basically the same as Gentoo's portage if you've ever used that. It downloads source tarballs and patches and then compiles them locally. There are built-in lists of "variants", basically sets of configure args, to compile each package. From R.Brodie at rl.ac.uk Thu Dec 17 11:24:32 2009 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Thu, 17 Dec 2009 16:24:32 -0000 Subject: Raw string substitution problem References: <931375.44828.qm@web58902.mail.re1.yahoo.com> Message-ID: "Alan G Isaac" wrote in message news:qemdnRUT0JvJ1LfWnZ2dnUVZ_vqdnZ2d at rcn.net... > Naturally enough. So I think the right answer is: > > 1. this is a documentation bug (i.e., the documentation > fails to specify unexpected behavior for raw strings), or > 2. this is a bug (i.e., raw strings are not handled correctly > when used as replacements) There is no raw string. A raw string is not a distinct type from an ordinary string in the same way byte strings and Unicode strings are. It is a merely a notation for constants, like writing integers in hexadecimal. >>> (r'\n', u'a', 0x16) ('\\n', u'a', 22) From vorticitywolfe at gmail.com Thu Dec 17 11:26:44 2009 From: vorticitywolfe at gmail.com (J Wolfe) Date: Thu, 17 Dec 2009 08:26:44 -0800 (PST) Subject: frames in toplevel Tkinter References: <26b8509c-921d-484b-bab3-e318ba95a73d@21g2000yqj.googlegroups.com> Message-ID: <73376cdb-9f0b-47d5-9bce-6ed9bc28f115@j4g2000yqe.googlegroups.com> On Dec 16, 11:09?pm, J Wolfe wrote: > Probably a stupid question, but can you have a frames in a toplevel > widget? Anything I try to put in a frame goes back to the main or root > widget and not the toplevel or pop-up widget. > > Thanks for the help! > Jonathan Thank you John, from Tkinter import * root = Tk() Label(root, text='This is the root window').pack() top = Toplevel(root) fr = Frame(top) # frame child of Toplevel called top fr.pack() Label(fr, text='This is in a frame in the Toplevel window').pack() root.mainloop() I swear I tried that about 20 times yesterday...and it kept putting it in my main window. Perhaps I had a naming issue. Thanks! Jonathan From wolftracks at invalid.com Thu Dec 17 11:29:26 2009 From: wolftracks at invalid.com (W. eWatson) Date: Thu, 17 Dec 2009 08:29:26 -0800 Subject: Using Python to Execute a C or FORTRAN Program (Windows) In-Reply-To: <65974b45-3e9c-4a18-86a3-915cbfb3a2e8@26g2000yqo.googlegroups.com> References: <65974b45-3e9c-4a18-86a3-915cbfb3a2e8@26g2000yqo.googlegroups.com> Message-ID: sturlamolden wrote: > On 17 Des, 03:41, "W. eWatson" wrote: > >> His program was originally written in Python, but a new >> hardware device (capture card) had no good interface with Python, so he >> wrote it in C++, which does. From my knowledge of the Python program >> before the entry of c++, it seems he could have farmed out the hardware >> interface in much the same way he had done it before with a capture card >> well know to him. > > This sounds a bit incompetent. > > Why didn't he just write an extension module in C++? > > Also, if you don't know how to spawn a subprocess, I'd question your > competence as well. > I can't read his mind. From wolftracks at invalid.com Thu Dec 17 11:31:46 2009 From: wolftracks at invalid.com (W. eWatson) Date: Thu, 17 Dec 2009 08:31:46 -0800 Subject: Either IDLE Can't Start a subprocess or a firewall software firewall is blocking the connection (Win)--Battlin McAfee In-Reply-To: References: Message-ID: Alf P. Steinbach wrote: > * W. eWatson: >> See Subject msg from Python 2.5 Win XP. It is preceded by a "Socket >> Error". It happened while I had a simple program displayed, and I >> wanted to see the shell. The msg occurred when I pressed Shell on Run >> from the menu. I played around for awhile, but got nowhere. Same msg. >> I did remove my McAfee firewall protection, and it worked once, but >> reverted to not working. >> >> I rebooted and the first time I could use Shell, it succeeded. After >> that it failed. Comments? Geeze! Mcaffe turned on the firewall again >> after the reboot. >> >> All seems well now. Nope. McAfee turned the firewall back on. It >> decided to warn me it was off, but now has allowed me to ignore the >> fact it is "no longer protecting me". I'll just let Win firewall do >> that, thank you. >> >> Nope it's back. I'll just stop here and let anyone who wants to just >> chime in. If I get it to stop, I'll be back. > > I recall vaguely some similar problem caused by a program attempting to > connect to localhost, and the solution then was to edit the hosts file > (don't ask me for details, but perhaps that'll help you search: that > problem had entirely to do with Windows' very over-zealous "security" > measures). > > > Cheers & hth., > > - Alf As it turns out, I can "sneak" around it, so I'm putting it aside. From sverreodegard at gmail.com Thu Dec 17 11:33:44 2009 From: sverreodegard at gmail.com (Sverre) Date: Thu, 17 Dec 2009 08:33:44 -0800 (PST) Subject: PIL: problem to convert an image array to PIL format References: <6d4cfad1-384c-4c4b-a16b-5947fc4ec90a@m26g2000yqb.googlegroups.com> Message-ID: On 17 Des, 15:45, Peter Otten <__pete... at web.de> wrote: > > This has come up before, see > > http://mail.python.org/pipermail/python-list/2009-October/1221578.html > > Peter Thank you! From anh.hai.trinh at gmail.com Thu Dec 17 11:41:19 2009 From: anh.hai.trinh at gmail.com (Anh Hai Trinh) Date: Thu, 17 Dec 2009 08:41:19 -0800 (PST) Subject: iterators and views of lists References: <89604fb4-9dfa-45f1-a3df-f676cd4353ea@x5g2000prf.googlegroups.com> Message-ID: <87b87511-744c-450e-a024-976f8c57f032@15g2000prz.googlegroups.com> > I have a couple of thoughts: > 1. Since [:] by convention already creates a copy, it might violate > people's expectations if that syntax were used. Indeed, listagent returns self on __getitem__[:]. What I meant was this: x = [0, 1, 2, 3, 4, 5, 6, 7] a = listagent(x)[::2] a[:] = listagent(x)[::-2] And we get x = [7, 1, 5, 3, 3, 5, 1, 7], the copying happens in-place, of course. > 2. I'd give the listagent the mutable sequence interface Done! I put the code in a repository here for those who might be interested: . In retrospect, the Python gurus here was right though. Copy, modify then replace is good enough, if not better since items are just pointers instead of values. For reversing, you need to translate all the indices (which cost exactly one addition and one multiplication per index). Is that cheaper than copying all the pointers to a new list? For sorting, you definitely need to construct a lookup table since the sort algorithm needs to look over the indices multiple times, which means you are using two pointer indirections per index. Is that cheaper than just copying all the pointers to a new list? Even if there is any benefit at all, you'll need to implement listagent in C to squeeze it out. However, using listagents is faster if you just want a few items out of the slice. And it's cute. Peace, ----aht From alan.isaac at gmail.com Thu Dec 17 11:51:26 2009 From: alan.isaac at gmail.com (Alan G Isaac) Date: Thu, 17 Dec 2009 11:51:26 -0500 Subject: Raw string substitution problem In-Reply-To: References: <931375.44828.qm@web58902.mail.re1.yahoo.com> Message-ID: <2I-dnaKkY7MM_LfWnZ2dnUVZ_sGdnZ2d@rcn.net> On 12/17/2009 11:24 AM, Richard Brodie wrote: > A raw string is not a distinct type from an ordinary string > in the same way byte strings and Unicode strings are. It > is a merely a notation for constants, like writing integers > in hexadecimal. > >>>> (r'\n', u'a', 0x16) > ('\\n', u'a', 22) Yes, that was a mistake. But the problem remains:: >>> re.sub('abc', r'a\nb\n.c\a','123abcdefg') == re.sub('abc', 'a\\nb\\n.c\\a',' 123abcdefg') == re.sub('abc', 'a\nb\n.c\a','123abcdefg') True >>> r'a\nb\n.c\a' == 'a\\nb\\n.c\\a' == 'a\nb\n.c\a' False Why are the first two strings being treated as if they are the last one? That is, why isn't '\\' being processed in the obvious way? This still seems wrong. Why isn't it? More simply, consider:: >>> re.sub('abc', '\\', '123abcdefg') Traceback (most recent call last): File "", line 1, in File "C:\Python26\lib\re.py", line 151, in sub return _compile(pattern, 0).sub(repl, string, count) File "C:\Python26\lib\re.py", line 273, in _subx template = _compile_repl(template, pattern) File "C:\Python26\lib\re.py", line 260, in _compile_repl raise error, v # invalid expression sre_constants.error: bogus escape (end of line) Why is this the proper handling of what one might think would be an obvious substitution? Thanks, Alan Isaac From thunderfoot at gmail.com Thu Dec 17 12:10:49 2009 From: thunderfoot at gmail.com (thunderfoot at gmail.com) Date: Thu, 17 Dec 2009 09:10:49 -0800 (PST) Subject: Help with parsing a list References: <36dec4ff0912161332y18233d1em8acf566ecf4356a@mail.gmail.com> <26bc9fdf-2e59-4949-9e17-c1780ca083cb@m26g2000yqb.googlegroups.com> Message-ID: <75366607-a2a4-4ea4-9f80-337b2ec8f548@v25g2000yqk.googlegroups.com> On Dec 17, 6:05?am, Sallu wrote: > Hi i tried with thunderfoot code > > error: > > Traceback (most recent call last): > ? File "", line 8, in ? > ValueError: need more than 1 value to unpack- Hide quoted text - > hence, my 'seemingly' functional qualification. :) that's most likely to due to a datum starting with '\t' instead of ' \t'. yet another reason that emile's code is superior to my one off. From darcy at druid.net Thu Dec 17 12:19:52 2009 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Thu, 17 Dec 2009 12:19:52 -0500 Subject: Raw string substitution problem In-Reply-To: <2I-dnaKkY7MM_LfWnZ2dnUVZ_sGdnZ2d@rcn.net> References: <931375.44828.qm@web58902.mail.re1.yahoo.com> <2I-dnaKkY7MM_LfWnZ2dnUVZ_sGdnZ2d@rcn.net> Message-ID: <20091217121952.bb56bcdc.darcy@druid.net> On Thu, 17 Dec 2009 11:51:26 -0500 Alan G Isaac wrote: > >>> re.sub('abc', r'a\nb\n.c\a','123abcdefg') == re.sub('abc', 'a\\nb\\n.c\\a',' 123abcdefg') == re.sub('abc', 'a\nb\n.c\a','123abcdefg') > True Was this a straight cut and paste or did you make a manual change? Is that leading space in the middle one a copying error? I get False for what you actually have there for obvious reasons. > >>> r'a\nb\n.c\a' == 'a\\nb\\n.c\\a' == 'a\nb\n.c\a' > False > > Why are the first two strings being treated as if they are the last one? They aren't. The last string is different. >>> for x in (r'a\nb\n.c\a', 'a\\nb\\n.c\\a', 'a\nb\n.c\a'): print repr(x) ... 'a\\nb\\n.c\\a' 'a\\nb\\n.c\\a' 'a\nb\n.c\x07' > That is, why isn't '\\' being processed in the obvious way? > This still seems wrong. Why isn't it? What do you think is wrong? What would the "obvious" way of handling '//' be? > > More simply, consider:: > > >>> re.sub('abc', '\\', '123abcdefg') > Traceback (most recent call last): > File "", line 1, in > File "C:\Python26\lib\re.py", line 151, in sub > return _compile(pattern, 0).sub(repl, string, count) > File "C:\Python26\lib\re.py", line 273, in _subx > template = _compile_repl(template, pattern) > File "C:\Python26\lib\re.py", line 260, in _compile_repl > raise error, v # invalid expression > sre_constants.error: bogus escape (end of line) > > Why is this the proper handling of what one might think would be an > obvious substitution? Is this what you want? What you have is a re expression consisting of a single backslash that doesn't escape anything (EOL) so it barfs. >>> re.sub('abc', r'\\', '123abcdefg') '123\\defg' -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From rridge at csclub.uwaterloo.ca Thu Dec 17 12:36:56 2009 From: rridge at csclub.uwaterloo.ca (Ross Ridge) Date: Thu, 17 Dec 2009 12:36:56 -0500 Subject: Which version of MSVC?90.DLL's to distribute with Python 2.6 based Py2exe executables? References: Message-ID: wrote: >Does anyone have any recommendations on which version of the >MSVC?90.DLL's need to be distributed with a Python 2.6.4 PY2EXE (0.6.9) >based executable? (I assume I need just a matching pair of MSVCR90.DLL >and MSVCP90.DLL?) Either the one the came with your copy Microsoft Visual C++ or Python 2.6.4. Otherwise, you don't have the legal right to redistribute Microsoft's code. Ross Ridge -- l/ // Ross Ridge -- The Great HTMU [oo][oo] rridge at csclub.uwaterloo.ca -()-/()/ http://www.csclub.uwaterloo.ca/~rridge/ db // From carlos.grohmann at gmail.com Thu Dec 17 12:37:58 2009 From: carlos.grohmann at gmail.com (Carlos Grohmann) Date: Thu, 17 Dec 2009 09:37:58 -0800 (PST) Subject: shouldn't list comprehension be faster than for loops? Message-ID: <979c8ffe-dc39-4b2b-ab9b-12ecefc12d7a@y24g2000yqb.googlegroups.com> Hello all I am testing my code with list comprehensions against for loops. the loop: dipList=[float(val[1]) for val in datalist] dip1=[] for dp in dipList: if dp == 90: dip1.append(dp - 0.01) else: dip1.append(dp) listcomp: dipList=[float(val[1]) for val in datalist] dip1=[(dp, dp-0.01)[dp==90.0] for dp in dipList] Tenting the time spent by each approach (using time.clock()), with a file with about 100,000 entries, I get 0.03s for the loop and 0.05s for the listcomp. thoughts? TIA Carlos From python at mrabarnett.plus.com Thu Dec 17 12:38:34 2009 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 17 Dec 2009 17:38:34 +0000 Subject: Raw string substitution problem In-Reply-To: <2I-dnaKkY7MM_LfWnZ2dnUVZ_sGdnZ2d@rcn.net> References: <931375.44828.qm@web58902.mail.re1.yahoo.com> <2I-dnaKkY7MM_LfWnZ2dnUVZ_sGdnZ2d@rcn.net> Message-ID: <4B2A6C9A.50909@mrabarnett.plus.com> Alan G Isaac wrote: > On 12/17/2009 11:24 AM, Richard Brodie wrote: >> A raw string is not a distinct type from an ordinary string >> in the same way byte strings and Unicode strings are. It >> is a merely a notation for constants, like writing integers >> in hexadecimal. >> >>>>> (r'\n', u'a', 0x16) >> ('\\n', u'a', 22) > > > > Yes, that was a mistake. But the problem remains:: > > >>> re.sub('abc', r'a\nb\n.c\a','123abcdefg') == re.sub('abc', > 'a\\nb\\n.c\\a',' 123abcdefg') == re.sub('abc', 'a\nb\n.c\a','123abcdefg') > True > >>> r'a\nb\n.c\a' == 'a\\nb\\n.c\\a' == 'a\nb\n.c\a' > False > > Why are the first two strings being treated as if they are the last one? > That is, why isn't '\\' being processed in the obvious way? > This still seems wrong. Why isn't it? > > More simply, consider:: > > >>> re.sub('abc', '\\', '123abcdefg') > Traceback (most recent call last): > File "", line 1, in > File "C:\Python26\lib\re.py", line 151, in sub > return _compile(pattern, 0).sub(repl, string, count) > File "C:\Python26\lib\re.py", line 273, in _subx > template = _compile_repl(template, pattern) > File "C:\Python26\lib\re.py", line 260, in _compile_repl > raise error, v # invalid expression > sre_constants.error: bogus escape (end of line) > > Why is this the proper handling of what one might think would be an > obvious substitution? > Regular expressions and replacement strings have their own escaping mechanism, which also uses backslashes. Some of these regex escape sequences are the same as those of string literals, eg \n represents a newline; others are different, eg \b in a regex represents a word boundary and not a backspace as in a string literal. You can match a newline in a regex by either using an actual newline character ('\n' in a string literal) or an escape sequence ('\\n' or r'\n' in a string literal). If you want a regex to match an actual backslash followed by a letter 'n' then you need to escape the backslash in the regex and then either use a raw string literal or escape it again in a non-raw string literal. Match characters: Regex: \n Raw string literal: r'\n' Non-raw string literal: '\\n' Match characters: \n Regex: \\n Raw string literal: r'\\n' Non-raw string literal: '\\\\n' Replace with characters: Replacement: \n Raw string literal: r'\n' Non-raw string literal: '\\n' Replace with characters: \n Replacement: \\n Raw string literal: r'\\n' Non-raw string literal: '\\\\n' From alfps at start.no Thu Dec 17 12:42:22 2009 From: alfps at start.no (Alf P. Steinbach) Date: Thu, 17 Dec 2009 18:42:22 +0100 Subject: shouldn't list comprehension be faster than for loops? In-Reply-To: <979c8ffe-dc39-4b2b-ab9b-12ecefc12d7a@y24g2000yqb.googlegroups.com> References: <979c8ffe-dc39-4b2b-ab9b-12ecefc12d7a@y24g2000yqb.googlegroups.com> Message-ID: * Carlos Grohmann: > Hello all > > I am testing my code with list comprehensions against for loops. > > the loop: > > dipList=[float(val[1]) for val in datalist] > dip1=[] > for dp in dipList: > if dp == 90: > dip1.append(dp - 0.01) > else: > dip1.append(dp) > > listcomp: > > dipList=[float(val[1]) for val in datalist] > dip1=[(dp, dp-0.01)[dp==90.0] for dp in dipList] > > > Tenting the time spent by each approach (using time.clock()), with a > file with about 100,000 entries, I get 0.03s for the loop and 0.05s > for the listcomp. > > thoughts? In the list comprehension you're constructing n tuples that you're not constructing in the loop. Have you tried this with dip1 = [dp - 0.01 if dp == 90 else dp for dp in dipList] ? Cheers & hth., - Alf From tjreedy at udel.edu Thu Dec 17 12:46:41 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 17 Dec 2009 12:46:41 -0500 Subject: pyZui - anyone know about this? In-Reply-To: <200912170914.00705.donn.ingle@gmail.com> References: <8b6746a9-e4d9-4a47-a11b-e2fd70e61bbc@y10g2000prg.googlegroups.com> <200912170914.00705.donn.ingle@gmail.com> Message-ID: On 12/17/2009 2:14 AM, Donn wrote: > On Wednesday 16 December 2009 07:03:19 David Roberts wrote: >> It involves scaling an image to various resolutions, and partitioning >> them into fixed-size tiles. It's roughly the same technique used by >> Google Maps/Earth. > Thanks. That gives me something to go on. Wikipedia didn't like my search > terms. > >>> ZUIs are useful for particular types of data - images& mapping >>> especially - but I'd hate to have to navigate my desktop using its >>> approach. > Ever since Corel Draw in the 90's zoomed into my life I have been in love with > the idea of an endless canvas that makes me feel like a satellite on a bungee > cord. I think it would fit the desktop very well. > > Personally I see a merging of normal app windows and a zui: some kind of new > window manager. The original idea, perhaps, was from Jef Raskin in The Human Interface. Wikipedia has articles on both. His idea was for a document rather than app centric plain. Not clear how one would pipe data from app to app in his model, though. tjr From alan.isaac at gmail.com Thu Dec 17 12:54:07 2009 From: alan.isaac at gmail.com (Alan G Isaac) Date: Thu, 17 Dec 2009 12:54:07 -0500 Subject: Raw string substitution problem In-Reply-To: References: <931375.44828.qm@web58902.mail.re1.yahoo.com> <2I-dnaKkY7MM_LfWnZ2dnUVZ_sGdnZ2d@rcn.net> Message-ID: > Alan G Isaac wrote: >> >>> re.sub('abc', r'a\nb\n.c\a','123abcdefg') == re.sub('abc', 'a\\nb\\n.c\\a','123abcdefg') == re.sub('abc', 'a\nb\n.c\a','123abcdefg') >> True >> Why are the first two strings being treated as if they are the last one? On 12/17/2009 12:19 PM, D'Arcy J.M. Cain wrote: > They aren't. The last string is different. Of course it is different. That is the basis of my question. Why is it being treated as if it is the same? (See the end of this post.) > Alan G Isaac wrote: >> More simply, consider:: >> >> >>> re.sub('abc', '\\', '123abcdefg') >> Traceback (most recent call last): >> File "", line 1, in >> File "C:\Python26\lib\re.py", line 151, in sub >> return _compile(pattern, 0).sub(repl, string, count) >> File "C:\Python26\lib\re.py", line 273, in _subx >> template = _compile_repl(template, pattern) >> File "C:\Python26\lib\re.py", line 260, in _compile_repl >> raise error, v # invalid expression >> sre_constants.error: bogus escape (end of line) >> >> Why is this the proper handling of what one might think would be an >> obvious substitution? On 12/17/2009 12:19 PM, D'Arcy J.M. Cain wrote: > Is this what you want? What you have is a re expression consisting of > a single backslash that doesn't escape anything (EOL) so it barfs. >>>> re.sub('abc', r'\\', '123abcdefg') > '123\\defg' Turning again to the documentation: "if it is a string, any backslash escapes in it are processed. That is, \n is converted to a single newline character, \r is converted to a linefeed, and so forth." So why is '\n' converted to a newline but '\\' does not become a literal backslash? OK, I don't do much string processing, so perhaps this is where I am missing the point: how is the replacement being "converted"? (As Peter's example shows, if you supply the replacement via a function, this does not happen.) You suggest it is just a matter of it being an re, but:: >>> re.sub('abc', 'a\\nc','1abcd') == re.sub('abc', 'a\nc','1abcd') True >>> re.compile('a\\nc') == re.compile('a\nc') False So I have two string that are not the same, nor do they compile equivalently, yet apparently they are "converted" to something equivalent for the substitution. Why? Is my question clearer? If the answer looks too obvious to state, assume I'm missing it anyway and please state it. As I said, I seldom use the re module. Alan Isaac From carlos.grohmann at gmail.com Thu Dec 17 13:04:16 2009 From: carlos.grohmann at gmail.com (Carlos Grohmann) Date: Thu, 17 Dec 2009 10:04:16 -0800 (PST) Subject: shouldn't list comprehension be faster than for loops? References: <979c8ffe-dc39-4b2b-ab9b-12ecefc12d7a@y24g2000yqb.googlegroups.com> Message-ID: <3d34a4ab-dd25-4ffc-bb7a-bdd62e9b153b@r5g2000yqb.googlegroups.com> > Have you tried this with > > ? ?dip1 = [dp - 0.01 if dp == 90 else dp for dp in dipList] > Yes that is better! many thanks! From mensanator at aol.com Thu Dec 17 13:18:04 2009 From: mensanator at aol.com (Mensanator) Date: Thu, 17 Dec 2009 10:18:04 -0800 (PST) Subject: More stuff added to ch 2 of my programming intro References: <9127dff9-90eb-4a73-aa51-e644f5e4e5bf@r1g2000vbn.googlegroups.com> <88bab2c0-d27c-4081-a703-26b353b9ed71@9g2000yqa.googlegroups.com> <183af5d2-e157-4cd6-bec6-8997809e1f51@d21g2000yqn.googlegroups.com> Message-ID: On Dec 17, 4:33?am, Ned Deily wrote: > In article > <183af5d2-e157-4cd6-bec6-8997809e1... at d21g2000yqn.googlegroups.com>, > > ?Mensanator wrote: > > Oh, I don't know, maybe because I'm thinking about > > buying one and seeing 2.3, 2.4 and 2.5 directories > > on the model in the store made me wary. > > That's odd since, AFAIK, Apple has never released an OS X with Python > 2.4. Hmm...I was poking around in the finder on a display of new iMacs at Best Buy last saturday. I searched for "python" and it took me to a directory listing with three items: Python 2.3 Python 2.4 Python 2.5 It's possible that Python 2.6 is located somewhere else. I assume that Snow Leopard was installed, but I didn't actually check that. > > Current Apple systems ship with OS X 10.6, aka Snow Leopard. ? 10.6 > includes a Python 2.6.1 (64-bit/32-bit) and a Python 2.5.4 (32-bit > only). ?The previous release, 10.5, shipped with 2.5 and 2.3. ?But, not > to worry, if you need other versions, you can download OS X installers > from python.org. > > > >http://www.python.org/download/releases/3.1.1/http://www.python.org/f... > > > on/3.1.1/python-3.1.1.dmg > > > This tells me nothing. > > That's the disk image for the OS X Python 3.1.1 installer. ? But it doesn't say whether that disk image is compatible with Snow Leopard and I don't take such things for granted. > Official > binary installers for OS X are provided on python.org for every final > Python release. > > > > or (for MacPorts fans): > > > > $ sudo port install python31 > > > And since I haven't got one, this also tells me nothing. > > http://www.macports.org/ > > "The MacPorts Project is an open-source community initiative to design > an easy-to-use system for compiling, installing, and upgrading either > command-line, X11 or Aqua based open-source software on the Mac OS X > operating system." Ok, now I know. Thanks for the information. > > -- > ?Ned Deily, > ?n... at acm.org From mensanator at aol.com Thu Dec 17 13:20:56 2009 From: mensanator at aol.com (Mensanator) Date: Thu, 17 Dec 2009 10:20:56 -0800 (PST) Subject: More stuff added to ch 2 of my programming intro References: <9127dff9-90eb-4a73-aa51-e644f5e4e5bf@r1g2000vbn.googlegroups.com> <88bab2c0-d27c-4081-a703-26b353b9ed71@9g2000yqa.googlegroups.com> <183af5d2-e157-4cd6-bec6-8997809e1f51@d21g2000yqn.googlegroups.com> Message-ID: <15c84d30-462d-44f5-980d-be40340ffc5b@b2g2000yqi.googlegroups.com> On Dec 17, 10:12?am, Benjamin Kaplan wrote: > On Thu, Dec 17, 2009 at 5:33 AM, Ned Deily wrote: > > >> > or (for MacPorts fans): > > >> > $ sudo port install python31 > > >> And since I haven't got one, this also tells me nothing. > > >http://www.macports.org/ > > > "The MacPorts Project is an open-source community initiative to design > > an easy-to-use system for compiling, installing, and upgrading either > > command-line, X11 or Aqua based open-source software on the Mac OS X > > operating system." > > Description sans marketing fluff: It's a Mac package manager. It's > basically the same as Gentoo's portage if you've ever used that. It > downloads source tarballs and patches and then compiles them locally. > There are built-in lists of "variants", basically sets of configure > args, to compile each package. That's the kind of thing I want to hear. Looks like I can go ahead and get a Mac and not worry about getting 3.1.1 installed. Thanks. From mensanator at aol.com Thu Dec 17 13:35:40 2009 From: mensanator at aol.com (Mensanator) Date: Thu, 17 Dec 2009 10:35:40 -0800 (PST) Subject: More stuff added to ch 2 of my programming intro References: <9127dff9-90eb-4a73-aa51-e644f5e4e5bf@r1g2000vbn.googlegroups.com> <88bab2c0-d27c-4081-a703-26b353b9ed71@9g2000yqa.googlegroups.com> <183af5d2-e157-4cd6-bec6-8997809e1f51@d21g2000yqn.googlegroups.com> Message-ID: On Dec 17, 1:40?am, geremy condra wrote: > On Thu, Dec 17, 2009 at 2:25 AM, Mensanator wrote: > > On Dec 16, 8:45 pm, Ned Deily wrote: > >> In article > >> <88bab2c0-d27c-4081-a703-26b353b9e... at 9g2000yqa.googlegroups.com>, > > >> Mensanator wrote: > >> > Oh, and about Chapter 1. > > >> > If you're going to use version 3.1.1 as your standard, shouldn't > >> > you also point out that 3.1.1 is NOT bundled with Mac OS X? > > >> > How about devoting a section on downloading the source files > >> > and compiling it on a Mac? > > >> Why would you do that? > > > Oh, I don't know, maybe because I'm thinking about > > buying one and seeing 2.3, 2.4 and 2.5 directories > > on the model in the store made me wary. > > >>http://www.python.org/download/releases/3.1.1/http://www.python.org/f... > > > This tells me nothing. > > >> or (for MacPorts fans): > > >> $ sudo port install python31 > > > And since I haven't got one, this also tells me nothing. > > He just told you what it meant, as if it weren't already obvious. Why would it be obvious? I use a PC, for which $ sudo port install python31 is meaningless. Is MacPorts bundled with Snow Leopard? Or do I have to do this first: MacPorts version 1.8.1 is available in various formats for download and installation (note, if you are upgrading your Mac OS X to a new major release, see the migration info page): ?dmg? disk images for Snow Leopard, Leopard and Tiger as a legacy platform, containing pkg installers for use with the Mac OS X Installer. By far the simplest installation procedure that most users should follow after meeting the requirements listed below. In source form as either a tar.bz2 package or a tar.gz one for manual compilation, if you intend to customize your installation in any way. SVN checkout of the unpackaged sources, if you wish to follow MacPorts development. The selfupdate target of the port(1) command, for users who already have MacPorts installed and wish to upgrade to a newer release. Checksums for our packaged downloads are contained in the corresponding checksums file. Please note that in order to install and run MacPorts on Mac OS X, your system must have installations of the following components: Apple's Xcode Developer Tools (version 3.2.1 or later for Snow Leopard, 3.1.4 or later for Leopard, or 2.5 for Tiger), found at the Apple Developer Connection site or on your Mac OS X installation CDs/ DVD. Ensure that the optional components for command line development are installed ("Unix Development" in the Xcode 3.x installer). The X11 windowing environment (A.K.A. ?X11 User?) for ports that depend on the functionality it provides to run. The ?X11 User? package is an optional installation on your system CDs/ DVD for Tiger, enabled through the ?Customize? button of the installer, whereas it is included by default on Leopard and Snow Leopard. You can use the xorg-server port instead of Apple's X11.app if you wish. > > Geremy Condra From donn.ingle at gmail.com Thu Dec 17 13:43:15 2009 From: donn.ingle at gmail.com (Donn) Date: Thu, 17 Dec 2009 20:43:15 +0200 Subject: pyZui - anyone know about this? In-Reply-To: References: <200912170914.00705.donn.ingle@gmail.com> Message-ID: <200912172043.15508.donn.ingle@gmail.com> On Thursday 17 December 2009 19:46:41 Terry Reedy wrote: > His idea was for a document rather than > app centric plain. These days I find the notion of monolithic apps to be a pita. The concept of many small black boxes (but open source) that each do a single job and pipe in/out is so much more powerful. I don't see why everything in a gui and down can't be such a box. Then we get to wire them together as needed. We'd still have 'big apps' but they would be constructed more loosely and we could adapt them to fit real life needs. I dunno. I think big apps are dinosaurs. As much as I love Inkscape and Blender and others, they are all islands with vast gulfs between them. And let's have Python glue them all together! > Not clear how one would pipe data from app to app in > his model, though. The picture I have of it is illustrated by Blender's material node system. have a look at this pic: http://upload.wikimedia.org/wikipedia/commons/2/26/Working_with_Nodes_Blender.PNG Just a mental jump-off point. Think bash meets zui with a Python driving. :D \d -- \/\/ave: donn.ingle at googlewave.com home: http://otherwise.relics.co.za/ 2D vector animation : https://savannah.nongnu.org/projects/things/ Font manager : https://savannah.nongnu.org/projects/fontypython/ From dahl.joachim at gmail.com Thu Dec 17 14:14:34 2009 From: dahl.joachim at gmail.com (Joachim Dahl) Date: Thu, 17 Dec 2009 11:14:34 -0800 (PST) Subject: PyArg_ParseTupleAndKeywords in Python3.1 References: <0a0b822c-8d57-4816-8563-5fd8ff39f7f1@p8g2000yqb.googlegroups.com> <83f08b89-6b61-4005-9fbd-c9a01da36654@d9g2000prh.googlegroups.com> <408e4acd-3182-4d08-bcb4-d4ff1632d9c2@l13g2000yqb.googlegroups.com> Message-ID: <2a0f6103-3615-4d6a-bd6c-e0bfcbf37eb6@26g2000yqo.googlegroups.com> In the Ubuntu 9.10 version of Python 3.1 (using your patch), there's a related bug: >>> foo(b='b') will set the value of a in the extension module to zero, thus clearing whatever default value it may have had. In other words, the optional character arguments that are skipped seem to be nulled by PyArg_ParseTupleAndKeywords(). From tartley at tartley.com Thu Dec 17 14:37:47 2009 From: tartley at tartley.com (Jonathan Hartley) Date: Thu, 17 Dec 2009 11:37:47 -0800 (PST) Subject: Which version of MSVC?90.DLL's to distribute with Python 2.6 based Py2exe executables? References: Message-ID: <0842d813-4cce-4283-8616-d90c7cbdabc2@a32g2000yqm.googlegroups.com> On Dec 17, 5:36?pm, Ross Ridge wrote: > wrote: > >Does anyone have any recommendations on which version of the > >MSVC?90.DLL's need to be distributed with a Python 2.6.4 PY2EXE (0.6.9) > >based executable? (I assume I need just a matching pair of MSVCR90.DLL > >and MSVCP90.DLL?) > > Either the one the came with your copy Microsoft Visual C++ or Python > 2.6.4. ?Otherwise, you don't have the legal right to redistribute > Microsoft's code. > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? Ross Ridge > > -- > ?l/ ?// ? Ross Ridge -- The Great HTMU > [oo][oo] ?rri... at csclub.uwaterloo.ca > -()-/()/ ?http://www.csclub.uwaterloo.ca/~rridge/ > ?db ?// ? Hi. I clearly haven't yet quite understood this very well. Only this week I sent a py2exe-derived executable to someone else (a non-developer) and it would not run on their WinXP machine ("'The system cannot execute the specified program'") - my current favourite hypothesis is that my omission of this dll or something similar was to blame. To diagnose what's wrong, I can't get access to the machine that gives the above error. To try and reproduce, I'm right now in the process of creating a bare-bones WindowsXP installed on a VM. My questions are, sadly, legion: 1) I don't understand why the OP's question doesn't deserve a literal answer - isn't one of those DLLs in the WinSxS directory derived from his MSVC install? In which case does he have the rights to redistribute it? Ross said: > Either the one the came with your copy Microsoft Visual C++ or Python 2.6.4. 2) The required dlls come with Python? Whatwhatwhat? Is this if I download Python source to compile myself? 2b) Presumably these runtimes must come with Visual Studio express edition (the free one.) I assume I can just prise the required DLL off my filesystem after MSVS express edition has installed, rather than insisting that my users run the MSVC runtime installer at 3) The wxpython site describes that I have to use a manifest file as well as the DLLs, although I find no mention of the word 'manifest' on www.py2exe.org, excepting a vaguely worded news item. Other sites (eg. StackOverflow) report conflicting ideas of whether and when this manifest file is needed. Is there a simple answer to whether this is required? 4) The py2exe wiki says, of the msvc runtime dll version 7.1 (for versions of Python prior to 2.6) that: "Since most Windows installations nowadays include this DLL by default, it may be unnecessary." To what extent is this true? Does the same not also apply to the msvc runtime 9.0 dll? (for Python 2.6.4) Malcome said: > (I assume I need just a matching pair of MSVCR90.DLL and MSVCP90.DLL?) 5) Whatwhatwhat again? More than one DLL is required? Are there ever any more than these two? Sorry to be dense. Terse links to useful sources of information appreciated. I've read the whole py2exe wiki and been googling the last hour. Jonathan From python at mrabarnett.plus.com Thu Dec 17 14:45:46 2009 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 17 Dec 2009 19:45:46 +0000 Subject: Raw string substitution problem In-Reply-To: References: <931375.44828.qm@web58902.mail.re1.yahoo.com> <2I-dnaKkY7MM_LfWnZ2dnUVZ_sGdnZ2d@rcn.net> Message-ID: <4B2A8A6A.9020207@mrabarnett.plus.com> Alan G Isaac wrote: >> Alan G Isaac wrote: >>> >>> re.sub('abc', r'a\nb\n.c\a','123abcdefg') == >>> re.sub('abc', 'a\\nb\\n.c\\a','123abcdefg') == re.sub('abc', >>> 'a\nb\n.c\a','123abcdefg') >>> True >>> Why are the first two strings being treated as if they are the last one? > > > On 12/17/2009 12:19 PM, D'Arcy J.M. Cain wrote: >> They aren't. The last string is different. > > Of course it is different. > That is the basis of my question. > Why is it being treated as if it is the same? > (See the end of this post.) > > >> Alan G Isaac wrote: >>> More simply, consider:: >>> >>> >>> re.sub('abc', '\\', '123abcdefg') >>> Traceback (most recent call last): >>> File "", line 1, in >>> File "C:\Python26\lib\re.py", line 151, in sub >>> return _compile(pattern, 0).sub(repl, string, count) >>> File "C:\Python26\lib\re.py", line 273, in _subx >>> template = _compile_repl(template, pattern) >>> File "C:\Python26\lib\re.py", line 260, in _compile_repl >>> raise error, v # invalid expression >>> sre_constants.error: bogus escape (end of line) >>> >>> Why is this the proper handling of what one might think would be an >>> obvious substitution? > > > On 12/17/2009 12:19 PM, D'Arcy J.M. Cain wrote: >> Is this what you want? What you have is a re expression consisting of >> a single backslash that doesn't escape anything (EOL) so it barfs. > >>>> re.sub('abc', r'\\', '123abcdefg') > > '123\\defg' > > > Turning again to the documentation: > "if it is a string, any backslash escapes in it are processed. > That is, \n is converted to a single newline character, \r is > converted to a linefeed, and so forth." > So why is '\n' converted to a newline but '\\' does not become a literal > backslash? OK, I don't do much string processing, so perhaps this is where > I am missing the point: how is the replacement being "converted"? > (As Peter's example shows, if you supply the replacement via > a function, this does not happen.) You suggest it is just a matter of > it being an re, but:: > > >>> re.sub('abc', 'a\\nc','1abcd') == re.sub('abc', 'a\nc','1abcd') > True > >>> re.compile('a\\nc') == re.compile('a\nc') > False > > So I have two string that are not the same, nor do they compile > equivalently, yet apparently they are "converted" to something > equivalent for the substitution. Why? Is my question clearer? > re.compile('a\\nc') _does_ compile to the same as regex as re.compile('a\nc'). However, regex objects never compare equal to each other, so, strictly speaking, re.compile('a\nc') != re.compile('a\nc'). However, having said that, the re module contains a cache (keyed on the string and options supplied), so the first re.compile('a\nc') will put the regex object in the cache and the second re.compile('a\nc') will return that same regex object from the cache. If you clear the cache in between the two calls (do re._cache.clear()) you'll get two different regex objects which won't compare equal even though they are to all intents identical. > If the answer looks too obvious to state, assume I'm missing it anyway > and please state it. As I said, I seldom use the re module. > From catphive at catphive.net Thu Dec 17 15:07:59 2009 From: catphive at catphive.net (Brendan Miller) Date: Thu, 17 Dec 2009 12:07:59 -0800 Subject: iterators and views of lists In-Reply-To: <87b87511-744c-450e-a024-976f8c57f032@15g2000prz.googlegroups.com> References: <89604fb4-9dfa-45f1-a3df-f676cd4353ea@x5g2000prf.googlegroups.com> <87b87511-744c-450e-a024-976f8c57f032@15g2000prz.googlegroups.com> Message-ID: On Thu, Dec 17, 2009 at 8:41 AM, Anh Hai Trinh wrote: >> I have a couple of thoughts: >> 1. Since [:] by convention already creates a copy, it might violate >> people's expectations if that syntax were used. > > Indeed, listagent returns self on __getitem__[:]. What I meant was > this: > > ?x = [0, 1, 2, 3, 4, 5, 6, 7] > ?a = listagent(x)[::2] > ?a[:] = listagent(x)[::-2] > > And we get x = [7, 1, 5, 3, 3, 5, 1, 7], the copying happens in-place, > of course. > > >> 2. I'd give the listagent the mutable sequence interface > > Done! ?I put the code in a repository here for those who might be > interested: > . > > In retrospect, the Python gurus here was right though. Copy, modify > then replace is good enough, if not better since items are just > pointers instead of values. For reversing, you need to translate all > the indices (which cost exactly one addition and one multiplication > per index). Is that cheaper than copying all the pointers to a new > list? ?For sorting, you definitely need to construct a lookup table > since the sort algorithm needs to look over the indices multiple > times, which means you are using two pointer indirections per index. > Is that cheaper than just copying all the pointers to a new list? Even > if there is any benefit at all, you'll need to implement listagent in > C to squeeze it out. > > However, using listagents is faster if you just want a few items out > of the slice. And it's cute. Well, it doesn't really need to be any slower than a normal list. You only need to use index and do extra additions because it's in python. However, if listagent were written in C, you would just have a pointer into the contents of the original list, and the length, which is all that list itself has. I don't actually expect you to write that, I'm just pointing it out. As for copying pointers not taking much time... that depends on how long the list is. if you are working with small sets of data, you can do almost anything and it will be efficient. However, if you have megabytes or gigabytes of data (say you are working with images or video), than the difference between an O(1) or an O(n) operation is a big deal. I agree though, it doesn't matter to everyone and anyone. The reason I was interested was because i was trying to solve some specific problems in an elegant way. I was thinking it would be cool to make python more usable in programming competitions by giving it its own port of the STL's algorithm library, which needs something along the lines of C++'s more powerful iterators. From alan.isaac at gmail.com Thu Dec 17 15:18:12 2009 From: alan.isaac at gmail.com (Alan G Isaac) Date: Thu, 17 Dec 2009 15:18:12 -0500 Subject: Raw string substitution problem In-Reply-To: References: <931375.44828.qm@web58902.mail.re1.yahoo.com> <2I-dnaKkY7MM_LfWnZ2dnUVZ_sGdnZ2d@rcn.net> Message-ID: On 12/17/2009 2:45 PM, MRAB wrote: > re.compile('a\\nc') _does_ compile to the same as regex as > re.compile('a\nc'). > > However, regex objects never compare equal to each other, so, strictly > speaking, re.compile('a\nc') != re.compile('a\nc'). > > However, having said that, the re module contains a cache (keyed on the > string and options supplied), so the first re.compile('a\nc') will put > the regex object in the cache and the second re.compile('a\nc') will > return that same regex object from the cache. If you clear the cache in > between the two calls (do re._cache.clear()) you'll get two different > regex objects which won't compare equal even though they are to all > intents identical. OK, this is helpful. (I did check equality but did not understand I got True only because re used caching.) So is the bottom line the following? A string replacement is not just "converted" as described in the documentation, essentially it is compiled? But that cannot quite be right. E.g., \b will be a back space not a word boundary. So then the question arises again, why isn't '\\' a backslash? Just because? Why does it not get the "obvious" conversion? Thanks, Alan Isaac From Eric_Dexter at msn.com Thu Dec 17 15:21:42 2009 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: Thu, 17 Dec 2009 12:21:42 -0800 (PST) Subject: I have a cross platform os.startfile but I need to asociate files with xdg-open in linux how do I do that?? References: <0829f1b4-b9eb-442c-9b09-0b1c41622ca6@n13g2000vbe.googlegroups.com> <4fb87f04-b058-45a4-9c07-eceb35bdc657@f20g2000vbl.googlegroups.com> Message-ID: <39a4a58d-3ab1-4536-8620-88ce39826a2c@e27g2000yqd.googlegroups.com> On Dec 16, 3:02?pm, "Eric_Dex... at msn.com" wrote: > On Dec 16, 10:36?am, Paul Boddie wrote: > > > > > On 16 Des, 17:03, "Eric_Dex... at msn.com" wrote: > > > > #this should be a cross platform example of os.startfile ( startfile ) > > > #for windows and linux. ?this is the first version and > > > #linux, mac, other os's commands for exceptions to the > > > #rule would be appreciated. ?at some point this will be > > > #in the dex tracker project. > > > You could look at the desktop package for something similar: > > >http://pypi.python.org/pypi/desktop > > > The desktop.open function supports a few extra workarounds, mostly > > because it pre-dates xdg-open. > > > Paul > > "Since desktop environments like KDE and GNOME provide mechanisms for > running > browsers and editors according to the identified type of a file or > resource, > just as Windows "runs" files or resources, it is appropriate to have a > module > which accesses these mechanisms. It is this kind of functionality that > the > desktop package aims to support. Note that this approach is arguably > better" > > I am concerned this means I cant do something like associate python > files with python in artistx (ubuntu). ?It just associates text files > with editors?? ?It does look like a cool package and I will look into > that further. I suppose I could test the extension.. if '.py' in filename and then default to xdg-open if it isn't seems realy messy though. ______________________________ http://dextracker.blogspot.com From jjposner at optimum.net Thu Dec 17 15:28:37 2009 From: jjposner at optimum.net (John Posner) Date: Thu, 17 Dec 2009 15:28:37 -0500 Subject: How to create a self-destructing Tkinter dialog box? References: Message-ID: On Thu, 17 Dec 2009 02:09:03 -0500, Martin P. Hellwig wrote: > mrstevegross wrote: >> Ok, I would like to put together a Python/Tkinter dialog box that >> displays a simple message and self-destructs after N seconds. Is there >> a simple way to do this? >> Thanks, >> --Steve > > Just, thinking aloud, I probably would do something like registering the > [place|grid|pack]_forget() function by using the alarm callback > 'after()' function of that frame. > Yup, after() is your friend: #--------------------------- from Tkinter import * from functools import partial def RemoveWindow(win): win.destroy() # root window root = Tk() Label(root, text="this is the main window").pack() # another top-level window, to be removed in 2 seconds top = Toplevel() Label(top, text="this is the window to be removed").pack() root.after(2000, partial(RemoveWindow, top)) # go root.mainloop() #--------------------------- HTH, John From lists at cheimes.de Thu Dec 17 15:39:14 2009 From: lists at cheimes.de (Christian Heimes) Date: Thu, 17 Dec 2009 21:39:14 +0100 Subject: Which version of MSVC?90.DLL's to distribute with Python 2.6 based Py2exe executables? In-Reply-To: <0842d813-4cce-4283-8616-d90c7cbdabc2@a32g2000yqm.googlegroups.com> References: <0842d813-4cce-4283-8616-d90c7cbdabc2@a32g2000yqm.googlegroups.com> Message-ID: Jonathan Hartley wrote: > Only this week I sent a py2exe-derived executable to someone else (a > non-developer) and it would not run on their WinXP machine ("'The > system cannot execute the specified program'") - my current favourite > hypothesis is that my omission of this dll or something similar was to > blame. > > To diagnose what's wrong, I can't get access to the machine that gives > the above error. To try and reproduce, I'm right now in the process of > creating a bare-bones WindowsXP installed on a VM. MSVCR90 is a side-by-side assembly (SxS). You can't just copy a SxS assembly to another computer. You must at least ship the manifest file, too. The easiest way to get your program running is the installation of the MSVCR redistributable installer. Christian From rridge at csclub.uwaterloo.ca Thu Dec 17 15:44:23 2009 From: rridge at csclub.uwaterloo.ca (Ross Ridge) Date: Thu, 17 Dec 2009 15:44:23 -0500 Subject: Which version of MSVC?90.DLL's to distribute with Python 2.6 based Py2exe executables? References: <0842d813-4cce-4283-8616-d90c7cbdabc2@a32g2000yqm.googlegroups.com> Message-ID: Jonathan Hartley wrote: >1) I don't understand why the OP's question doesn't deserve a literal >answer ... I gave what I thought was a simple, direct and literal answer. >.. isn't one of those DLLs in the WinSxS directory derived from >his MSVC install? I have no idea. He might not even have Microsoft Visual C++ installed on his machine. >2) The required dlls come with Python? Whatwhatwhat? The DLLs are required for Python to work, so yes the DLLs are included in the official binary Python distribution for Windows. > Is this if I download Python source to compile myself? No, the DLLs aren't included in the source distribution. However, if you compile the Python source yourself with a suitably licenced copy of Microsoft Visual C++ then you'd be allowed to redistribute the Microsoft Runtime DLLs as a part of your own binary Python distribution. >2b) Presumably these runtimes must come with Visual Studio express >edition (the free one.) I'd assume so, but you should check the the terms of the EULA for that particular product to make sure it also allows you to redistribute the runtime DLLs. > I assume I can just prise the required DLL off my filesystem after >MSVS express edition has installed, rather than insisting that my users >run the MSVC runtime installer at It would problably simpler to use the DLL included in the "redist" subdirectory of Microsoft Visual C++ installation. That is, assumming there is one, again you'll need to check the EULA. Sometimes Microsoft makes specific requirements on how its redistributables are packaged and installed, and that definately seems to be the case with Visual C++ 2008. >4) The py2exe wiki says, of the msvc runtime dll version 7.1 (for >versions of Python prior to 2.6) that: > > "Since most Windows installations nowadays include this DLL by >default, it may be unnecessary." > >To what extent is this true? It's less true for newer versions of Windows. I know there are a fair number of people running Windows Vista and Windows 7 who've run into problems with my own py2exe wrapped program because their machines don't already have MSVCR71.DLL installed in their system directories. >Does the same not also apply to the msvc >runtime 9.0 dll? (for Python 2.6.4) I'd assume the problem would be even worse. I don't think Microsoft allows the 9.0 runtime to be installed in system directory, so the specific version of the runtime would need to be already installed the WinSxS directory. >Malcome said: >> (I assume I need just a matching pair of MSVCR90.DLL and MSVCP90.DLL?) > >5) Whatwhatwhat again? More than one DLL is required? Are there ever >any more than these two? The "P" DLL is for C++ and so the original poster may not actually need it. I'm pretty sure Python itself doesn't need it, and py2exe shouldn't either, but wxPython, or more precisely wxWidgets, almost certainly does. So in your case you'll probably need to redistribute both DLLs. Ross Ridge -- l/ // Ross Ridge -- The Great HTMU [oo][oo] rridge at csclub.uwaterloo.ca -()-/()/ http://www.csclub.uwaterloo.ca/~rridge/ db // From python at mrabarnett.plus.com Thu Dec 17 15:51:04 2009 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 17 Dec 2009 20:51:04 +0000 Subject: Raw string substitution problem In-Reply-To: References: <931375.44828.qm@web58902.mail.re1.yahoo.com> <2I-dnaKkY7MM_LfWnZ2dnUVZ_sGdnZ2d@rcn.net> Message-ID: <4B2A99B8.5040904@mrabarnett.plus.com> Alan G Isaac wrote: > On 12/17/2009 2:45 PM, MRAB wrote: >> re.compile('a\\nc') _does_ compile to the same as regex as >> re.compile('a\nc'). >> >> However, regex objects never compare equal to each other, so, strictly >> speaking, re.compile('a\nc') != re.compile('a\nc'). >> >> However, having said that, the re module contains a cache (keyed on the >> string and options supplied), so the first re.compile('a\nc') will put >> the regex object in the cache and the second re.compile('a\nc') will >> return that same regex object from the cache. If you clear the cache in >> between the two calls (do re._cache.clear()) you'll get two different >> regex objects which won't compare equal even though they are to all >> intents identical. > > > OK, this is helpful. > (I did check equality but did not understand > I got True only because re used caching.) > So is the bottom line the following? > A string replacement is not just "converted" > as described in the documentation, essentially > it is compiled? > > But that cannot quite be right. E.g., \b will be a back > space not a word boundary. So then the question arises > again, why isn't '\\' a backslash? Just because? > Why does it not get the "obvious" conversion? > If you give the re module a string containing \b, eg. '\\b' or r'\b', then it will compile it to a word boundary if it's in a regex string or a backspace if it's in a replacement string. This is different from giving the re module a string which actually contains a backspace, eg, '\b'. Because the re module uses backslashes for escaping, you'll need to escape a literal backslash with a backslash in the string you give it. But string literals also use backslashes for escaping, so you'll need to escape each of those backslashes with a backslash. From lucaberto at libero.it Thu Dec 17 15:59:08 2009 From: lucaberto at libero.it (luca72) Date: Thu, 17 Dec 2009 12:59:08 -0800 (PST) Subject: read from bin file Message-ID: <713dc4e7-9378-49cc-9393-1319b75a3a77@d10g2000yqh.googlegroups.com> I have a bin file that i read as: in_file = open('primo.ske', 'rb') leggo = luca.readlines() i get a list like : ['\x00\x80p\x8b\x00\x00\x01\x19\x9b\x11\xa1\xa1\x1f\xc9\x12\xaf\x81! \x84\x01\x00\x01\x01\x02\xff\xff\x80\x01\x03\xb0\x01\x01\x10m\x7f\n', etc...] but if i try to print luca[0] i get not the the string in the list but i get some like " ?{" how i can get a string like the string in the list? Thanks Luca From malaclypse2 at gmail.com Thu Dec 17 16:15:26 2009 From: malaclypse2 at gmail.com (Jerry Hill) Date: Thu, 17 Dec 2009 16:15:26 -0500 Subject: read from bin file In-Reply-To: <713dc4e7-9378-49cc-9393-1319b75a3a77@d10g2000yqh.googlegroups.com> References: <713dc4e7-9378-49cc-9393-1319b75a3a77@d10g2000yqh.googlegroups.com> Message-ID: <16651e80912171315u7650205eme8f02468d3133f5f@mail.gmail.com> On Thu, Dec 17, 2009 at 3:59 PM, luca72 wrote: > I have a bin file that i read as: > in_file = open('primo.ske', 'rb') > leggo = luca.readlines() > > i get a list like : > ['\x00\x80p\x8b\x00\x00\x01\x19\x9b\x11\xa1\xa1\x1f\xc9\x12\xaf\x81! > \x84\x01\x00\x01\x01\x02\xff\xff\x80\x01\x03\xb0\x01\x01\x10m\x7f\n', > etc...] > > but if i try to print ?luca[0] > i get not the the string in the list but i get some like " ?{" > how i can get a string like the string in the list? print repr(luca[0]) -- Jerry From chris at simplistix.co.uk Thu Dec 17 16:15:55 2009 From: chris at simplistix.co.uk (Chris Withers) Date: Thu, 17 Dec 2009 21:15:55 +0000 Subject: subprocess.Popen and ordering writes to stdout and stderr Message-ID: <4B2A9F8B.6090704@simplistix.co.uk> Hi All, I have this simple function: def execute(command): process = Popen(command.split(),stderr=STDOUT,stdout=PIPE) return process.communicate()[0] ..but my unit test for it fails: from testfixtures import tempdir,compare from unittest import TestCase class TestExecute(TestCase): @tempdir() def test_out_and_err(self,d): path = d.write('test.py','\n'.join(( "import sys", "sys.stdout.write('stdout\\n')", "sys.stderr.write('stderr\\n')", "sys.stdout.write('stdout2\\n')", )),path=True) compare('stdout\nstderr\nstdout2\n', execute(sys.executable+' '+path)) ...because: AssertionError: @@ -1,4 +1,4 @@ -stdout -stderr -stdout2 +stdout +stdout2 +stderr ...the order of the writes isn't preserved. How can I get this to be the case? Chris -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk From aioe.org at technicalbloke.com Thu Dec 17 16:24:12 2009 From: aioe.org at technicalbloke.com (r0g) Date: Thu, 17 Dec 2009 21:24:12 +0000 Subject: ftplib timeout in Python 2.4 References: Message-ID: Nico Grubert wrote: >> I don't know of one so you may need a workaround. What platforms do you >> need to support? > > Suse Linux Enterprise 10, 64 Bit with Python 2.4.4. > I need the Python 2.4.4 for a running application Server (Zope). OK, then one approach would be to use signals.alarm(timeout) to raise SIGALRM and break out of your FTP function. Have a look at the example at the very bottom of... http://docs.python.org/library/signal.html Roger. From exarkun at twistedmatrix.com Thu Dec 17 16:49:44 2009 From: exarkun at twistedmatrix.com (exarkun at twistedmatrix.com) Date: Thu, 17 Dec 2009 21:49:44 -0000 Subject: subprocess.Popen and ordering writes to stdout and stderr In-Reply-To: <4B2A9F8B.6090704@simplistix.co.uk> References: <4B2A9F8B.6090704@simplistix.co.uk> Message-ID: <20091217214944.15596.34509175.divmod.xquotient.420@localhost.localdomain> On 09:15 pm, chris at simplistix.co.uk wrote: >Hi All, > >I have this simple function: > >def execute(command): > process = Popen(command.split(),stderr=STDOUT,stdout=PIPE) > return process.communicate()[0] > >..but my unit test for it fails: > >from testfixtures import tempdir,compare >from unittest import TestCase > >class TestExecute(TestCase): > > @tempdir() > def test_out_and_err(self,d): > path = d.write('test.py','\n'.join(( > "import sys", > "sys.stdout.write('stdout\\n')", > "sys.stderr.write('stderr\\n')", > "sys.stdout.write('stdout2\\n')", > )),path=True) > compare('stdout\nstderr\nstdout2\n', > execute(sys.executable+' '+path)) > >...because: > >AssertionError: >@@ -1,4 +1,4 @@ >-stdout >-stderr >-stdout2 >+stdout >+stdout2 >+stderr > >...the order of the writes isn't preserved. >How can I get this to be the case? You probably just need to flush stdout and stderr after each write. You set them up to go to the same underlying file descriptor, but they still each have independent buffering on top of that. Jean-Paul From chris at simplistix.co.uk Thu Dec 17 16:56:54 2009 From: chris at simplistix.co.uk (Chris Withers) Date: Thu, 17 Dec 2009 21:56:54 +0000 Subject: subprocess.Popen and ordering writes to stdout and stderr In-Reply-To: <20091217214944.15596.34509175.divmod.xquotient.420@localhost.localdomain> References: <4B2A9F8B.6090704@simplistix.co.uk> <20091217214944.15596.34509175.divmod.xquotient.420@localhost.localdomain> Message-ID: <4B2AA926.9060007@simplistix.co.uk> exarkun at twistedmatrix.com wrote: >> How can I get this to be the case? > > You probably just need to flush stdout and stderr after each write. You > set them up to go to the same underlying file descriptor, but they still > each have independent buffering on top of that. Okay, but if I do: os.system(sys.executable+' '+path) ...with test.py as-is, I get things in the correct order. How come? Chris -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk From exarkun at twistedmatrix.com Thu Dec 17 17:17:06 2009 From: exarkun at twistedmatrix.com (exarkun at twistedmatrix.com) Date: Thu, 17 Dec 2009 22:17:06 -0000 Subject: subprocess.Popen and ordering writes to stdout and stderr In-Reply-To: <4B2AA926.9060007@simplistix.co.uk> References: <4B2A9F8B.6090704@simplistix.co.uk> <20091217214944.15596.34509175.divmod.xquotient.420@localhost.localdomain> <4B2AA926.9060007@simplistix.co.uk> Message-ID: <20091217221706.15596.1851075391.divmod.xquotient.427@localhost.localdomain> On 09:56 pm, chris at simplistix.co.uk wrote: >exarkun at twistedmatrix.com wrote: >>>How can I get this to be the case? >> >>You probably just need to flush stdout and stderr after each write. >>You set them up to go to the same underlying file descriptor, but they >>still each have independent buffering on top of that. > >Okay, but if I do: > >os.system(sys.executable+' '+path) > >...with test.py as-is, I get things in the correct order. libc is probably giving you line buffering when you use os.system (because the child process inherits the parent's stdio, and the parent's stdio is probably a pty, and that's the policy libc implements). When you use subprocess.Popen, the child process gets a pipe (ie, not a pty) for its stdout/err, and libc gives you block buffering instead. This makes the difference, since your test writes all end with \n - flushing the libc buffer when it's in line buffered mode, but not otherwise. Try the os.system version with the parent process's stdio not attached to a pty (say, 'cat | program | cat') or try giving the subprocess.Popen version a pty of its own (I'm not sure how you do this with subprocess.Popen, though). You should be able to observe the behavior change based on this. Jean-Paul From chris at simplistix.co.uk Thu Dec 17 17:33:53 2009 From: chris at simplistix.co.uk (Chris Withers) Date: Thu, 17 Dec 2009 22:33:53 +0000 Subject: subprocess.Popen and ordering writes to stdout and stderr In-Reply-To: <20091217221706.15596.1851075391.divmod.xquotient.427@localhost.localdomain> References: <4B2A9F8B.6090704@simplistix.co.uk> <20091217214944.15596.34509175.divmod.xquotient.420@localhost.localdomain> <4B2AA926.9060007@simplistix.co.uk> <20091217221706.15596.1851075391.divmod.xquotient.427@localhost.localdomain> Message-ID: <4B2AB1D1.7070806@simplistix.co.uk> exarkun at twistedmatrix.com wrote: > libc is probably giving you line buffering when you use os.system > (because the child process inherits the parent's stdio, and the parent's > stdio is probably a pty, and that's the policy libc implements). Interesting, but do these assertions still hold true when I tell you that I'm doing all this on Windows? ;-) Chris -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk From davea at ieee.org Thu Dec 17 17:50:36 2009 From: davea at ieee.org (Dave Angel) Date: Thu, 17 Dec 2009 17:50:36 -0500 Subject: read from bin file In-Reply-To: <16651e80912171315u7650205eme8f02468d3133f5f@mail.gmail.com> References: <713dc4e7-9378-49cc-9393-1319b75a3a77@d10g2000yqh.googlegroups.com> <16651e80912171315u7650205eme8f02468d3133f5f@mail.gmail.com> Message-ID: <4B2AB5BC.8080508@ieee.org> Jerry Hill wrote: > On Thu, Dec 17, 2009 at 3:59 PM, luca72 wrote: > >> I have a bin file that i read as: >> in_file =pen('primo.ske', 'rb') >> leggo =uca.readlines() >> >> i get a list like : >> ['\x00\x80p\x8b\x00\x00\x01\x19\x9b\x11\xa1\xa1\x1f\xc9\x12\xaf\x81! >> \x84\x01\x00\x01\x01\x02\xff\xff\x80\x01\x03\xb0\x01\x01\x10m\x7f\n', >> etc...] >> >> but if i try to print luca[0] >> i get not the the string in the list but i get some like " ?{" >> how i can get a string like the string in the list? >> > > print repr(luca[0]) > > You have several questions there. First, readlines() doesn't make sense if the file is binary. Unless you know that \n happens to be a delimiter in that particular formatted file, it makes more sense to just use read(), rather than readlines(). And in that case, you get a single string. You can specify how many bytes you want to read() each time. Now when you print a list, print calls repr() on each item in the list. So Jerry is right that repr() is the direct answer to your question. However, you may want a prettier output, such as that produced by binascii.hexlify(). A traditional dump file has hex bytes on one side, and printable characters on the other, with suitable spacing and such. DaveA From skippy.hammond at gmail.com Thu Dec 17 18:16:14 2009 From: skippy.hammond at gmail.com (Mark Hammond) Date: Fri, 18 Dec 2009 10:16:14 +1100 Subject: Which version of MSVC?90.DLL's to distribute with Python 2.6 based Py2exe executables? In-Reply-To: References: <0842d813-4cce-4283-8616-d90c7cbdabc2@a32g2000yqm.googlegroups.com> Message-ID: <4B2ABBBE.7080507@gmail.com> On 18/12/2009 7:44 AM, Ross Ridge wrote: > The "P" DLL is for C++ and so the original poster may not actually need > it. I'm pretty sure Python itself doesn't need it, and py2exe shouldn't > either, but wxPython, or more precisely wxWidgets, almost certainly does. > So in your case you'll probably need to redistribute both DLLs. FYI, my experience is that an entire manifest must be distributed. As the manifest in question actually lists 3 DLLs, IIUC, you must ship all 4 files - the 3 DLLs and the manifest, even if only one of the DLLs is actually used. This is from memory some time back though, so apologies in advance if I'm mis-remembering. Mark From skippy.hammond at gmail.com Thu Dec 17 18:23:33 2009 From: skippy.hammond at gmail.com (Mark Hammond) Date: Fri, 18 Dec 2009 10:23:33 +1100 Subject: subprocess.Popen and ordering writes to stdout and stderr In-Reply-To: <4B2AB1D1.7070806@simplistix.co.uk> References: <4B2A9F8B.6090704@simplistix.co.uk> <20091217214944.15596.34509175.divmod.xquotient.420@localhost.localdomain> <4B2AA926.9060007@simplistix.co.uk> <20091217221706.15596.1851075391.divmod.xquotient.427@localhost.localdomain> <4B2AB1D1.7070806@simplistix.co.uk> Message-ID: <4B2ABD75.9070805@gmail.com> On 18/12/2009 9:33 AM, Chris Withers wrote: > exarkun at twistedmatrix.com wrote: >> libc is probably giving you line buffering when you use os.system >> (because the child process inherits the parent's stdio, and the >> parent's stdio is probably a pty, and that's the policy libc implements). > > > > Interesting, but do these assertions still hold true when I tell you > that I'm doing all this on Windows? ;-) Yep. You can see similar behaviour from just the cmd-prompt and the following script: -- import sys for i in range(10): print "stdout" print >> sys.stderr, "stderr" -- If you execute it "normally" from a command-prompt, you will see things written in the correct order. If you execute it like 'python foo.py > out 2>&1', the order will be mixed up. If you execute it like 'python -u foo.py > out 2>&1' the order is restored. HTH, Mark From tjreedy at udel.edu Thu Dec 17 18:58:36 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 17 Dec 2009 18:58:36 -0500 Subject: subprocess.Popen and ordering writes to stdout and stderr In-Reply-To: <4B2AB1D1.7070806@simplistix.co.uk> References: <4B2A9F8B.6090704@simplistix.co.uk> <20091217214944.15596.34509175.divmod.xquotient.420@localhost.localdomain> <4B2AA926.9060007@simplistix.co.uk> <20091217221706.15596.1851075391.divmod.xquotient.427@localhost.localdomain> <4B2AB1D1.7070806@simplistix.co.uk> Message-ID: On 12/17/2009 5:33 PM, Chris Withers wrote: > exarkun at twistedmatrix.com wrote: >> libc is probably giving you line buffering when you use os.system >> (because the child process inherits the parent's stdio, and the >> parent's stdio is probably a pty, and that's the policy libc implements). > > > > Interesting, but do these assertions still hold true when I tell you > that I'm doing all this on Windows? ;-) Which version /-)? You can *fix* the test by sorting before comparing. If the app really requires synchronization of streams, I would just flush when needed and see if that were enough. tjr From rhodri at wildebst.demon.co.uk Thu Dec 17 19:59:12 2009 From: rhodri at wildebst.demon.co.uk (Rhodri James) Date: Fri, 18 Dec 2009 00:59:12 -0000 Subject: Raw string substitution problem References: <931375.44828.qm@web58902.mail.re1.yahoo.com> <2I-dnaKkY7MM_LfWnZ2dnUVZ_sGdnZ2d@rcn.net> Message-ID: On Thu, 17 Dec 2009 20:18:12 -0000, Alan G Isaac wrote: > So is the bottom line the following? > A string replacement is not just "converted" > as described in the documentation, essentially > it is compiled? That depends entirely on what you mean. > But that cannot quite be right. E.g., \b will be a back > space not a word boundary. So then the question arises > again, why isn't '\\' a backslash? Just because? > Why does it not get the "obvious" conversion? '\\' *is* a backslash. That string containing a single backslash is then processed by the re module which sees a backslash, tries to interpret it as an escape, fails and barfs. "re.compile('a\\nc')" passes a sequence of four characters to re.compile: 'a', '\', 'n' and 'c'. re.compile() then does it's own interpretation: 'a' passes through as is, '\' flags an escape which combined with 'n' produces the newline character (0x0a), and 'c' passes through as is. "re.compile('a\nc')" by contrast passes a sequence of three character to re.compile: 'a', 0x0a and 'c'. re.compile() does it's own interpretation, which happens not to change any of the characters, resulting in the same regular expression as before. Your problem is that you are conflating the compile-time processing of string literals with the run-time processing of strings specific to re. -- Rhodri James *-* Wildebeeste Herder to the Masses From nobody at nowhere.com Thu Dec 17 20:00:36 2009 From: nobody at nowhere.com (Nobody) Date: Fri, 18 Dec 2009 01:00:36 +0000 Subject: Seek support for new slice syntax PEP. References: <8e5054b1-8424-4633-a52e-1d9dcd1637b6@c34g2000yqn.googlegroups.com> Message-ID: On Mon, 14 Dec 2009 14:18:49 -0500, Terry Reedy wrote: > Many more people uses range objects (xrange in 2.x). A range object has > the same info as a slice object *plus* it is iterable. This isn't quite true, as a range cannot have a stop value of None, i.e. you can't represent [n:] or [:] etc as a range. Similarly for using negative stop values for indices relative to the end of the sequence being sliced. Also, aside from the semantics of slice objects themselves, slice notation isn't limited to a single slice object; it can also return a tuple of slices and values, e.g.: > numpy.s_[1::2,...,3,4:5:6] (slice(1, None, 2), Ellipsis, 3, slice(4, 5, 6)) For a single slice, enumerating over a slice with an unspecified stop value would be equivalent to itertools.count(). Negative stop values won't work. For a multi-dimensional slice, with everything specified, you would probably want to iterate over the cartesian product (i.e. N nested loops for an N-dimensional slice). But this won't work if anything other than the outermost loop has an unspecified stop value, or if you use an ellipsis within a slice. Oh, and being able to slice a slice could be quite useful, i.e.: [10:90:10][2::2] == [30:90:20] cf: > numpy.arange(100)[10:90:10][2::2] array([30, 50, 70]) > numpy.arange(100)[30:90:20] array([30, 50, 70]) From fitzpadj at tcd.ie Thu Dec 17 20:08:43 2009 From: fitzpadj at tcd.ie (seafoid) Date: Thu, 17 Dec 2009 17:08:43 -0800 (PST) Subject: Parsing file format to ensure file meets criteria Message-ID: <26837682.post@talk.nabble.com> Hi folks, I am new to python and am having some trouble parsing a file. I wish to parse a file and ensure that the format meets certain restrictions. The file format is as below (abbreviated): c this is a comment p wcnf 1468 817439 186181 286 32 0 186191 -198 -1098 0 186191 98 -1098 1123 0 Lines beginning c are comment lines and must precede all other lines. Lines beginning p are header lines with the numbers being 'nvar', 'nclauses' and 'hard' respectively. All other lines are clause lines. These must contain at least two integers followed by zero. There is no limit on the number of clause lines. Header lines must precede clause lines. In the above example: nvar = 1468 nclauses = 817439 hard = 186191 Now for the interesting part........... The first number in a clause line = weight. All else are literals. Therefore, clause = weight + literals weight <= hard |literal| > 0 |literal| <= nvar number of clause lines = nclauses My attempts thus far have been a dismal failure, computing is so viciously logical :confused: My main problem is that below: fname = raw_input('Please enter the name of the file: ') z = open(fname, 'r') z_list = [i.strip().split() for i in z] #here each line is converted to a list, all nested within a list - all elements of the list are strings, even integers are converted to strings Question - how are nested lists indexed? I then attempted to extract the comment, headers and clauses from the nested list and assign them to a variable. I tried: for inner in z_list: for lists in inner: if lists[0] == 'c': comment = lists[:] elif lists[0] == 'p': header = lists[:] else: clause = lists[:] print comment, header, clause This does not work for some reasons which I understand. I have messed up the indexing and my assignment of variables is wrong. The aim was to extract the headers and comments and then be left with a nested list of clauses. Then I intended to converted the strings within the clauses nested list back to integers and via indexing, check that all conditions are met. This would have involved also converting the numerical strings within the header to integers but the actual strings are proving a difficult problem to ignore. Any suggestions? If my mistakes are irritatingly stupid, please feel free to advise that I r.t.f.m (read the f**king manual). However, thus far the manual has helped me little. Thanking you, Seafoid. -- View this message in context: http://old.nabble.com/Parsing-file-format-to-ensure-file-meets-criteria-tp26837682p26837682.html Sent from the Python - python-list mailing list archive at Nabble.com. From python at mrabarnett.plus.com Thu Dec 17 20:42:56 2009 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 18 Dec 2009 01:42:56 +0000 Subject: Parsing file format to ensure file meets criteria In-Reply-To: <26837682.post@talk.nabble.com> References: <26837682.post@talk.nabble.com> Message-ID: <4B2ADE20.8060603@mrabarnett.plus.com> seafoid wrote: > Hi folks, > > I am new to python and am having some trouble parsing a file. > > I wish to parse a file and ensure that the format meets certain > restrictions. > > The file format is as below (abbreviated): > > c this is a comment > p wcnf 1468 817439 186181 > 286 32 0 > 186191 -198 -1098 0 > 186191 98 -1098 1123 0 > > Lines beginning c are comment lines and must precede all other lines. > > Lines beginning p are header lines with the numbers being 'nvar', 'nclauses' > and 'hard' respectively. > > All other lines are clause lines. These must contain at least two integers > followed by zero. There is no limit on the number of clause lines. > > Header lines must precede clause lines. > > In the above example: > nvar = 1468 > nclauses = 817439 > hard = 186191 > > Now for the interesting part........... > > The first number in a clause line = weight. > All else are literals. > Therefore, clause = weight + literals > > weight <= hard > |literal| > 0 > |literal| <= nvar > number of clause lines = nclauses > > My attempts thus far have been a dismal failure, computing is so viciously > logical :confused: > > My main problem is that below: > > fname = raw_input('Please enter the name of the file: ') > > z = open(fname, 'r') > > z_list = [i.strip().split() for i in z] > > #here each line is converted to a list, all nested within a list - all > elements of the list are strings, even integers are converted to strings > > Question - how are nested lists indexed? > A list is indexed by integers: >>> my_list = ['a', 'b', 'c'] >>> my_list[0] 'a' A list of lists requires 2 subscripts, one for the list and the other for the list in that list: >>> my_list = [['a', 'b'], ['c', 'd']] >>> my_list[0] ['a', 'b'] >>> my_list[0][1] 'b' > I then attempted to extract the comment, headers and clauses from the nested > list and assign them to a variable. > > I tried: > z_list is a list of lines, where each line is a list of words. For example, is the file contains: c this is a comment p wcnf 1468 817439 186181 then z_list contains: [['c', 'this', 'is', 'a', 'comment'], ['p', 'wcnf', '1468', '817439', '186181']] > for inner in z_list: > for lists in inner: > if lists[0] == 'c': > comment = lists[:] > elif lists[0] == 'p': > header = lists[:] > else: > clause = lists[:] > print comment, header, clause > > This does not work for some reasons which I understand. I have messed up the > indexing and my assignment of variables is wrong. > > The aim was to extract the headers and comments and then be left with a > nested list of clauses. > > Then I intended to converted the strings within the clauses nested list back > to integers and via indexing, check that all conditions are met. This would > have involved also converting the numerical strings within the header to > integers but the actual strings are proving a difficult problem to ignore. > > Any suggestions? > > If my mistakes are irritatingly stupid, please feel free to advise that I > r.t.f.m (read the f**king manual). However, thus far the manual has helped > me little. > From john at castleamber.com Thu Dec 17 20:57:36 2009 From: john at castleamber.com (John Bokma) Date: Thu, 17 Dec 2009 19:57:36 -0600 Subject: Parsing file format to ensure file meets criteria References: Message-ID: <874onpdoxb.fsf@castleamber.com> seafoid writes: > Hi folks, > > I am new to python and am having some trouble parsing a file. It really sounds like you need something that generates a parser for you based on a grammar instead of trying to code your own parser. See: http://wiki.python.org/moin/LanguageParsing for an overview of modules. -- John Bokma Read my blog: http://johnbokma.com/ Hire me (Perl/Python): http://castleamber.com/ From fitzpadj at tcd.ie Thu Dec 17 21:01:05 2009 From: fitzpadj at tcd.ie (seafoid) Date: Thu, 17 Dec 2009 18:01:05 -0800 (PST) Subject: Parsing file format to ensure file meets criteria In-Reply-To: <4B2ADE20.8060603@mrabarnett.plus.com> References: <26837682.post@talk.nabble.com> <4B2ADE20.8060603@mrabarnett.plus.com> Message-ID: <26838085.post@talk.nabble.com> MRAB-2 Thank you for that! Funny how something so simple clarifies a whole lot! I will crack on now! Once again, Cheers and Thanks! -- View this message in context: http://old.nabble.com/Parsing-file-format-to-ensure-file-meets-criteria-tp26837682p26838085.html Sent from the Python - python-list mailing list archive at Nabble.com. From fitzpadj at tcd.ie Thu Dec 17 21:08:32 2009 From: fitzpadj at tcd.ie (seafoid) Date: Thu, 17 Dec 2009 18:08:32 -0800 (PST) Subject: Parsing file format to ensure file meets criteria In-Reply-To: <874onpdoxb.fsf@castleamber.com> References: <26837682.post@talk.nabble.com> <874onpdoxb.fsf@castleamber.com> Message-ID: <26838132.post@talk.nabble.com> Hi John, I considered that, but in an attempt to really figure out this supposedly simple language, I figure that I should try and solve this. I will check out the modules for future reference. Thanks, Seafoid :-) -- View this message in context: http://old.nabble.com/Parsing-file-format-to-ensure-file-meets-criteria-tp26837682p26838132.html Sent from the Python - python-list mailing list archive at Nabble.com. From nad at acm.org Thu Dec 17 21:25:54 2009 From: nad at acm.org (Ned Deily) Date: Thu, 17 Dec 2009 18:25:54 -0800 Subject: More stuff added to ch 2 of my programming intro References: <9127dff9-90eb-4a73-aa51-e644f5e4e5bf@r1g2000vbn.googlegroups.com> <88bab2c0-d27c-4081-a703-26b353b9ed71@9g2000yqa.googlegroups.com> <183af5d2-e157-4cd6-bec6-8997809e1f51@d21g2000yqn.googlegroups.com> Message-ID: In article , Mensanator wrote: > > That's the disk image for the OS X Python 3.1.1 installer. ? > > But it doesn't say whether that disk image is compatible with > Snow Leopard and I don't take such things for granted. That's a good point. There should be stated there somewhere about which operating systems are supported. For the record, 3.1.1 has been tested on 10.4, 10.5, and 10.6 and should work on 10.3.9. -- Ned Deily, nad at acm.org From steve at REMOVE-THIS-cybersource.com.au Thu Dec 17 21:44:08 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 18 Dec 2009 02:44:08 GMT Subject: iterators and views of lists References: <89604fb4-9dfa-45f1-a3df-f676cd4353ea@x5g2000prf.googlegroups.com> <87b87511-744c-450e-a024-976f8c57f032@15g2000prz.googlegroups.com> Message-ID: <00b47124$0$15654$c3e8da3@news.astraweb.com> On Thu, 17 Dec 2009 12:07:59 -0800, Brendan Miller wrote: > I was thinking it would be cool to make python more usable in > programming competitions by giving it its own port of the STL's > algorithm library, which needs something along the lines of C++'s more > powerful iterators. For the benefit of those of us who aren't C++ programmers, what do its iterators do that Python's don't? -- Steven From jussij at zeusedit.com Thu Dec 17 22:28:40 2009 From: jussij at zeusedit.com (JussiJ) Date: Thu, 17 Dec 2009 19:28:40 -0800 (PST) Subject: ANN: Zeus for Windows IDE Version 3.97a Message-ID: <3d34cada-bb2f-4cc1-826c-8c0fae29dd29@u1g2000pre.googlegroups.com> The latest 3.97a release of the Zeus for Windows IDE is now available: http://www.zeusedit.com/whatsnew.html Zeus is fully configurable, language neutral IDE. It comes pre-configured with Python syntax highlighting and code folding. It is also possible to write Zeus scripts using Python. Jussi Jumppanen Author: Zeus for Windows From phily05 at gmail.com Thu Dec 17 22:37:22 2009 From: phily05 at gmail.com (Phil) Date: Thu, 17 Dec 2009 19:37:22 -0800 (PST) Subject: imports in __init__.py Message-ID: I use distutils / setup.py to install 'packagename', where... /packagename __init__.py modulename.py modulename.py has a class named 'classname'. >From an arbitrary python module, I 'import packagename'. In said module, I want to use the 'classname' class from 'packagename.modulename', by doing 'packagename.classname(params)'. I have seen this done by having either 'import modulename' and/or 'from modulename import *' in 'packagename's __init__.py. I don't really know which one or combination of them would work, but I can't get it to work either way. Unless I am missing something, webpy does this with, among other things, its application class that is in application.py. From a new web app, you would just use web.application (params). I am using Python 3.1.1, although I don't think that should matter. Any help is appreciated. Thanks! From ben+python at benfinney.id.au Thu Dec 17 23:34:57 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 18 Dec 2009 15:34:57 +1100 Subject: imports in __init__.py References: Message-ID: <87y6l0zyq6.fsf@benfinney.id.au> Phil writes: > I use distutils / setup.py to install 'packagename', where... > /packagename > __init__.py > modulename.py > > modulename.py has a class named 'classname'. As per PEP 8, it's best if user-defined classes are named with TitleCase, so ?ClassName?. > From an arbitrary python module, I 'import packagename'. At that point, you have all the names that were defined within ?packagename?, available inside the namespace ?packagename?. Since ?modulename? is a module in that package, the module's namespace is available to you via ?packagename.modulename?. > In said module, I want to use the 'classname' class from > 'packagename.modulename', by doing 'packagename.classname(params)'. The name ?ClassName? is not in the namespace ?packagename?. It is in the namespace ?packagename.modulename?, so you'll need to access it there:: import packagename.modulename packagename.modulename.ClassName(params) You can import the class from that namespace explicitly:: from packagename.modulename import ClassName ClassName(params) or you can import the module from the package namespace:: from packagename import modulename modulename.ClassName(params) > I have seen this done by having either 'import modulename' and/or > 'from modulename import *' in 'packagename's __init__.py. Importing the module in the package would mean you would not have to import the module yourself when using the package; it would not change the qualification necessary of the namespace. Importing using the ?from foo import *? form is usually a bad idea, since it clobbers namespaces and makes it impossible to tell by looking at the import code where the name ?ClassName? appeared from. Best to import only explicit names, as above. If you want to abbreviate, you can use the ability to rename while importing:: import packagename.modulename as foo foo.ClassName(params) which keeps the names explicit and traceable. -- \ ?Give a man a fish, and you'll feed him for a day; give him a | `\ religion, and he'll starve to death while praying for a fish.? | _o__) ?Anonymous | Ben Finney From phily05 at gmail.com Fri Dec 18 00:04:11 2009 From: phily05 at gmail.com (Phil) Date: Thu, 17 Dec 2009 21:04:11 -0800 (PST) Subject: imports in __init__.py References: <87y6l0zyq6.fsf@benfinney.id.au> Message-ID: <910b03ef-0e72-471b-b331-0f9ad40c6015@u20g2000vbq.googlegroups.com> I understand all of the above, including the reasons as to why this is bad. For purposes of experimenting, I would still like to do it. I guess I'm (still) wondering how it is done in webpy. I recall seeing it done elsewhere too. All I noticed was that in webpy's package 'web', it defines the 'application' class in 'application.py'. And in web's __init__.py it has... from application import * And in whatever app you are creating, it has... import web app = web.application(params) That being said, I can't get similar functionality with my own package. Is there more to this? Within my package's __init__.py, I am unable to import a module from the package without an import error. Thanks again! From ryan at rfk.id.au Fri Dec 18 00:35:27 2009 From: ryan at rfk.id.au (Ryan Kelly) Date: Fri, 18 Dec 2009 16:35:27 +1100 Subject: ANN: withrestart 0.2.1 Message-ID: <1261114527.2759.4.camel@durian> Hi All, Apologies if you receive multiple copies of this, my python-announce posts don't seem to be making it through. I've just released a new python module called "withrestart". It's an attempted Pythonisation of the restart-based condition system of Common Lisp. Details are on PyPI: http://pypi.python.org/pypi/withrestart/0.2.1 For an introduction to conditions and restarts, see "Beyond Exception Handling" by Peter Seibel: http://www.gigamonkeys.com/book/beyond-exception-handling-conditions-and-restarts.html For a quick demo of the module in action, keep reading... Cheers, Ryan About withrestart: ------------------ Version: 0.2.1 Licence: MIT Source: http://github.com/rfk/withrestart withrestart is a Pythonisation (Lispers might rightly say "bastardisation") of the restart-based condition system of Common Lisp. It's designed to make error recovery simpler and easier by removing the assumption that unhandled errors must be fatal. A "restart" represents a named strategy for resuming execution of a function after the occurrence of an error. At any point during its execution a function can push a Restart object onto its call stack. If an exception occurs within the scope of that Restart, code higher-up in the call chain can invoke it to recover from the error and let the function continue execution. By providing several restarts, functions can offer several different strategies for recovering from errors. A "handler" represents a higher-level strategy for dealing with the occurrence of an error. It is conceptually similar to an "except" clause, in that one establishes a suite of Handler objects to be invoked if an error occurs during the execution of some code. There is, however, a crucial difference: handlers are executed without unwinding the call stack. They thus have the opportunity to take corrective action and then resume execution of whatever function raised the error. As an example, here's a function that doesn't like the number seven: def anything_but_seven(v): if v == 7: raise ValueError("Argh! A Seven!") return v And here's a function that can recover from the occurrence of a seven using the pre-defined restarts "skip" and "use_value": def sum_items(items): total = 0 for i in items: with restarts(skip,use_value) as invoke: total += invoke(anything_but_seven,i) return total Naively calling this will raise a ValueError: >>> sum_items(range(8)) Traceback (most recent call last): ... ValueError: Argh! A Seven! >>> But if we handle ValueErrors by invoking the "skip" restart, we can still get the sum of the remaining items: >>> with Handler(ValueError,"skip"): ... sum_items(range(8)) ... 21 >>> Alternately, we can invoke the "use_value" restart to replace the sevens with another value: >>> with Handler(ValueError,"use_value",12): ... sum_items(range(8)) ... 33 >>> By splitting the responsibility for error recovery between Handlers and Restarts, we can cleanly separate the low-level mechanics of recovering from an error from the high-level decisions about what sort of recovery to perform. -- Ryan Kelly http://www.rfk.id.au | This message is digitally signed. Please visit ryan at rfk.id.au | http://www.rfk.id.au/ramblings/gpg/ for details -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 197 bytes Desc: This is a digitally signed message part URL: From catphive at catphive.net Fri Dec 18 01:00:20 2009 From: catphive at catphive.net (Brendan Miller) Date: Thu, 17 Dec 2009 22:00:20 -0800 Subject: iterators and views of lists In-Reply-To: <00b47124$0$15654$c3e8da3@news.astraweb.com> References: <89604fb4-9dfa-45f1-a3df-f676cd4353ea@x5g2000prf.googlegroups.com> <87b87511-744c-450e-a024-976f8c57f032@15g2000prz.googlegroups.com> <00b47124$0$15654$c3e8da3@news.astraweb.com> Message-ID: On Thu, Dec 17, 2009 at 6:44 PM, Steven D'Aprano wrote: > On Thu, 17 Dec 2009 12:07:59 -0800, Brendan Miller wrote: > >> I was thinking it would be cool to make python more usable in >> programming competitions by giving it its own port of the STL's >> algorithm library, which needs something along the lines of C++'s more >> powerful iterators. > > For the benefit of those of us who aren't C++ programmers, what do its > iterators do that Python's don't? Python iterators basically only have one operation: next(), which returns the next element or throws StopIteration. In C++ terminology this is a Input iterator. It is good for writing "for each" loops or map reduce operations. An input iterator can't mutate the data it points to. C++ also has progressively stronger iterators: http://www.sgi.com/tech/stl/Iterators.html InputIterator <- read only, one direction, single pass ForwardIterator <- read/write, one direction, multi pass BidirectionalIterator <- read/write, can move in either direction RandomAccessIterator <- read/write, can move in either direction by an arbitrary amount in constant time (as powerful as a pointer) Each only adds extra operations over the one before. So a RandomAccessIterator can be used anywhere a InputIterator can, but not vice versa. Also, this is a duck typing relationship, not a formal class inheritance. Anything that quacks like a RandomAccessIterator is a RandomAccessIterator, but there is no actual RandomAccessIterator class. So, for instance stl sort function takes pair of random access iterator delimiting a range, and can sort any datastructure that can provide that powerful of an iterator (arrays, vectors, deques). http://www.sgi.com/tech/stl/sort.html MyCollection stuff; // put some stuff in stuff sort(stuff.begin(), stuff.end()); Where begin() and end() by convention return iterators pointing to the beginning and end of the sequence. From s.selvamsiva at gmail.com Fri Dec 18 01:40:07 2009 From: s.selvamsiva at gmail.com (S.Selvam) Date: Fri, 18 Dec 2009 12:10:07 +0530 Subject: regex help In-Reply-To: <4B2915FD.9090405@arimaz.com> References: <4B2915FD.9090405@arimaz.com> Message-ID: On Wed, Dec 16, 2009 at 10:46 PM, Gabriel Rossetti < gabriel.rossetti at arimaz.com> wrote: > Hello everyone, > > I'm going nuts with some regex, could someone please show me what I'm doing > wrong? > > I have an XMPP msg : > > > > > 123 > 456 > > ... > > > > > the node may be absent or empty (), the node > may be absent. I'd like to grab everything exept the nod and > create something new using regex, with the XMPP message example above I'd > get this : > > > > > 123 > 456 > > > > > > for some reason my regex doesn't work correctly : > > r"().*?( .*?>).*?(?:(.*?)|)?.*?()?" > > If all you need is to remove payload node ,this could be useful, s1="123456..." pat=re.compile(r"") s1=pat.sub("",s1) -- Regards, S.Selvam -------------- next part -------------- An HTML attachment was scrubbed... URL: From vohsrea at gmail.com Fri Dec 18 02:48:11 2009 From: vohsrea at gmail.com (blumenkraft) Date: Thu, 17 Dec 2009 23:48:11 -0800 (PST) Subject: share dictionary between processes Message-ID: Hi, I want to share dictionary between two distinct processes. Something like this: first.py import magic_share_module def create_dictionary(): return {"a": 1} magic_share_module.share("shared_dictionary", creator.create_dictionary) while True: pass second.py import magic_share_module d = magic_share_module.get_shared("shared_dictionary") print d["a"] And then run in command line: python first.py & sleep 1 python second.py I have looked at POSH, but it requires master process that will fork childs. I want read-only sharing between completely unrelated processes. Is it possible? From greg.ewing at canterbury.ac.nz Fri Dec 18 02:51:56 2009 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Fri, 18 Dec 2009 20:51:56 +1300 Subject: Raw string substitution problem In-Reply-To: References: <931375.44828.qm@web58902.mail.re1.yahoo.com> <2I-dnaKkY7MM_LfWnZ2dnUVZ_sGdnZ2d@rcn.net> Message-ID: <7p0q09F6qiU1@mid.individual.net> MRAB wrote: > Regular expressions and replacement strings have their own escaping > mechanism, which also uses backslashes. This seems like a misfeature to me. It makes sense for a regular expression to give special meanings to backslash sequences, because it's a sublanguage with its own syntax. But I can't see any earthly reason to do that with the *replacement* string, which is just data. It looks like a feature that's been blindly copied over from Perl without thinking about whether it makes sense in Python. -- Greg From prakash.stack at gmail.com Fri Dec 18 03:00:59 2009 From: prakash.stack at gmail.com (prakash jp) Date: Fri, 18 Dec 2009 13:30:59 +0530 Subject: wrap exe with in another exe Message-ID: <805f59d50912180000h5cc1da5dw5a8e4116e61926d3@mail.gmail.com> Hi all, I need to call an external executable from my "calling_exe.py" python program. Can we make a executable say->"Final.exe" from the "calling_exe.py" and the "external.exe" * "calling_exe.py" ->(calling)-> "external.exe" | | ----------------------------------------------------------- (integrate using py2exe) || how should the setup.py file look like????? \||/ \/ "Final.exe" * *Regards* *Prakash* -------------- next part -------------- An HTML attachment was scrubbed... URL: From garabik-news-2005-05 at kassiopeia.juls.savba.sk Fri Dec 18 03:07:57 2009 From: garabik-news-2005-05 at kassiopeia.juls.savba.sk (garabik-news-2005-05 at kassiopeia.juls.savba.sk) Date: Fri, 18 Dec 2009 08:07:57 +0000 (UTC) Subject: share dictionary between processes References: Message-ID: blumenkraft wrote: > Hi, > > I want to share dictionary between two distinct processes. > ... > I have looked at POSH, but it requires master process that will fork > childs. I want read-only sharing between completely unrelated > processes. > Is it possible? Depends on your exact needs - dbm or shelve might be enough, especially for read only access. -- ----------------------------------------------------------- | Radovan Garab?k http://kassiopeia.juls.savba.sk/~garabik/ | | __..--^^^--..__ garabik @ kassiopeia.juls.savba.sk | ----------------------------------------------------------- Antivirus alert: file .signature infected by signature virus. Hi! I'm a signature virus! Copy me into your signature file to help me spread! From michele.simionato at gmail.com Fri Dec 18 03:10:01 2009 From: michele.simionato at gmail.com (Michele Simionato) Date: Fri, 18 Dec 2009 00:10:01 -0800 (PST) Subject: share dictionary between processes References: Message-ID: <9e3a2ea0-f811-4c25-8614-5677ee6ea3ed@b15g2000yqd.googlegroups.com> On Dec 18, 8:48?am, blumenkraft wrote: > Hi, > > I want to share dictionary between two distinct processes. > > Something like this: > > first.py > import magic_share_module > > def create_dictionary(): > ? ? return {"a": 1} > > magic_share_module.share("shared_dictionary", > creator.create_dictionary) > while True: > ? ? ?pass > > second.py > import magic_share_module > d = magic_share_module.get_shared("shared_dictionary") > print d["a"] > > And then run in command line: > python first.py & > sleep 1 > python second.py > > I have looked at POSH, but it requires master process that will fork > childs. I want read-only sharing between completely unrelated > processes. > Is it possible? Yes, see http://docs.python.org/library/multiprocessing.html From casevh at gmail.com Fri Dec 18 03:17:38 2009 From: casevh at gmail.com (casevh) Date: Fri, 18 Dec 2009 00:17:38 -0800 (PST) Subject: PyArg_ParseTupleAndKeywords in Python3.1 References: <0a0b822c-8d57-4816-8563-5fd8ff39f7f1@p8g2000yqb.googlegroups.com> <83f08b89-6b61-4005-9fbd-c9a01da36654@d9g2000prh.googlegroups.com> <408e4acd-3182-4d08-bcb4-d4ff1632d9c2@l13g2000yqb.googlegroups.com> <2a0f6103-3615-4d6a-bd6c-e0bfcbf37eb6@26g2000yqo.googlegroups.com> Message-ID: On Dec 17, 11:14?am, Joachim Dahl wrote: > In the Ubuntu 9.10 version of Python 3.1 (using your patch), there's a > related bug: > > >>> foo(b='b') > > will set the value of a in the extension module to zero, thus clearing > whatever > default value it may have had. ?In other words, the optional character > arguments > that are skipped seem to be nulled by PyArg_ParseTupleAndKeywords(). The following code seems to work fine for me: static PyObject* foo(PyObject *self, PyObject *args, PyObject *kwrds) { int a=65, b=66; char *kwlist[] = {"a", "b", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwrds, "|CC", kwlist, &a, &b)) return NULL; return Py_BuildValue("(CC)", a, b); } The default values seem to remain as 'A' and 'B'. >>> foo() ('A', 'B') >>> foo(b='b') ('A', 'b') >>> foo() ('A', 'B') >>> foo('a') ('a', 'B') >>> foo('a', b='b') ('a', 'b') >>> foo() ('A', 'B') >>> casevh From news123 at free.fr Fri Dec 18 03:35:11 2009 From: news123 at free.fr (News123) Date: Fri, 18 Dec 2009 09:35:11 +0100 Subject: share dictionary between processes In-Reply-To: <9e3a2ea0-f811-4c25-8614-5677ee6ea3ed@b15g2000yqd.googlegroups.com> References: <9e3a2ea0-f811-4c25-8614-5677ee6ea3ed@b15g2000yqd.googlegroups.com> Message-ID: <4b2b3ebf$0$30642$426a74cc@news.free.fr> Hi Michael, I'm new to the module multiprocessing, but at a first glance it seems, that multiprocessing.Value can only be shared if you create the second process from the first one. Id like to start the first process from the command line and much later the second process from the command line. Is this possible? thanks in advance and bye N Michele Simionato wrote: > On Dec 18, 8:48 am, blumenkraft wrote: >> Hi, >> >> I want to share dictionary between two distinct processes. >> >> Something like this: >> >> first.py >> import magic_share_module >> >> def create_dictionary(): >> return {"a": 1} >> >> magic_share_module.share("shared_dictionary", >> creator.create_dictionary) >> while True: >> pass >> >> second.py >> import magic_share_module >> d = magic_share_module.get_shared("shared_dictionary") >> print d["a"] >> >> And then run in command line: >> python first.py & >> sleep 1 >> python second.py >> >> I have looked at POSH, but it requires master process that will fork >> childs. I want read-only sharing between completely unrelated >> processes. >> Is it possible? > > Yes, see http://docs.python.org/library/multiprocessing.html From emekamicro at gmail.com Fri Dec 18 05:24:26 2009 From: emekamicro at gmail.com (Emeka) Date: Fri, 18 Dec 2009 10:24:26 +0000 Subject: Fwd: PyArg_ParseTupleAndKeywords in Python3.1 In-Reply-To: <89c38c820912180223gf116a20t8f411a7c2b8a41e1@mail.gmail.com> References: <0a0b822c-8d57-4816-8563-5fd8ff39f7f1@p8g2000yqb.googlegroups.com> <83f08b89-6b61-4005-9fbd-c9a01da36654@d9g2000prh.googlegroups.com> <408e4acd-3182-4d08-bcb4-d4ff1632d9c2@l13g2000yqb.googlegroups.com> <2a0f6103-3615-4d6a-bd6c-e0bfcbf37eb6@26g2000yqo.googlegroups.com> <89c38c820912180223gf116a20t8f411a7c2b8a41e1@mail.gmail.com> Message-ID: <89c38c820912180224uaeb3872l35710ff97dbd6cb5@mail.gmail.com> static PyObject* foo(PyObject *self, PyObject *args, PyObject *kwrds) { int a=65, b=66; char *kwlist[] = {"a", "b", NULL}; I am yet to understand what kwlist pointer does and why it is needed? if (!PyArg_ParseTupleAndKeywords(args, kwrds, "|CC", kwlist, &a, &b)) return NULL; return Py_BuildValue("(CC)", a, b); } Regards, Emeka The following code seems to work fine for me: static PyObject* foo(PyObject *self, PyObject *args, PyObject *kwrds) { int a=65, b=66; char *kwlist[] = {"a", "b", NULL}; I am yet to understand what kwlist pointer does and why it is needed? if (!PyArg_ParseTupleAndKeywords(args, kwrds, "|CC", kwlist, &a, &b)) return NULL; return Py_BuildValue("(CC)", a, b); } Regards, Emeka The default values seem to remain as 'A' and 'B' On Fri, Dec 18, 2009 at 8:17 AM, casevh wrote: > On Dec 17, 11:14 am, Joachim Dahl wrote: > > In the Ubuntu 9.10 version of Python 3.1 (using your patch), there's a > > related bug: > > > > >>> foo(b='b') > > > > will set the value of a in the extension module to zero, thus clearing > > whatever > > default value it may have had. In other words, the optional character > > arguments > > that are skipped seem to be nulled by PyArg_ParseTupleAndKeywords(). > > The following code seems to work fine for me: > > static PyObject* foo(PyObject *self, PyObject *args, PyObject *kwrds) > { > int a=65, b=66; > char *kwlist[] = {"a", "b", NULL}; > if (!PyArg_ParseTupleAndKeywords(args, kwrds, "|CC", kwlist, &a, > &b)) > return NULL; > return Py_BuildValue("(CC)", a, b); > } > > The default values seem to remain as 'A' and 'B'. > > >>> foo() > ('A', 'B') > >>> foo(b='b') > ('A', 'b') > >>> foo() > ('A', 'B') > >>> foo('a') > ('a', 'B') > >>> foo('a', b='b') > ('a', 'b') > >>> foo() > ('A', 'B') > >>> > > casevh > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From emekamicro at gmail.com Fri Dec 18 05:26:20 2009 From: emekamicro at gmail.com (Emeka) Date: Fri, 18 Dec 2009 10:26:20 +0000 Subject: PyArg_ParseTupleAndKeywords in Python3.1 In-Reply-To: References: <0a0b822c-8d57-4816-8563-5fd8ff39f7f1@p8g2000yqb.googlegroups.com> <83f08b89-6b61-4005-9fbd-c9a01da36654@d9g2000prh.googlegroups.com> <408e4acd-3182-4d08-bcb4-d4ff1632d9c2@l13g2000yqb.googlegroups.com> <2a0f6103-3615-4d6a-bd6c-e0bfcbf37eb6@26g2000yqo.googlegroups.com> Message-ID: <89c38c820912180226k6e692acl8089ef739655b464@mail.gmail.com> char *kwlist[] = {"a", "b", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwrds, "|CC", kwlist, &a, &b)) I am yet to understand what pointer kwlist[] does and why it is needed? Regards, Emeka On Fri, Dec 18, 2009 at 8:17 AM, casevh wrote: > On Dec 17, 11:14 am, Joachim Dahl wrote: > > In the Ubuntu 9.10 version of Python 3.1 (using your patch), there's a > > related bug: > > > > >>> foo(b='b') > > > > will set the value of a in the extension module to zero, thus clearing > > whatever > > default value it may have had. In other words, the optional character > > arguments > > that are skipped seem to be nulled by PyArg_ParseTupleAndKeywords(). > > The following code seems to work fine for me: > > static PyObject* foo(PyObject *self, PyObject *args, PyObject *kwrds) > { > int a=65, b=66; > char *kwlist[] = {"a", "b", NULL}; > if (!PyArg_ParseTupleAndKeywords(args, kwrds, "|CC", kwlist, &a, > &b)) > return NULL; > return Py_BuildValue("(CC)", a, b); > } > > The default values seem to remain as 'A' and 'B'. > > >>> foo() > ('A', 'B') > >>> foo(b='b') > ('A', 'b') > >>> foo() > ('A', 'B') > >>> foo('a') > ('a', 'B') > >>> foo('a', b='b') > ('a', 'b') > >>> foo() > ('A', 'B') > >>> > > casevh > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From thehcdreamer at gmail.com Fri Dec 18 06:05:48 2009 From: thehcdreamer at gmail.com (Oscar Del Ben) Date: Fri, 18 Dec 2009 03:05:48 -0800 (PST) Subject: Webpy and UnicodeDecodeError Message-ID: <5f704b6c-bc94-40cd-ae71-3d6b363e8c9e@p8g2000yqb.googlegroups.com> So I'm trying to send a file through webpy and urllib2 but I can't get around these UnicodeErrors. Here's the code: # controller x = web.input(video_original={}) params = {'foo': x['foo']} files = (('video[original]', 'test', x['video_original'].file.read ()),) client.upload(upload_url, params, files, access_token()) # client library def __encodeMultipart(self, fields, files): """ fields is a sequence of (name, value) elements for regular form fields. files is a sequence of (name, filename, value) elements for data to be uploaded as files Return (content_type, body) ready for httplib.HTTP instance """ boundary = mimetools.choose_boundary() crlf = '\r\n' l = [] for k, v in fields.iteritems(): l.append('--' + boundary) l.append('Content-Disposition: form-data; name="%s"' % k) l.append('') l.append(v) for (k, f, v) in files: l.append('--' + boundary) l.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (k, f)) l.append('Content-Type: %s' % self.__getContentType(f)) l.append('') l.append(v) l.append('--' + boundary + '--') l.append('') body = crlf.join(l) return boundary, body def __getContentType(self, filename): return mimetypes.guess_type(filename)[0] or 'application/octet- stream' def upload(self, path, post_params, files, token=None): if token: token = oauth.OAuthToken.from_string(token) url = "http://%s%s" % (self.authority, path) (boundary, body) = self.__encodeMultipart(post_params, files) headers = {'Content-Type': 'multipart/form-data; boundary=%s' % boundary, 'Content-Length': str(len(body)) } request = oauth.OAuthRequest.from_consumer_and_token( self.consumer, token, http_method='POST', http_url=url, parameters=post_params ) request.sign_request(oauth.OAuthSignatureMethod_HMAC_SHA1(), self.consumer, token) request = urllib2.Request(request.http_url, postdata=body, headers=headers) request.get_method = lambda: 'POST' return urllib2.urlopen(request) Unfortunately I get two kinds of unicode error, the first one in the crlf.join(l): Traceback (most recent call last): File "/Users/oscar/projects/work/whitelabel/web/application.py", line 242, in process return self.handle() File "/Users/oscar/projects/work/whitelabel/web/application.py", line 233, in handle return self._delegate(fn, self.fvars, args) File "/Users/oscar/projects/work/whitelabel/web/application.py", line 412, in _delegate return handle_class(cls) File "/Users/oscar/projects/work/whitelabel/web/application.py", line 387, in handle_class return tocall(*args) File "/Users/oscar/projects/work/whitelabel/code.py", line 328, in POST return simplejson.load(client.upload(upload_url, params, files, access_token())) File "/Users/oscar/projects/work/whitelabel/oauth_client.py", line 131, in upload (boundary, body) = self.__encodeMultipart(post_params, files) File "/Users/oscar/projects/work/whitelabel/oauth_client.py", line 111, in __encodeMultipart body = crlf.join(l) UnicodeDecodeError: 'ascii' codec can't decode byte 0xb7 in position 42: ordinal not in range(128) And here's another one: Traceback (most recent call last): File "/Users/oscar/projects/work/whitelabel/web/application.py", line 242, in process return self.handle() File "/Users/oscar/projects/work/whitelabel/web/application.py", line 233, in handle return self._delegate(fn, self.fvars, args) File "/Users/oscar/projects/work/whitelabel/web/application.py", line 412, in _delegate return handle_class(cls) File "/Users/oscar/projects/work/whitelabel/web/application.py", line 387, in handle_class return tocall(*args) File "/Users/oscar/projects/work/whitelabel/code.py", line 328, in POST return simplejson.load(client.upload(upload_url, params, files, access_token())) File "/Users/oscar/projects/work/whitelabel/oauth_client.py", line 131, in upload (boundary, body) = self.__encodeMultipart(post_params, files) File "/Users/oscar/projects/work/whitelabel/oauth_client.py", line 111, in __encodeMultipart body = crlf.join(l) UnicodeDecodeError: 'ascii' codec can't decode byte 0xb7 in position 42: ordinal not in range(128) Does anyone know why this errors happens and what I should do to prevent them? Many thanks. Oscar From ndbecker2 at gmail.com Fri Dec 18 07:12:15 2009 From: ndbecker2 at gmail.com (Neal Becker) Date: Fri, 18 Dec 2009 07:12:15 -0500 Subject: ANN: withrestart 0.2.1 References: <1261114527.2759.4.camel@durian> Message-ID: I haven't tried it, but it sounds really cool. I suppose I should expect a lot more overhead compared to try/except, since it's not built-in to python? From sylvain.thenault at logilab.fr Fri Dec 18 07:39:18 2009 From: sylvain.thenault at logilab.fr (Sylvain =?utf-8?B?VGjDqW5hdWx0?=) Date: Fri, 18 Dec 2009 13:39:18 +0100 Subject: [ANN] pylint 0.19 / astng 0.19.2 Message-ID: <20091218123918.GH24924@lupus.logilab.fr> Hi, I'm very pleased to announce the release of pylint 0.19 / astng 0.19.2 release! More information / download on http://www.logilab.org/project/pylint/0.19.0. This is a "community" release, including the work we've done during the pylint bug day [1] and patches mostly from James Lingard and Vincent Ferotin. Many thanks to James Lingard which provided two long waited features: * check of function call arguments * check string interpolation consistency So, happy christmas, enjoy! [1] http://www.logilab.org/blogentry/19260 -- Sylvain Th?nault LOGILAB, Paris (France) Formations Python, Debian, M?th. Agiles: http://www.logilab.fr/formations D?veloppement logiciel sur mesure: http://www.logilab.fr/services CubicWeb, the semantic web framework: http://www.cubicweb.org From nicogrubert at gmail.com Fri Dec 18 07:59:42 2009 From: nicogrubert at gmail.com (Nico Grubert) Date: Fri, 18 Dec 2009 13:59:42 +0100 Subject: ftplib timeout in Python 2.4 In-Reply-To: References: Message-ID: <4B2B7CBE.5080202@gmail.com> > Try the timelimited function from this recipe > > Works perfect! Thanks a lot, Jean! From aioe.org at technicalbloke.com Fri Dec 18 08:27:30 2009 From: aioe.org at technicalbloke.com (r0g) Date: Fri, 18 Dec 2009 13:27:30 +0000 Subject: share dictionary between processes References: Message-ID: blumenkraft wrote: > Hi, > > I want to share dictionary between two distinct processes. > > > Something like this: > > first.py > import magic_share_module > > def create_dictionary(): > return {"a": 1} > > magic_share_module.share("shared_dictionary", > creator.create_dictionary) > while True: > pass > > > second.py > import magic_share_module > d = magic_share_module.get_shared("shared_dictionary") > print d["a"] > > And then run in command line: > python first.py & > sleep 1 > python second.py > > I have looked at POSH, but it requires master process that will fork > childs. I want read-only sharing between completely unrelated > processes. > Is it possible? Depends if you need to have access to the object itself or merely look up values in it. If it's the latter you could start a thread in first.py that offers dictionary lookups via a specific UDP socket. Any number of subsequent progs and processes could then pitch up and lookup whatever values they like whenever they like. ~10 lines of code in first.py, maybe 5 in second.py Roger. From wentland at cl.uni-heidelberg.de Fri Dec 18 09:20:42 2009 From: wentland at cl.uni-heidelberg.de (Wolodja Wentland) Date: Fri, 18 Dec 2009 15:20:42 +0100 Subject: share dictionary between processes In-Reply-To: References: Message-ID: <20091218142042.GB5300@kinakuta.local> On Thu, Dec 17, 2009 at 23:48 -0800, blumenkraft wrote: > I want to share dictionary between two distinct processes. > Something like this: > > first.py > import magic_share_module > def create_dictionary(): > return {"a": 1} > > magic_share_module.share("shared_dictionary", > creator.create_dictionary) > while True: > pass Have a look at multiprocessing.Manager() it provides (among other things) proxies for dictionaries that can be used in different threads. These are even accessible on different hosts if configures correctly. -- .''`. Wolodja Wentland : :' : `. `'` 4096R/CAF14EFC `- 081C B7CD FF04 2BA9 94EA 36B2 8B7F 7D30 CAF1 4EFC -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 836 bytes Desc: Digital signature URL: From vs at it.uu.se Fri Dec 18 09:44:18 2009 From: vs at it.uu.se (Virgil Stokes) Date: Fri, 18 Dec 2009 15:44:18 +0100 Subject: Java-to-Python? Message-ID: <4B2B9542.1090106@it.uu.se> I have a rather large Java package for the analysis of networks that I would like to convert to Python. Many of the classes in the Java package are "Serializable". Any recommendations on Java-to-Python (2.6) would be appreciated. --V From cjwilliams43 at gmail.com Fri Dec 18 09:49:26 2009 From: cjwilliams43 at gmail.com (Colin W.) Date: Fri, 18 Dec 2009 09:49:26 -0500 Subject: Seek support for new slice syntax PEP. In-Reply-To: References: <8e5054b1-8424-4633-a52e-1d9dcd1637b6@c34g2000yqn.googlegroups.com> Message-ID: <4B2B9676.4070206@gmail.com> On 17-Dec-09 20:00 PM, Nobody wrote: > On Mon, 14 Dec 2009 14:18:49 -0500, Terry Reedy wrote: > >> Many more people uses range objects (xrange in 2.x). A range object has >> the same info as a slice object *plus* it is iterable. > > This isn't quite true, as a range cannot have a stop value of None, i.e. > you can't represent [n:] or [:] etc as a range. Similarly for using > negative stop values for indices relative to the end of the sequence being > sliced. > > Also, aside from the semantics of slice objects themselves, slice notation > isn't limited to a single slice object; it can also return a tuple of > slices and values, e.g.: > > > numpy.s_[1::2,...,3,4:5:6] > (slice(1, None, 2), Ellipsis, 3, slice(4, 5, 6)) > > For a single slice, enumerating over a slice with an unspecified stop > value would be equivalent to itertools.count(). Negative stop values won't > work. > > For a multi-dimensional slice, with everything specified, you would > probably want to iterate over the cartesian product (i.e. N nested loops > for an N-dimensional slice). But this won't work if anything other than > the outermost loop has an unspecified stop value, or if you use an > ellipsis within a slice. > > Oh, and being able to slice a slice could be quite useful, i.e.: > > [10:90:10][2::2] == [30:90:20] > > cf: > > numpy.arange(100)[10:90:10][2::2] > array([30, 50, 70]) > > numpy.arange(100)[30:90:20] > array([30, 50, 70]) > You don't say, but seem to imply that the slice components include None. Section 5.3.3 of the Python doc for 2.6.4 has The lower and upper bound expressions, if present, must evaluate to plain integers; defaults are zero and the sys.maxint, respectively. If either bound is negative, the sequence?s length is added to it. The slicing now selects all items with index k such that i <= k < j where i and j are the specified lower and upper bounds. This may be an empty sequence. It is not an error if i or j lie outside the range of valid indexes (such items don?t exist so they aren?t selected). Colin W. From cjwilliams43 at gmail.com Fri Dec 18 09:50:01 2009 From: cjwilliams43 at gmail.com (Colin W.) Date: Fri, 18 Dec 2009 09:50:01 -0500 Subject: Seek support for new slice syntax PEP. In-Reply-To: References: <8e5054b1-8424-4633-a52e-1d9dcd1637b6@c34g2000yqn.googlegroups.com> Message-ID: On 17-Dec-09 20:00 PM, Nobody wrote: > On Mon, 14 Dec 2009 14:18:49 -0500, Terry Reedy wrote: > >> Many more people uses range objects (xrange in 2.x). A range object has >> the same info as a slice object *plus* it is iterable. > > This isn't quite true, as a range cannot have a stop value of None, i.e. > you can't represent [n:] or [:] etc as a range. Similarly for using > negative stop values for indices relative to the end of the sequence being > sliced. > > Also, aside from the semantics of slice objects themselves, slice notation > isn't limited to a single slice object; it can also return a tuple of > slices and values, e.g.: > > > numpy.s_[1::2,...,3,4:5:6] > (slice(1, None, 2), Ellipsis, 3, slice(4, 5, 6)) > > For a single slice, enumerating over a slice with an unspecified stop > value would be equivalent to itertools.count(). Negative stop values won't > work. > > For a multi-dimensional slice, with everything specified, you would > probably want to iterate over the cartesian product (i.e. N nested loops > for an N-dimensional slice). But this won't work if anything other than > the outermost loop has an unspecified stop value, or if you use an > ellipsis within a slice. > > Oh, and being able to slice a slice could be quite useful, i.e.: > > [10:90:10][2::2] == [30:90:20] > > cf: > > numpy.arange(100)[10:90:10][2::2] > array([30, 50, 70]) > > numpy.arange(100)[30:90:20] > array([30, 50, 70]) > You don't say, but seem to imply that the slice components include None. Section 5.3.3 of the Python doc for 2.6.4 has The lower and upper bound expressions, if present, must evaluate to plain integers; defaults are zero and the sys.maxint, respectively. If either bound is negative, the sequence?s length is added to it. The slicing now selects all items with index k such that i <= k < j where i and j are the specified lower and upper bounds. This may be an empty sequence. It is not an error if i or j lie outside the range of valid indexes (such items don?t exist so they aren?t selected). Colin W. From casevh at gmail.com Fri Dec 18 10:02:04 2009 From: casevh at gmail.com (Case Vanhorsen) Date: Fri, 18 Dec 2009 07:02:04 -0800 Subject: PyArg_ParseTupleAndKeywords in Python3.1 In-Reply-To: <89c38c820912180226k6e692acl8089ef739655b464@mail.gmail.com> References: <0a0b822c-8d57-4816-8563-5fd8ff39f7f1@p8g2000yqb.googlegroups.com> <83f08b89-6b61-4005-9fbd-c9a01da36654@d9g2000prh.googlegroups.com> <408e4acd-3182-4d08-bcb4-d4ff1632d9c2@l13g2000yqb.googlegroups.com> <2a0f6103-3615-4d6a-bd6c-e0bfcbf37eb6@26g2000yqo.googlegroups.com> <89c38c820912180226k6e692acl8089ef739655b464@mail.gmail.com> Message-ID: <99e0b9530912180702p2de1a17p6f8f662dc2269c7b@mail.gmail.com> On Fri, Dec 18, 2009 at 2:26 AM, Emeka wrote: > ?? char *kwlist[] = {"a", "b", NULL}; > ? ?if (!PyArg_ParseTupleAndKeywords(args, kwrds, "|CC", kwlist, &a, > &b)) > I am yet to understand what pointer kwlist[] does and why it is needed? > Regards, > Emeka foo is designed to accept two arguments that can be specified by either position or name. kwlist contains the legal keyword names. In this example, the legal keywords are 'a' and 'b'. That they match the names of the C variables is just a lucky coincidence. If you want to change the keyword names to 'foo' and 'bar', you would just use char *kwlist[]={"foo", "bar", NULL}. casevh > > On Fri, Dec 18, 2009 at 8:17 AM, casevh wrote: >> >> On Dec 17, 11:14?am, Joachim Dahl wrote: >> > In the Ubuntu 9.10 version of Python 3.1 (using your patch), there's a >> > related bug: >> > >> > >>> foo(b='b') >> > >> > will set the value of a in the extension module to zero, thus clearing >> > whatever >> > default value it may have had. ?In other words, the optional character >> > arguments >> > that are skipped seem to be nulled by PyArg_ParseTupleAndKeywords(). >> >> The following code seems to work fine for me: >> >> static PyObject* foo(PyObject *self, PyObject *args, PyObject *kwrds) >> { >> ? ?int a=65, b=66; >> ? ?char *kwlist[] = {"a", "b", NULL}; >> ? ?if (!PyArg_ParseTupleAndKeywords(args, kwrds, "|CC", kwlist, &a, >> &b)) >> ? ? ? ?return NULL; >> ? ?return Py_BuildValue("(CC)", a, b); >> } >> >> The default values seem to remain as 'A' and 'B'. >> >> >>> foo() >> ('A', 'B') >> >>> foo(b='b') >> ('A', 'b') >> >>> foo() >> ('A', 'B') >> >>> foo('a') >> ('a', 'B') >> >>> foo('a', b='b') >> ('a', 'b') >> >>> foo() >> ('A', 'B') >> >>> >> >> casevh >> -- >> http://mail.python.org/mailman/listinfo/python-list > > From astan.chee at al.com.au Fri Dec 18 10:31:51 2009 From: astan.chee at al.com.au (Astan Chee) Date: Sat, 19 Dec 2009 02:31:51 +1100 Subject: Help with invoking standard mail app in windows Message-ID: <4B2BA067.5050204@al.com.au> Hi, I'm trying to launch standard mail app in windows and after looking around most look like this: import urllib, webbrowser, win32api def mailto_url(to=None,subject=None,body=None,cc=None): """ encodes the content as a mailto link as described on http://www.faqs.org/rfcs/rfc2368.html """ url = "mailto: " + urllib.quote(to.strip(),"@,") sep = "?" if cc: url+= sep + "cc=" + urllib.quote(cc,"@,") sep = "&" if subject: url+= sep + "subject=" + urllib.quote(subject,"") sep = "&" if body: # Also note that line breaks in the body of a message MUST be # encoded with "%0D%0A". (RFC 2368) body="\r\n".join(body.splitlines()) url+= sep + "body=" + urllib.quote(body,"") sep = "&" return url url = mailto_url(txtTo,txtSubject,body,txtCC) # win32api.ShellExecute(0,'open',url,None,None,0) webbrowser.open(url,new=1) # os.startfile(url) all of these are having "WindowsError : [Error 5] Access is denied" errors. I'm using windows xp and python 2.5. I have outlook 2007 installed as a default mail client. Clicking on any mailto links in html brings up the normal write mail from the mail client. Any ideas why this is happening or how do I debug what access is being denied? Thanks for any help Astan From steve at holdenweb.com Fri Dec 18 10:38:37 2009 From: steve at holdenweb.com (Steve Holden) Date: Fri, 18 Dec 2009 10:38:37 -0500 Subject: Eclipse Carriage Return Workaround Message-ID: I've written a Python 3 course that uses an Eclipse-based teaching system. The school is telling me that their version of Eclipse/pydev appears to have an input() function that appends a carriage return character to the user's input. This makes several things go screwy, as it's definitely not the way the standalone interpreter works, even on Windows. Can anyone think of a simple way work around this issue by overriding __builtins__.input() with a function that calls input() and then returns an rstrip()ped version of the input string? I though of setting a PYTHONSTARTUP environment variable, but that only affects interactive interpreter instances. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ UPCOMING EVENTS: http://holdenweb.eventbrite.com/ From fitzpadj at tcd.ie Fri Dec 18 10:42:19 2009 From: fitzpadj at tcd.ie (seafoid) Date: Fri, 18 Dec 2009 07:42:19 -0800 (PST) Subject: Line indexing in Python Message-ID: <26845253.post@talk.nabble.com> Hi Guys, When python reads in a file, can lines be referred to via an index? Example: for line in file: if line[0] == '0': a.write(line) This works, however, I am unsure if line[0] refers only to the first line or the first character in all lines. Is there an easy way to refer to a line with the first character being a single letter that you know? Thanks in advance, Seafoid. -- View this message in context: http://old.nabble.com/Line-indexing-in-Python-tp26845253p26845253.html Sent from the Python - python-list mailing list archive at Nabble.com. From davea at ieee.org Fri Dec 18 10:43:21 2009 From: davea at ieee.org (Dave Angel) Date: Fri, 18 Dec 2009 10:43:21 -0500 Subject: Webpy and UnicodeDecodeError In-Reply-To: <5f704b6c-bc94-40cd-ae71-3d6b363e8c9e@p8g2000yqb.googlegroups.com> References: <5f704b6c-bc94-40cd-ae71-3d6b363e8c9e@p8g2000yqb.googlegroups.com> Message-ID: <4B2BA319.2000008@ieee.org> Oscar Del Ben wrote: > So I'm trying to send a file through webpy and urllib2 but I can't get > around these UnicodeErrors. Here's the code: > > # controller > > x = web.input(video_original={}) > params = {'foo': x['foo']} > > files = (('video[original]', 'test', x['video_original'].file.read > ()),) > client.upload(upload_url, params, files, access_token()) > > # client library > > def __encodeMultipart(self, fields, files): > """ > fields is a sequence of (name, value) elements for regular > form fields. > files is a sequence of (name, filename, value) elements for > data to be uploaded as files > Return (content_type, body) ready for httplib.HTTP instance > """ > boundary = mimetools.choose_boundary() > crlf = '\r\n' > > l = [] > for k, v in fields.iteritems(): > l.append('--' + boundary) > l.append('Content-Disposition: form-data; name="%s"' % k) > l.append('') > l.append(v) > for (k, f, v) in files: > l.append('--' + boundary) > l.append('Content-Disposition: form-data; name="%s"; > filename="%s"' % (k, f)) > l.append('Content-Type: %s' % self.__getContentType(f)) > l.append('') > l.append(v) > l.append('--' + boundary + '--') > l.append('') > body = crlf.join(l) > > return boundary, body > > def __getContentType(self, filename): > return mimetypes.guess_type(filename)[0] or 'application/octet- > stream' > > def upload(self, path, post_params, files, token=None): > > if token: > token = oauth.OAuthToken.from_string(token) > > url = "http://%s%s" % (self.authority, path) > > (boundary, body) = self.__encodeMultipart(post_params, files) > > headers = {'Content-Type': 'multipart/form-data; boundary=%s' % > boundary, > 'Content-Length': str(len(body)) > } > > request = oauth.OAuthRequest.from_consumer_and_token( > self.consumer, > token, > http_method='POST', > http_url=url, > parameters=post_params > ) > > request.sign_request(oauth.OAuthSignatureMethod_HMAC_SHA1(), > self.consumer, token) > > request = urllib2.Request(request.http_url, postdata=body, > headers=headers) > request.get_method = lambda: 'POST' > > return urllib2.urlopen(request) > > Unfortunately I get two kinds of unicode error, the first one in the > crlf.join(l): > > Traceback (most recent call last): > File "/Users/oscar/projects/work/whitelabel/web/application.py", > line 242, in process > return self.handle() > File "/Users/oscar/projects/work/whitelabel/web/application.py", > line 233, in handle > return self._delegate(fn, self.fvars, args) > File "/Users/oscar/projects/work/whitelabel/web/application.py", > line 412, in _delegate > return handle_class(cls) > File "/Users/oscar/projects/work/whitelabel/web/application.py", > line 387, in handle_class > return tocall(*args) > File "/Users/oscar/projects/work/whitelabel/code.py", line 328, in > POST > return simplejson.load(client.upload(upload_url, params, files, > access_token())) > File "/Users/oscar/projects/work/whitelabel/oauth_client.py", line > 131, in upload > (boundary, body) = self.__encodeMultipart(post_params, files) > File "/Users/oscar/projects/work/whitelabel/oauth_client.py", line > 111, in __encodeMultipart > body = crlf.join(l) > UnicodeDecodeError: 'ascii' codec can't decode byte 0xb7 in position > 42: ordinal not in range(128) > > > And here's another one: > > Traceback (most recent call last): > File "/Users/oscar/projects/work/whitelabel/web/application.py", > line 242, in process > return self.handle() > File "/Users/oscar/projects/work/whitelabel/web/application.py", > line 233, in handle > return self._delegate(fn, self.fvars, args) > File "/Users/oscar/projects/work/whitelabel/web/application.py", > line 412, in _delegate > return handle_class(cls) > File "/Users/oscar/projects/work/whitelabel/web/application.py", > line 387, in handle_class > return tocall(*args) > File "/Users/oscar/projects/work/whitelabel/code.py", line 328, in > POST > return simplejson.load(client.upload(upload_url, params, files, > access_token())) > File "/Users/oscar/projects/work/whitelabel/oauth_client.py", line > 131, in upload > (boundary, body) = self.__encodeMultipart(post_params, files) > File "/Users/oscar/projects/work/whitelabel/oauth_client.py", line > 111, in __encodeMultipart > body = crlf.join(l) > UnicodeDecodeError: 'ascii' codec can't decode byte 0xb7 in position > 42: ordinal not in range(128) > > Does anyone know why this errors happens and what I should do to > prevent them? Many thanks. > > Oscar > > I did a short test to demonstrate the likely problem, without all the other libraries and complexity. lst = ["abc"] lst.append("def") lst.append(u"abc") lst.append("g\x48\x82\x94i") print lst print "**".join(lst) That fragment of code generates (in Python 2.6) the following output and traceback: ['abc', 'def', u'abc', 'gH\x82\x94i'] Traceback (most recent call last): File "M:\Programming\Python\sources\dummy\stuff2.py", line 10, in print "**".join(lst) UnicodeDecodeError: 'ascii' codec can't decode byte 0x82 in position 2: ordinal not in range(128) You'll notice that one of the strings is a unicode one, and another one has the character 0x82 in it. Once join() discovers Unicode, it needs to produce a Unicode string, and by default, it uses the ASCII codec to get it. If you print your 'l' list (bad name, by the way, looks too much like a '1'), you can see which element is Unicode, and which one has the \xb7 in position 42. You'll have to decide which is the problem, and solve it accordingly. Was the fact that one of the strings is unicode an oversight? Or did you think that all characters would be 0x7f or less? Or do you want to handle all possible characters, and if so, with what encoding? DaveA From jim.valenza at gmail.com Fri Dec 18 10:46:25 2009 From: jim.valenza at gmail.com (Jim Valenza) Date: Fri, 18 Dec 2009 09:46:25 -0600 Subject: Setting Parameters inside of code Message-ID: <12ef9e020912180746o490b792dra6d71aa264be364f@mail.gmail.com> Hello All - I have a very novice question for any of you out there. I need to assign several parameters to a code in python. I have an example of a code that was in DOS that I would need to set as parameters in my Python script. SetLocal EnableDelayedExpansion SET OUTPUT=..\log SET LOG=..\log SET COMPLETED=..\Loaded SET FAILED=..\Errors SET REPORT=..\log\batch_projectdb.txt SET SOURCE=..\InBox SET BACKUP=..\Backup SET SERVER=housdep01 SET INSTANCE=port:5151 SET DATASET=sde SET /a LOADED=0 SET /a POSTED=0 :: If the directories don't exist, later commands run into problems. MD %OUTPUT% MD %LOG% MD %COMPLETED% MD %FAILED% MD %BACKUP% I've been researching Parameters with the Python manuals and have not found the help to be usefull as there is not much documentation for some reason. I am new to the Python world so maybe I'm missing an important piece of vocab. Thanks A lot Jim -------------- next part -------------- An HTML attachment was scrubbed... URL: From tim.wintle at teamrubber.com Fri Dec 18 10:47:49 2009 From: tim.wintle at teamrubber.com (Tim Wintle) Date: Fri, 18 Dec 2009 15:47:49 +0000 Subject: Java-to-Python? In-Reply-To: <4B2B9542.1090106@it.uu.se> References: <4B2B9542.1090106@it.uu.se> Message-ID: <1261151269.24497.3.camel@localhost> On Fri, 2009-12-18 at 15:44 +0100, Virgil Stokes wrote: > I have a rather large Java package for the analysis of networks that I > would like to convert to Python. Many of the classes in the Java package > are "Serializable". > > Any recommendations on Java-to-Python (2.6) would be appreciated. I used java2python recently with quite a lot of success. I believe it doesn't support newer java features though. http://code.google.com/p/java2python/ From chardster at gmail.com Fri Dec 18 10:51:12 2009 From: chardster at gmail.com (Richard Thomas) Date: Fri, 18 Dec 2009 07:51:12 -0800 (PST) Subject: Line indexing in Python References: Message-ID: <991844f5-f74f-4f07-a626-bde2ad533fd9@l13g2000yqb.googlegroups.com> On Dec 18, 3:42?pm, seafoid wrote: > Hi Guys, > > When python reads in a file, can lines be referred to via an index? > > Example: > > for line in file: > ? ? ?if line[0] == '0': > ? ? ? ? ?a.write(line) > > This works, however, I am unsure if line[0] refers only to the first line or > the first character in all lines. > > Is there an easy way to refer to a line with the first character being a > single letter that you know? > > Thanks in advance, > Seafoid. > -- > View this message in context:http://old.nabble.com/Line-indexing-in-Python-tp26845253p26845253.html > Sent from the Python - python-list mailing list archive at Nabble.com. 'for line in file' goes through the lines of the file. 'line[0]' is then the first character of that line. You'll need to index them manually, for which you should use a dictionary: index = {} for line in file: index[line[0]] = line a.write(index['0']) Richard. From thehcdreamer at gmail.com Fri Dec 18 10:51:29 2009 From: thehcdreamer at gmail.com (Oscar Del Ben) Date: Fri, 18 Dec 2009 07:51:29 -0800 (PST) Subject: Webpy and UnicodeDecodeError References: <5f704b6c-bc94-40cd-ae71-3d6b363e8c9e@p8g2000yqb.googlegroups.com> Message-ID: <630903f9-bd71-4e4a-a8ac-acbf3c8976c0@21g2000yqj.googlegroups.com> On Dec 18, 4:43?pm, Dave Angel wrote: > Oscar Del Ben wrote: > > So I'm trying to send a file through webpy and urllib2 but I can't get > > around these UnicodeErrors. Here's the code: > > > # controller > > > x = web.input(video_original={}) > > params = {'foo': x['foo']} > > > files = (('video[original]', 'test', x['video_original'].file.read > > ()),) > > client.upload(upload_url, params, files, access_token()) > > > # client library > > > def __encodeMultipart(self, fields, files): > > ? ? ? ? """ > > ? ? ? ? fields is a sequence of (name, value) elements for regular > > form fields. > > ? ? ? ? files is a sequence of (name, filename, value) elements for > > data to be uploaded as files > > ? ? ? ? Return (content_type, body) ready for httplib.HTTP instance > > ? ? ? ? """ > > ? ? ? ? boundary = mimetools.choose_boundary() > > ? ? ? ? crlf = '\r\n' > > > ? ? ? ? l = [] > > ? ? ? ? for k, v in fields.iteritems(): > > ? ? ? ? ? ? l.append('--' + boundary) > > ? ? ? ? ? ? l.append('Content-Disposition: form-data; name="%s"' % k) > > ? ? ? ? ? ? l.append('') > > ? ? ? ? ? ? l.append(v) > > ? ? ? ? for (k, f, v) in files: > > ? ? ? ? ? ? l.append('--' + boundary) > > ? ? ? ? ? ? l.append('Content-Disposition: form-data; name="%s"; > > filename="%s"' % (k, f)) > > ? ? ? ? ? ? l.append('Content-Type: %s' % self.__getContentType(f)) > > ? ? ? ? ? ? l.append('') > > ? ? ? ? ? ? l.append(v) > > ? ? ? ? l.append('--' + boundary + '--') > > ? ? ? ? l.append('') > > ? ? ? ? body = crlf.join(l) > > > ? ? ? ? return boundary, body > > > ? ? def __getContentType(self, filename): > > ? ? ? ? return mimetypes.guess_type(filename)[0] or 'application/octet- > > stream' > > > ? ? def upload(self, path, post_params, files, token=None): > > > ? ? ? if token: > > ? ? ? ? token = oauth.OAuthToken.from_string(token) > > > ? ? ? url = "http://%s%s" % (self.authority, path) > > > ? ? ? (boundary, body) = self.__encodeMultipart(post_params, files) > > > ? ? ? headers = {'Content-Type': 'multipart/form-data; boundary=%s' % > > boundary, > > ? ? ? ? ? 'Content-Length': str(len(body)) > > ? ? ? ? ? } > > > ? ? ? request = oauth.OAuthRequest.from_consumer_and_token( > > ? ? ? ? self.consumer, > > ? ? ? ? token, > > ? ? ? ? http_method='POST', > > ? ? ? ? http_url=url, > > ? ? ? ? parameters=post_params > > ? ? ? ) > > > ? ? ? request.sign_request(oauth.OAuthSignatureMethod_HMAC_SHA1(), > > self.consumer, token) > > > ? ? ? request = urllib2.Request(request.http_url, postdata=body, > > headers=headers) > > ? ? ? request.get_method = lambda: 'POST' > > > ? ? ? return urllib2.urlopen(request) > > > Unfortunately I get two kinds of unicode error, the first one in the > > crlf.join(l): > > > Traceback (most recent call last): > > ? File "/Users/oscar/projects/work/whitelabel/web/application.py", > > line 242, in process > > ? ? return self.handle() > > ? File "/Users/oscar/projects/work/whitelabel/web/application.py", > > line 233, in handle > > ? ? return self._delegate(fn, self.fvars, args) > > ? File "/Users/oscar/projects/work/whitelabel/web/application.py", > > line 412, in _delegate > > ? ? return handle_class(cls) > > ? File "/Users/oscar/projects/work/whitelabel/web/application.py", > > line 387, in handle_class > > ? ? return tocall(*args) > > ? File "/Users/oscar/projects/work/whitelabel/code.py", line 328, in > > POST > > ? ? return simplejson.load(client.upload(upload_url, params, files, > > access_token())) > > ? File "/Users/oscar/projects/work/whitelabel/oauth_client.py", line > > 131, in upload > > ? ? (boundary, body) = self.__encodeMultipart(post_params, files) > > ? File "/Users/oscar/projects/work/whitelabel/oauth_client.py", line > > 111, in __encodeMultipart > > ? ? body = crlf.join(l) > > UnicodeDecodeError: 'ascii' codec can't decode byte 0xb7 in position > > 42: ordinal not in range(128) > > > And here's another one: > > > Traceback (most recent call last): > > ? File "/Users/oscar/projects/work/whitelabel/web/application.py", > > line 242, in process > > ? ? return self.handle() > > ? File "/Users/oscar/projects/work/whitelabel/web/application.py", > > line 233, in handle > > ? ? return self._delegate(fn, self.fvars, args) > > ? File "/Users/oscar/projects/work/whitelabel/web/application.py", > > line 412, in _delegate > > ? ? return handle_class(cls) > > ? File "/Users/oscar/projects/work/whitelabel/web/application.py", > > line 387, in handle_class > > ? ? return tocall(*args) > > ? File "/Users/oscar/projects/work/whitelabel/code.py", line 328, in > > POST > > ? ? return simplejson.load(client.upload(upload_url, params, files, > > access_token())) > > ? File "/Users/oscar/projects/work/whitelabel/oauth_client.py", line > > 131, in upload > > ? ? (boundary, body) = self.__encodeMultipart(post_params, files) > > ? File "/Users/oscar/projects/work/whitelabel/oauth_client.py", line > > 111, in __encodeMultipart > > ? ? body = crlf.join(l) > > UnicodeDecodeError: 'ascii' codec can't decode byte 0xb7 in position > > 42: ordinal not in range(128) > > > Does anyone know why this errors happens and what I should do to > > prevent them? Many thanks. > > > Oscar > > I did a short test to demonstrate the likely problem, without all the > other libraries and complexity. > > lst = ["abc"] > lst.append("def") > lst.append(u"abc") > lst.append("g\x48\x82\x94i") > print lst > print "**".join(lst) > > That fragment of code generates (in Python 2.6) the following output and > traceback: > > ['abc', 'def', u'abc', 'gH\x82\x94i'] > Traceback (most recent call last): > ? File "M:\Programming\Python\sources\dummy\stuff2.py", line 10, in > ? ? print "**".join(lst) > UnicodeDecodeError: 'ascii' codec can't decode byte 0x82 in position 2: > ordinal not in range(128) > > You'll notice that one of the strings is a unicode one, and another one > has the character 0x82 in it. ?Once join() discovers Unicode, it needs > to produce a Unicode string, and by default, it uses the ASCII codec to > get it. > > If you print your 'l' list (bad name, by the way, looks too much like a > '1'), you can see which element is Unicode, and which one has the \xb7 > in position 42. ?You'll have to decide which is the problem, and solve > it accordingly. ?Was the fact that one of the strings is unicode an > oversight? ?Or did you think that all characters would be 0x7f or less? ? > Or do you want to handle all possible characters, and if so, with what > encoding? > > DaveA Thanks for your reply DaveA. Since I'm dealing with file uploads, I guess I should only care about those. I understand the fact that I'm trying to concatenate a unicode string with a binary, but I don't know how to deal with this. Perhaps the uploaded file should be encoded in some way? I don't think this is the case though. From emekamicro at gmail.com Fri Dec 18 10:57:00 2009 From: emekamicro at gmail.com (Emeka) Date: Fri, 18 Dec 2009 15:57:00 +0000 Subject: PyArg_ParseTupleAndKeywords in Python3.1 In-Reply-To: <99e0b9530912180702p2de1a17p6f8f662dc2269c7b@mail.gmail.com> References: <0a0b822c-8d57-4816-8563-5fd8ff39f7f1@p8g2000yqb.googlegroups.com> <83f08b89-6b61-4005-9fbd-c9a01da36654@d9g2000prh.googlegroups.com> <408e4acd-3182-4d08-bcb4-d4ff1632d9c2@l13g2000yqb.googlegroups.com> <2a0f6103-3615-4d6a-bd6c-e0bfcbf37eb6@26g2000yqo.googlegroups.com> <89c38c820912180226k6e692acl8089ef739655b464@mail.gmail.com> <99e0b9530912180702p2de1a17p6f8f662dc2269c7b@mail.gmail.com> Message-ID: <89c38c820912180757m7d63f200v9f6b6b10c37a13a6@mail.gmail.com> Case, Thanks so much! However, I am still confused. This is what I understood; foo (a = "a", b = "b") so function , foo, has default values which are "a" and "b". pointer kwlist[] is a way of specifying default values . Regards, Emeka On Fri, Dec 18, 2009 at 3:02 PM, Case Vanhorsen wrote: > On Fri, Dec 18, 2009 at 2:26 AM, Emeka wrote: > > char *kwlist[] = {"a", "b", NULL}; > > if (!PyArg_ParseTupleAndKeywords(args, kwrds, "|CC", kwlist, &a, > > &b)) > > I am yet to understand what pointer kwlist[] does and why it is needed? > > Regards, > > Emeka > > foo is designed to accept two arguments that can be specified by > either position or name. kwlist contains the legal keyword names. In > this example, the legal keywords are 'a' and 'b'. That they match the > names of the C variables is just a lucky coincidence. If you want to > change the keyword names to 'foo' and 'bar', you would just use char > *kwlist[]={"foo", "bar", NULL}. > > casevh > > > > On Fri, Dec 18, 2009 at 8:17 AM, casevh wrote: > >> > >> On Dec 17, 11:14 am, Joachim Dahl wrote: > >> > In the Ubuntu 9.10 version of Python 3.1 (using your patch), there's a > >> > related bug: > >> > > >> > >>> foo(b='b') > >> > > >> > will set the value of a in the extension module to zero, thus clearing > >> > whatever > >> > default value it may have had. In other words, the optional character > >> > arguments > >> > that are skipped seem to be nulled by PyArg_ParseTupleAndKeywords(). > >> > >> The following code seems to work fine for me: > >> > >> static PyObject* foo(PyObject *self, PyObject *args, PyObject *kwrds) > >> { > >> int a=65, b=66; > >> char *kwlist[] = {"a", "b", NULL}; > >> if (!PyArg_ParseTupleAndKeywords(args, kwrds, "|CC", kwlist, &a, > >> &b)) > >> return NULL; > >> return Py_BuildValue("(CC)", a, b); > >> } > >> > >> The default values seem to remain as 'A' and 'B'. > >> > >> >>> foo() > >> ('A', 'B') > >> >>> foo(b='b') > >> ('A', 'b') > >> >>> foo() > >> ('A', 'B') > >> >>> foo('a') > >> ('a', 'B') > >> >>> foo('a', b='b') > >> ('a', 'b') > >> >>> foo() > >> ('A', 'B') > >> >>> > >> > >> casevh > >> -- > >> http://mail.python.org/mailman/listinfo/python-list > > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at holdenweb.com Fri Dec 18 11:12:08 2009 From: steve at holdenweb.com (Steve Holden) Date: Fri, 18 Dec 2009 11:12:08 -0500 Subject: Line indexing in Python In-Reply-To: <26845253.post@talk.nabble.com> References: <26845253.post@talk.nabble.com> Message-ID: seafoid wrote: > Hi Guys, > > When python reads in a file, can lines be referred to via an index? > > Example: > > for line in file: > if line[0] == '0': > a.write(line) > > This works, however, I am unsure if line[0] refers only to the first line or > the first character in all lines. > Each time around the loop the variable "line" contains the current line from the file. Thus line[0] is the first character of the current line. If your intent is to print all lines beginning with "0" then your code will work. > Is there an easy way to refer to a line with the first character being a > single letter that you know? > You might express it more readably as for line in file: if line.startswith("0"): a.write(line) This seems to express the intent of your code somewhat more directly. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ UPCOMING EVENTS: http://holdenweb.eventbrite.com/ From casevh at gmail.com Fri Dec 18 11:24:04 2009 From: casevh at gmail.com (Case Vanhorsen) Date: Fri, 18 Dec 2009 08:24:04 -0800 Subject: PyArg_ParseTupleAndKeywords in Python3.1 In-Reply-To: <89c38c820912180757m7d63f200v9f6b6b10c37a13a6@mail.gmail.com> References: <83f08b89-6b61-4005-9fbd-c9a01da36654@d9g2000prh.googlegroups.com> <408e4acd-3182-4d08-bcb4-d4ff1632d9c2@l13g2000yqb.googlegroups.com> <2a0f6103-3615-4d6a-bd6c-e0bfcbf37eb6@26g2000yqo.googlegroups.com> <89c38c820912180226k6e692acl8089ef739655b464@mail.gmail.com> <99e0b9530912180702p2de1a17p6f8f662dc2269c7b@mail.gmail.com> <89c38c820912180757m7d63f200v9f6b6b10c37a13a6@mail.gmail.com> Message-ID: <99e0b9530912180824k6a219634qff9709262c777884@mail.gmail.com> On Fri, Dec 18, 2009 at 7:57 AM, Emeka wrote: > Case, > Thanks so much! However, I am still confused. This is what I understood; > foo (a = "a", b = "b") so function , foo, ?has default values which are "a" > and "b". pointer kwlist[] is a way of specifying default values . > Regards, > Emeka kwlist just specifies the names. The default values are specified by "int a=65, b=66;". 65 is equivalent to 'A' and 66 is equivalent to 'B'. casevh > > On Fri, Dec 18, 2009 at 3:02 PM, Case Vanhorsen wrote: >> >> On Fri, Dec 18, 2009 at 2:26 AM, Emeka wrote: >> > ?? char *kwlist[] = {"a", "b", NULL}; >> > ? ?if (!PyArg_ParseTupleAndKeywords(args, kwrds, "|CC", kwlist, &a, >> > &b)) >> > I am yet to understand what pointer kwlist[] does and why it is needed? >> > Regards, >> > Emeka >> >> foo is designed to accept two arguments that can be specified by >> either position or name. kwlist contains the legal keyword names. In >> this example, the legal keywords are 'a' and 'b'. That they match the >> names of the C variables is just a lucky coincidence. If you want to >> change the keyword names to 'foo' and 'bar', you would just use char >> *kwlist[]={"foo", "bar", NULL}. >> >> casevh >> > >> > On Fri, Dec 18, 2009 at 8:17 AM, casevh wrote: >> >> >> >> On Dec 17, 11:14?am, Joachim Dahl wrote: >> >> > In the Ubuntu 9.10 version of Python 3.1 (using your patch), there's >> >> > a >> >> > related bug: >> >> > >> >> > >>> foo(b='b') >> >> > >> >> > will set the value of a in the extension module to zero, thus >> >> > clearing >> >> > whatever >> >> > default value it may have had. ?In other words, the optional >> >> > character >> >> > arguments >> >> > that are skipped seem to be nulled by PyArg_ParseTupleAndKeywords(). >> >> >> >> The following code seems to work fine for me: >> >> >> >> static PyObject* foo(PyObject *self, PyObject *args, PyObject *kwrds) >> >> { >> >> ? ?int a=65, b=66; >> >> ? ?char *kwlist[] = {"a", "b", NULL}; >> >> ? ?if (!PyArg_ParseTupleAndKeywords(args, kwrds, "|CC", kwlist, &a, >> >> &b)) >> >> ? ? ? ?return NULL; >> >> ? ?return Py_BuildValue("(CC)", a, b); >> >> } >> >> >> >> The default values seem to remain as 'A' and 'B'. >> >> >> >> >>> foo() >> >> ('A', 'B') >> >> >>> foo(b='b') >> >> ('A', 'b') >> >> >>> foo() >> >> ('A', 'B') >> >> >>> foo('a') >> >> ('a', 'B') >> >> >>> foo('a', b='b') >> >> ('a', 'b') >> >> >>> foo() >> >> ('A', 'B') >> >> >>> >> >> >> >> casevh >> >> -- >> >> http://mail.python.org/mailman/listinfo/python-list >> > >> > > > From fitzpadj at tcd.ie Fri Dec 18 11:27:56 2009 From: fitzpadj at tcd.ie (seafoid) Date: Fri, 18 Dec 2009 08:27:56 -0800 (PST) Subject: Line indexing in Python In-Reply-To: <991844f5-f74f-4f07-a626-bde2ad533fd9@l13g2000yqb.googlegroups.com> References: <26845253.post@talk.nabble.com> <991844f5-f74f-4f07-a626-bde2ad533fd9@l13g2000yqb.googlegroups.com> Message-ID: <26845949.post@talk.nabble.com> Thanks for that Richard and Steve. I have another question. fname = raw_input('Please enter the name of the file: ') # create file objects blah = open(fname, 'r') a = open('rubbish', 'w') for line in blah: if line.startswith("0"): a.write(line) elif line.endswith("0"): lists_a = line.strip().split() print lists_a elif line.startswith("0"): lists_b = line.strip().split() print lists_b Essentially, I wish to take input from a file and based on the location of zero, assign lines to lists. Any suggestions? Seafoid. -- View this message in context: http://old.nabble.com/Line-indexing-in-Python-tp26845253p26845949.html Sent from the Python - python-list mailing list archive at Nabble.com. From luismgz at gmail.com Fri Dec 18 11:33:54 2009 From: luismgz at gmail.com (=?ISO-8859-1?Q?Luis_M=2E_Gonz=E1lez?=) Date: Fri, 18 Dec 2009 08:33:54 -0800 (PST) Subject: Java-to-Python? References: Message-ID: <26298a06-395f-434c-a144-f69416219291@k4g2000yqb.googlegroups.com> On Dec 18, 11:44?am, Virgil Stokes wrote: > I have a rather large Java package for the analysis of networks that I > would like to convert to Python. Many of the classes in the Java package > are "Serializable". > > Any recommendations on Java-to-Python (2.6) would be appreciated. > > --V Have you considered using this package with Jython? From fitzpadj at tcd.ie Fri Dec 18 11:35:16 2009 From: fitzpadj at tcd.ie (seafoid) Date: Fri, 18 Dec 2009 08:35:16 -0800 (PST) Subject: Line indexing in Python In-Reply-To: References: <26845253.post@talk.nabble.com> Message-ID: <26846049.post@talk.nabble.com> Thanks for that Richard and Steve! Below is my full code so far: for line in file: if line.startswith("1"): a.write(line) elif line.endswith("0"): lists_a = line.strip().split() print lists_a elif line.startswith("2"): lists_b = line.strip().split() print list_a Essentially, I want to read in a file and depending on location of 0, 1, 2, write to another file or create lists. The above passes without error warning but does nothing (semantic error?). Any Suggestions? Thanks in advance, Seafoid. -- View this message in context: http://old.nabble.com/Line-indexing-in-Python-tp26845253p26846049.html Sent from the Python - python-list mailing list archive at Nabble.com. From mailings at julianmoritz.de Fri Dec 18 11:38:22 2009 From: mailings at julianmoritz.de (Julian) Date: Fri, 18 Dec 2009 08:38:22 -0800 (PST) Subject: Design question about pretree classifier Message-ID: <7351dfbf-90a2-4303-b3d8-2377dcd2698e@o28g2000yqh.googlegroups.com> Hello, I've got a design problem for a classifier. To make it short: it maps strings on strings. Some strings have exactly one classification, some none and some more than one. There's a method classify(self, word) wich classifies a word. For the first case there's no problem: - one classification: return the value (it's a string) But: - none classification: return an exception or None? I think None is better, hence its not an exception that there is no classification but a defined state. What do you think? - many classifications: what to do? retun a sequence of strings? raise an exception and implement another method wich returns than the classifications? what should I do here? thanks for your answers! From fitzpadj at tcd.ie Fri Dec 18 11:39:16 2009 From: fitzpadj at tcd.ie (seafoid) Date: Fri, 18 Dec 2009 08:39:16 -0800 (PST) Subject: Line indexing in Python Message-ID: <26846049.post@talk.nabble.com> Thanks for that Richard and Steve! Below is my full code so far: for line in file: if line.startswith("1"): a.write(line) elif line.endswith("0"): lists_a = line.strip().split() print lists_a elif line.startswith("2"): lists_b = line.strip().split() print list_b Essentially, I want to read in a file and depending on location of 0, 1, 2, write to another file or create lists. The above passes without error warning but does nothing (semantic error?). Any Suggestions? Thanks in advance, Seafoid. -- View this message in context: http://old.nabble.com/Line-indexing-in-Python-tp26845253p26846049.html Sent from the Python - python-list mailing list archive at Nabble.com. From sry4spam at gmail.com Fri Dec 18 11:41:15 2009 From: sry4spam at gmail.com (sKeeZe) Date: Fri, 18 Dec 2009 08:41:15 -0800 (PST) Subject: imports in __init__.py References: <87y6l0zyq6.fsf@benfinney.id.au> <910b03ef-0e72-471b-b331-0f9ad40c6015@u20g2000vbq.googlegroups.com> Message-ID: <52adf2c6-8050-461c-8b0d-11745dbd5b3e@d20g2000yqh.googlegroups.com> I wrote my last message late last night. When I said "I am unable to import a module from the package without an import error.", I did mean the 'modulename' module. However, I just set up a Debian VM with Python 2.5.2 and what I was trying to do works. So it is either something that changed with Python 3.1.1, or a problem with Windows. From phily05 at gmail.com Fri Dec 18 11:42:58 2009 From: phily05 at gmail.com (Phil) Date: Fri, 18 Dec 2009 08:42:58 -0800 (PST) Subject: imports in __init__.py References: <87y6l0zyq6.fsf@benfinney.id.au> <910b03ef-0e72-471b-b331-0f9ad40c6015@u20g2000vbq.googlegroups.com> Message-ID: I wrote my last message late last night. When I said "I am unable to import a module from the package without an import error.", I did mean the 'modulename' module. However, I just set up a Debian VM with Python 2.5.2 and what I was trying to do works. So it is either something that changed with Python 3.1.1, or a problem with Windows. From lie.1296 at gmail.com Fri Dec 18 11:54:10 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Sat, 19 Dec 2009 03:54:10 +1100 Subject: Line indexing in Python In-Reply-To: References: <26845253.post@talk.nabble.com> <991844f5-f74f-4f07-a626-bde2ad533fd9@l13g2000yqb.googlegroups.com> Message-ID: <4b2bb3c8$1@dnews.tpgi.com.au> On 12/19/2009 3:27 AM, seafoid wrote: > > Thanks for that Richard and Steve. > > I have another question. What's the question? > fname = raw_input('Please enter the name of the file: ') > > # create file objects > > blah = open(fname, 'r') > a = open('rubbish', 'w') > > for line in blah: > if line.startswith("0"): > a.write(line) > elif line.endswith("0"): > lists_a = line.strip().split() > print lists_a The following block is a dead code; the block will never be executed since if line.startswith("0") is true, the control will fall to the a.write(line) block and this block is skipped. > elif line.startswith("0"): > lists_b = line.strip().split() > print lists_b > > Essentially, I wish to take input from a file and based on the location of > zero, assign lines to lists. > > Any suggestions? > > Seafoid. > From anh.hai.trinh at gmail.com Fri Dec 18 12:03:21 2009 From: anh.hai.trinh at gmail.com (Anh Hai Trinh) Date: Fri, 18 Dec 2009 09:03:21 -0800 (PST) Subject: iterators and views of lists References: <89604fb4-9dfa-45f1-a3df-f676cd4353ea@x5g2000prf.googlegroups.com> <87b87511-744c-450e-a024-976f8c57f032@15g2000prz.googlegroups.com> Message-ID: <5d4ec11e-5f9a-46ab-9875-b511897367c0@v7g2000pro.googlegroups.com> On Dec 18, 3:07?am, Brendan Miller wrote: > Well, it doesn't really need to be any slower than a normal list. You > only need to use index and do extra additions because it's in python. > However, if listagent were written in C, you would just have a pointer > into the contents of the original list, and the length, which is all > that list itself has. You're right, I was thinking in Python instead of C. So the translations in that case is really straight forward, using just pointer arithmetic. ----aht From sion at viridian.paintbox Fri Dec 18 12:09:41 2009 From: sion at viridian.paintbox (Sion Arrowsmith) Date: Fri, 18 Dec 2009 17:09:41 GMT Subject: Raw string substitution problem References: <931375.44828.qm@web58902.mail.re1.yahoo.com> <2I-dnaKkY7MM_LfWnZ2dnUVZ_sGdnZ2d@rcn.net> <7p0q09F6qiU1@mid.individual.net> Message-ID: Gregory Ewing wrote: >MRAB wrote: >> Regular expressions and replacement strings have their own escaping >> mechanism, which also uses backslashes. >This seems like a misfeature to me. It makes sense for >a regular expression to give special meanings to backslash >sequences, because it's a sublanguage with its own syntax. >But I can't see any earthly reason to do that with the >*replacement* string, which is just data. >>> re.sub('a(.)c', r'\1', "123abcdefg") '123bdefg' Still think the replacement string is "just data"? -- \S under construction From python at mrabarnett.plus.com Fri Dec 18 12:17:27 2009 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 18 Dec 2009 17:17:27 +0000 Subject: Raw string substitution problem In-Reply-To: <7p0q09F6qiU1@mid.individual.net> References: <931375.44828.qm@web58902.mail.re1.yahoo.com> <2I-dnaKkY7MM_LfWnZ2dnUVZ_sGdnZ2d@rcn.net> <7p0q09F6qiU1@mid.individual.net> Message-ID: <4B2BB927.3060008@mrabarnett.plus.com> Gregory Ewing wrote: > MRAB wrote: > >> Regular expressions and replacement strings have their own escaping >> mechanism, which also uses backslashes. > > This seems like a misfeature to me. It makes sense for a regular > expression to give special meanings to backslash sequences, because > it's a sublanguage with its own syntax. But I can't see any earthly > reason to do that with the *replacement* string, which is just data. > > It looks like a feature that's been blindly copied over from Perl > without thinking about whether it makes sense in Python. > In simple cases you might be replacing with the same string every time, but other cases you might want the replacement to contain substrings captured by the regex. For example, swapping pairs of words: >>> re.sub(r'(\w+) (\w+)', r'\2 \1', r'first second third fourth') 'second first fourth third' Python also allows you to provide a function that returns the replacement string, but that seems a bit long-winded for those cases when a simple replacement template would suffice. From jeanmichel at sequans.com Fri Dec 18 12:24:27 2009 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Fri, 18 Dec 2009 18:24:27 +0100 Subject: [ANN] pylint 0.19 / astng 0.19.2 In-Reply-To: <20091218123918.GH24924@lupus.logilab.fr> References: <20091218123918.GH24924@lupus.logilab.fr> Message-ID: <4B2BBACB.1060605@sequans.com> Sylvain Th?nault wrote: > Hi, > > I'm very pleased to announce the release of pylint 0.19 / astng 0.19.2 release! > > More information / download on http://www.logilab.org/project/pylint/0.19.0. > > This is a "community" release, including the work we've done during the pylint > bug day [1] and patches mostly from James Lingard and Vincent Ferotin. > > Many thanks to James Lingard which provided two long waited features: > > * check of function call arguments > * check string interpolation consistency > > > So, happy christmas, enjoy! > > [1] http://www.logilab.org/blogentry/19260 > I have troubles after updating pylint: easy_install pylint -U --install-dir /opt/tools/python/python2.3/site-packages > pylint File "/opt/tools/python/python2.3/site-packages/logilab_astng-0.19.2-py2.5.egg/logilab/astng/infutils.py", line 28, in from logilab.astng._nodes import Proxy_, List, Tuple, Function, If, TryExcept ImportError: No module named _nodes There is no _nodes.py file within the egg. Has anyone experienced the same issue ? Jean-Michel From steve at holdenweb.com Fri Dec 18 12:27:55 2009 From: steve at holdenweb.com (Steve Holden) Date: Fri, 18 Dec 2009 12:27:55 -0500 Subject: share dictionary between processes In-Reply-To: References: Message-ID: <4B2BBB9B.8040205@holdenweb.com> blumenkraft wrote: > Hi, > > I want to share dictionary between two distinct processes. > > > Something like this: > > first.py > import magic_share_module > > def create_dictionary(): > return {"a": 1} > > magic_share_module.share("shared_dictionary", > creator.create_dictionary) > while True: > pass > > > second.py > import magic_share_module > d = magic_share_module.get_shared("shared_dictionary") > print d["a"] > > And then run in command line: > python first.py & > sleep 1 > python second.py > > I have looked at POSH, but it requires master process that will fork > childs. I want read-only sharing between completely unrelated > processes. > Is it possible? Take a look at pyro, though it may be overkill for your needs. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ UPCOMING EVENTS: http://holdenweb.eventbrite.com/ From steve at holdenweb.com Fri Dec 18 12:27:55 2009 From: steve at holdenweb.com (Steve Holden) Date: Fri, 18 Dec 2009 12:27:55 -0500 Subject: share dictionary between processes In-Reply-To: References: Message-ID: <4B2BBB9B.8040205@holdenweb.com> blumenkraft wrote: > Hi, > > I want to share dictionary between two distinct processes. > > > Something like this: > > first.py > import magic_share_module > > def create_dictionary(): > return {"a": 1} > > magic_share_module.share("shared_dictionary", > creator.create_dictionary) > while True: > pass > > > second.py > import magic_share_module > d = magic_share_module.get_shared("shared_dictionary") > print d["a"] > > And then run in command line: > python first.py & > sleep 1 > python second.py > > I have looked at POSH, but it requires master process that will fork > childs. I want read-only sharing between completely unrelated > processes. > Is it possible? Take a look at pyro, though it may be overkill for your needs. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ UPCOMING EVENTS: http://holdenweb.eventbrite.com/ From malaclypse2 at gmail.com Fri Dec 18 12:32:33 2009 From: malaclypse2 at gmail.com (Jerry Hill) Date: Fri, 18 Dec 2009 12:32:33 -0500 Subject: [ANN] pylint 0.19 / astng 0.19.2 In-Reply-To: <4B2BBACB.1060605@sequans.com> References: <20091218123918.GH24924@lupus.logilab.fr> <4B2BBACB.1060605@sequans.com> Message-ID: <16651e80912180932m6e9280b2wf52f2f6ccaa24fea@mail.gmail.com> On Fri, Dec 18, 2009 at 12:24 PM, Jean-Michel Pichavant > ?File > "/opt/tools/python/python2.3/site-packages/logilab_astng-0.19.2-py2.5.egg/logilab/astng/infutils.py", > line 28, in > ? from logilab.astng._nodes import Proxy_, List, Tuple, Function, If, > TryExcept > ImportError: No module named _nodes You're installing the wrong version of logilab. That's the python 2.5 version, judging by the name of the egg. I'm not sure how easy_install decides which version of python to install for, but it's definitely picking the wrong one here. -- Jerry From fitzpadj at tcd.ie Fri Dec 18 12:33:43 2009 From: fitzpadj at tcd.ie (seafoid) Date: Fri, 18 Dec 2009 09:33:43 -0800 (PST) Subject: Line indexing in Python In-Reply-To: <4b2bb3c8$1@dnews.tpgi.com.au> References: <26845253.post@talk.nabble.com> <991844f5-f74f-4f07-a626-bde2ad533fd9@l13g2000yqb.googlegroups.com> <4b2bb3c8$1@dnews.tpgi.com.au> Message-ID: <26846854.post@talk.nabble.com> Thanks for that Lie. I had to have a think about what you meant when you referred to control going to a.write(line). Have you any suggestions how I may render this code undead or should I scrap it and create something new? My confusion and ineptitude is perhaps explained by my being a biologist :-( Thanks, Seafoid. -- View this message in context: http://old.nabble.com/Line-indexing-in-Python-tp26845253p26846854.html Sent from the Python - python-list mailing list archive at Nabble.com. From __peter__ at web.de Fri Dec 18 12:40:00 2009 From: __peter__ at web.de (Peter Otten) Date: Fri, 18 Dec 2009 18:40 +0100 Subject: imports in __init__.py References: <87y6l0zyq6.fsf@benfinney.id.au> <910b03ef-0e72-471b-b331-0f9ad40c6015@u20g2000vbq.googlegroups.com> Message-ID: Phil wrote: > I wrote my last message late last night. When I said "I am unable to > import a module from the package without an import error.", I did mean > the 'modulename' module. > > However, I just set up a Debian VM with Python 2.5.2 and what I was > trying to do works. So it is either something that changed with Python > 3.1.1, or a problem with Windows. In Python 3.x absolute import is on by default. Change from application import * to from .application import * to indicate that the application module is located within the current package. Peter From jeanmichel at sequans.com Fri Dec 18 12:49:56 2009 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Fri, 18 Dec 2009 18:49:56 +0100 Subject: [ANN] pylint 0.19 / astng 0.19.2 In-Reply-To: <16651e80912180932m6e9280b2wf52f2f6ccaa24fea@mail.gmail.com> References: <20091218123918.GH24924@lupus.logilab.fr> <4B2BBACB.1060605@sequans.com> <16651e80912180932m6e9280b2wf52f2f6ccaa24fea@mail.gmail.com> Message-ID: <4B2BC0C4.9000605@sequans.com> Jerry Hill wrote: > On Fri, Dec 18, 2009 at 12:24 PM, Jean-Michel Pichavant > File > >> "/opt/tools/python/python2.3/site-packages/logilab_astng-0.19.2-py2.5.egg/logilab/astng/infutils.py", >> line 28, in >> from logilab.astng._nodes import Proxy_, List, Tuple, Function, If, >> TryExcept >> ImportError: No module named _nodes >> > > You're installing the wrong version of logilab. That's the python 2.5 > version, judging by the name of the egg. I'm not sure how > easy_install decides which version of python to install for, but it's > definitely picking the wrong one here. > > well, according this mail title, astng 0.19.2 is the correct one. I should have mentioned /opt/tools/python/python2.3/ is a network drive where we install 3rd party modules. It is still named python2.3 but this is in fact totally irrelevant (we're the kind of lazy guys). Python 2.5 is the one installed on my system so easy_install guess is right. Or maybe you suggested that pylint is no more compatible with python2.5 ? JM From sylvain.thenault at logilab.fr Fri Dec 18 12:55:47 2009 From: sylvain.thenault at logilab.fr (Sylvain =?utf-8?B?VGjDqW5hdWx0?=) Date: Fri, 18 Dec 2009 18:55:47 +0100 Subject: [ANN] pylint 0.19 / astng 0.19.2 In-Reply-To: <4B2BBACB.1060605@sequans.com> References: <20091218123918.GH24924@lupus.logilab.fr> <4B2BBACB.1060605@sequans.com> Message-ID: <20091218175547.GA11027@lupus.logilab.fr> On 18 d?cembre 18:24, Jean-Michel Pichavant wrote: > Sylvain Th?nault wrote: > >Hi, > > > >I'm very pleased to announce the release of pylint 0.19 / astng 0.19.2 release! > > > >More information / download on http://www.logilab.org/project/pylint/0.19.0. > > > >This is a "community" release, including the work we've done during the pylint > >bug day [1] and patches mostly from James Lingard and Vincent Ferotin. > > > >Many thanks to James Lingard which provided two long waited features: > > > >* check of function call arguments > >* check string interpolation consistency > > > > > >So, happy christmas, enjoy! > > > >[1] http://www.logilab.org/blogentry/19260 > I have troubles after updating pylint: > > easy_install pylint -U --install-dir > /opt/tools/python/python2.3/site-packages > > > pylint > > File "/opt/tools/python/python2.3/site-packages/logilab_astng-0.19.2-py2.5.egg/logilab/astng/infutils.py", > line 28, in > from logilab.astng._nodes import Proxy_, List, Tuple, Function, > If, TryExcept > ImportError: No module named _nodes > > There is no _nodes.py file within the egg. Has anyone experienced > the same issue ? yep someone else on the list have the same pb. I think I've identified it: python setup.py register sdist upload *doesn't* regenerate MANIFEST if one is found... So packages uploaded to pypi had some missing files. Should be fixed now, sorry for this pb. -- Sylvain Th?nault LOGILAB, Paris (France) Formations Python, Debian, M?th. Agiles: http://www.logilab.fr/formations D?veloppement logiciel sur mesure: http://www.logilab.fr/services CubicWeb, the semantic web framework: http://www.cubicweb.org From astan.chee at al.com.au Fri Dec 18 12:56:34 2009 From: astan.chee at al.com.au (Astan Chee) Date: Sat, 19 Dec 2009 04:56:34 +1100 Subject: Help with invoking standard mail app in windows Message-ID: <4B2BC252.3060509@al.com.au> Hi, I don't know if my last mail made it or not but here it is again. I'm trying to launch standard mail app in windows and after looking around most look like this: import urllib, webbrowser, win32api def mailto_url(to=None,subject=None,body=None,cc=None): """ encodes the content as a mailto link as described on http://www.faqs.org/rfcs/rfc2368.html """ url = "mailto: " + urllib.quote(to.strip(),"@,") sep = "?" if cc: url+= sep + "cc=" + urllib.quote(cc,"@,") sep = "&" if subject: url+= sep + "subject=" + urllib.quote(subject,"") sep = "&" if body: # Also note that line breaks in the body of a message MUST be # encoded with "%0D%0A". (RFC 2368) body="\r\n".join(body.splitlines()) url+= sep + "body=" + urllib.quote(body,"") sep = "&" return url url = mailto_url(txtTo,txtSubject,body,txtCC) # win32api.ShellExecute(0,'open',url,None,None,0) webbrowser.open(url,new=1) # os.startfile(url) all of these are having "WindowsError : [Error 5] Access is denied" errors. I'm using windows xp and python 2.5. I have outlook 2007 installed as a default mail client. Clicking on any mailto links in html brings up the normal write mail from the mail client. Any ideas why this is happening or how do I debug what access is being denied? Thanks for any help Astan From alan.isaac at gmail.com Fri Dec 18 12:58:08 2009 From: alan.isaac at gmail.com (Alan G Isaac) Date: Fri, 18 Dec 2009 12:58:08 -0500 Subject: Raw string substitution problem In-Reply-To: References: <931375.44828.qm@web58902.mail.re1.yahoo.com> <2I-dnaKkY7MM_LfWnZ2dnUVZ_sGdnZ2d@rcn.net> Message-ID: On 12/17/2009 7:59 PM, Rhodri James wrote: > "re.compile('a\\nc')" passes a sequence of four characters to > re.compile: 'a', '\', 'n' and 'c'. re.compile() then does it's own > interpretation: 'a' passes through as is, '\' flags an escape which > combined with 'n' produces the newline character (0x0a), and 'c' passes > through as is. I got that from MRAB's posts. (Thanks.) What I'm not getting is why the replacement string gets this particular interpretation. What is the payoff? (Contrast e.g. Vim's substitution syntax.) Thanks, Alan From albert at spenarnc.xs4all.nl Fri Dec 18 12:58:21 2009 From: albert at spenarnc.xs4all.nl (Albert van der Horst) Date: 18 Dec 2009 17:58:21 GMT Subject: Dangerous behavior of list(generator) References: Message-ID: In article , Gabriel Genellina wrote: > >Despite a promise in PEP 289, generator expressions semantics isn't >explained in detail in the language reference. I can't tell if the >difference is intentional, accidental, undocumented behavior, an >implementation accident, a bug, or what... Philosophically speaking ... An important feature that is not documented is a severe defect. (important maps to severe). Before it is documented, there can be no discrepancy between specification and implementation so other defects are formally not present in relation to this situation. >-- >Gabriel Genellina > Groetjes Albert. -- -- Albert van der Horst, UTRECHT,THE NETHERLANDS Economic growth -- being exponential -- ultimately falters. albert at spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst From alan.isaac at gmail.com Fri Dec 18 12:59:38 2009 From: alan.isaac at gmail.com (Alan G Isaac) Date: Fri, 18 Dec 2009 12:59:38 -0500 Subject: Raw string substitution problem In-Reply-To: References: <931375.44828.qm@web58902.mail.re1.yahoo.com> <2I-dnaKkY7MM_LfWnZ2dnUVZ_sGdnZ2d@rcn.net> <7p0q09F6qiU1@mid.individual.net> Message-ID: On 12/18/2009 12:17 PM, MRAB wrote: > In simple cases you might be replacing with the same string every time, > but other cases you might want the replacement to contain substrings > captured by the regex. Of course that "conversion" is needed in the replacement. But e.g. Vim substitutions handle this fine without the odd (to non perlers) handling of backslashes in replacement. Alan Isaac From steve at holdenweb.com Fri Dec 18 12:59:38 2009 From: steve at holdenweb.com (Steve Holden) Date: Fri, 18 Dec 2009 12:59:38 -0500 Subject: Design question about pretree classifier In-Reply-To: <7351dfbf-90a2-4303-b3d8-2377dcd2698e@o28g2000yqh.googlegroups.com> References: <7351dfbf-90a2-4303-b3d8-2377dcd2698e@o28g2000yqh.googlegroups.com> Message-ID: Julian wrote: > Hello, > > I've got a design problem for a classifier. To make it short: it maps > strings on strings. > > Some strings have exactly one classification, some none and some more > than one. > > There's a method classify(self, word) wich classifies a word. For the > first case there's no problem: > > - one classification: return the value (it's a string) > > But: > > - none classification: return an exception or None? I think None is > better, hence its not an exception that there is no classification but > a defined state. What do you think? > - many classifications: what to do? retun a sequence of strings? raise > an exception and implement another method wich returns than the > classifications? what should I do here? > > thanks for your answers! Always return a list or tuple. For no classifications it should be empty, for one classification it should have one element, ... , for N classifications it should have N elements. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ UPCOMING EVENTS: http://holdenweb.eventbrite.com/ From alfps at start.no Fri Dec 18 13:00:48 2009 From: alfps at start.no (Alf P. Steinbach) Date: Fri, 18 Dec 2009 19:00:48 +0100 Subject: Programming intro book ch1 and ch2 (Windows/Python 3) - Request For Comments Message-ID: I finally finished (draft), I believe!, chapter 2... Chapter 1 gets the reader up & running, i.e. it's "Hello, world!", basic tool usage, without discussing anything about programming really. One reaction to this chapter, based on the two example programs in it, was that it wasn't gradual and slow enough; hey, those examples are far too advanced, and unexplained! But that reader misunderstood: the progression is actually *slower* than one might expect. This chapter is only about tool usage. I.e., it's about getting those programs running, for the reader who can't rely on teachers or fellow students or, as Kernighan & Ritchie put it, "your local guru" (IIRC). Chapter 2 is about Basic Concepts (of programming). It's the usual: variables, basic types and arrays, loops, decision, routines, classes, events, although not presented in that order. I make heavy use of complete, concrete examples, many of them graphical, and everything is in support of what's actually needed for such concrete examples. The intent is to enable the reader to experiment and try things out -- since the only way to really learn is by doing! As best I could I've labored to apply this minimalism also to the Python language, using only a "minimal" subset (to the degree of not even introducing boolean ops :-) ). Chapter 3 will, by my current plan, delve into the Python language and such things as how integers and floating point works on the inside, and that includes those in chapter 2 not even mentioned boolean operations. One important issue, introducing exceptions, and in support of that, type hierarchies. After chapter 3 I have only much vaguer notions about what to introduce in what order, but a main issue, assuming that I go on with this writing, will be to apply and teach methodology all the way, integrated into the examples and text. A table of contents + chapters 1 and 2 is available in PDF format at Google Docs, at Comments are very welcome! Re comments: there are two deviations from current Python practice in chapter 2. First, that I use spaces inside argument parentheses, which makes the code more readable when one gets used/trained to it because it gives the eye more direct information (with some training visual structure can be processed unconsciously & effortlessly, but purely logical structure has to be processed analytically). The second deviation is that since most names are constants, I do not follow PEP 8's recommendation to use uppercase names of constants. In fact almost no Python code does, but then it seems that people are not aware of how many of their names are constants and think that they're uppercasing constants when in fact they're not. E.g. routine arguments and in particular routine names are usually constants, absolutely not meant to be modified, but it would be silly to UC... So both these two deviations from Python practice are /intentional/, since this is a book about programming, not about Python the language & how to conform to idiosyncratic language-specific conventions. But, if there are other deviations from Python practice I'd be very glad to hear of it! I'm very hopeful that any such convention deviations can be fixed. :-) Cheers, - Alf From rory at campbell-lange.net Fri Dec 18 13:01:04 2009 From: rory at campbell-lange.net (Rory Campbell-Lange) Date: Fri, 18 Dec 2009 18:01:04 +0000 Subject: Line indexing in Python In-Reply-To: <26846854.post@talk.nabble.com> References: <26845253.post@talk.nabble.com> <991844f5-f74f-4f07-a626-bde2ad533fd9@l13g2000yqb.googlegroups.com> <4b2bb3c8$1@dnews.tpgi.com.au> <26846854.post@talk.nabble.com> Message-ID: <20091218180104.GA18007@campbell-lange.net> On 18/12/09, seafoid (fitzpadj at tcd.ie) wrote: > Have you any suggestions how I may render this code undead or should I scrap > it and create something new? It might be easier for us to help you if you give us an example of your input file and a clearer description of what you are trying to do with the output from your programme. -- Rory Campbell-Lange rory at campbell-lange.net Campbell-Lange Workshop www.campbell-lange.net 0207 6311 555 3 Tottenham Street London W1T 2AF Registered in England No. 04551928 From drobinow at gmail.com Fri Dec 18 13:04:05 2009 From: drobinow at gmail.com (David Robinow) Date: Fri, 18 Dec 2009 13:04:05 -0500 Subject: [ANN] pylint 0.19 / astng 0.19.2 In-Reply-To: <4B2BC0C4.9000605@sequans.com> References: <20091218123918.GH24924@lupus.logilab.fr> <4B2BBACB.1060605@sequans.com> <16651e80912180932m6e9280b2wf52f2f6ccaa24fea@mail.gmail.com> <4B2BC0C4.9000605@sequans.com> Message-ID: <4eb0089f0912181004m243434eas531ec8b444dd5334@mail.gmail.com> On Fri, Dec 18, 2009 at 12:49 PM, Jean-Michel Pichavant wrote: > Jerry Hill wrote: >> >> On Fri, Dec 18, 2009 at 12:24 PM, Jean-Michel Pichavant > ?File >>> "/opt/tools/python/python2.3/site-packages/logilab_astng-0.19.2-py2.5.egg/logilab/astng/infutils.py", >>> line 28, in >>> ?from logilab.astng._nodes import Proxy_, List, Tuple, Function, If, >>> TryExcept >>> ImportError: No module named _nodes >>> It works for me (but I'm running cygwin) You should have a file /opt/tools/python/python2.3/site-packages/logilab_astng-0.19.2-py2.5.egg/logilab/astng/_nodes.py Does it exist? If not, reinstall logilab_astng-0.19.2 From nagle at animats.com Fri Dec 18 13:17:25 2009 From: nagle at animats.com (John Nagle) Date: Fri, 18 Dec 2009 10:17:25 -0800 Subject: Another MySQL Problem In-Reply-To: References: <4dc0cfea0912131022n1f54985alc77a507c2ab7b0a2@mail.gmail.com> Message-ID: <4b2bc444$0$1596$742ec2ed@news.sonic.net> MRAB wrote: > Victor Subervi wrote: >> Hi; >> >> mysql> truncate tem126072414516; >> Query OK, 0 rows affected (0.00 sec) >> >> Then I run a script: >> >> if whatDo == 'insert': >> try: >> sql = 'insert into %s (ProdID, Quantity) values ("%s", "%s");' % >> (tmpTable, prodid, quantity) >> print sql >> cursor.execute(sql) Don't put values into an SQL statement using the "%" operator. It doesn't do SQL escapes and allows SQL injection attacks. Try something more like this (assuming that tmpTable does NOT come from external input, which would be very risky). cursor = db.cursor() ## create cursor sql = 'insert into ' + tmpTable + ' (ProdID, Quantity) values (%s,%s);' values = (prodid, quantity) ## values to insert print sql cursor.execute(sql, values) ## let SQL do the substitution db.commit() ## commit transaction > 1. The table names look different. > 2. Did you commit the changes? That, too. John Nagle From julien at danjou.info Fri Dec 18 13:18:01 2009 From: julien at danjou.info (Julien Danjou) Date: Fri, 18 Dec 2009 19:18:01 +0100 Subject: Using PyImport_ExtendInittab with package Message-ID: <20091218181801.GA27164@keller.adm.naquadah.org> Hi, I'm trying to embed Python and therefore use PyImport_ExtendInittab() to register modules. My current problem is that, if it works well with a simple module "hello", naming a module "hello.foobar" in the inittab struct does not seems to work. imp.find_module("hello.foobar") returns correctly that the module is found, but import hello.foobar fails badly. Is . notation supported in inittab? Am I doing something wrong? -- Julien Danjou // ? http://julien.danjou.info // 9A0D 5FD9 EB42 22F6 8974 C95C A462 B51E C2FE E5CD // Don't give up. -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 198 bytes Desc: Digital signature URL: From lie.1296 at gmail.com Fri Dec 18 13:18:11 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Sat, 19 Dec 2009 05:18:11 +1100 Subject: Line indexing in Python In-Reply-To: References: <26845253.post@talk.nabble.com> <991844f5-f74f-4f07-a626-bde2ad533fd9@l13g2000yqb.googlegroups.com> <4b2bb3c8$1@dnews.tpgi.com.au> Message-ID: <4b2bc779$1@dnews.tpgi.com.au> On 12/19/2009 4:33 AM, seafoid wrote: > > Thanks for that Lie. > > I had to have a think about what you meant when you referred to control > going to a.write(line). and if-elif-elif-... chain is executed sequentially and when a match is found, the rest of the chain is skipped. Your code: if line.startswith("0"): # BLOCK 1 # elif line.endswith("0"): # BLOCK 2 # elif line.startswith("0"): # BLOCK 3 # BLOCK 3 never gets executed, since if line.startswith("0") is true, your BLOCK 1 is executed and the rest of the if-elif chain is skipped. > Have you any suggestions how I may render this code undead or should I scrap > it and create something new? I still don't get what you want to do with the code, but to make it not dead you can either: for line in blah: if line.startswith("0"): a.write(line) lists_b = line.strip().split() print lists_b elif line.endswith("0"): lists_a = line.strip().split() print lists_a or this: for line in blah: if line.startswith("0"): a.write(line) if line.endswith("0"): lists_a = line.strip().split() print lists_a elif line.startswith("0"): lists_b = line.strip().split() print lists_b depending on which one seems more readable to you. > My confusion and ineptitude is perhaps explained by my being a biologist :-( > > Thanks, > Seafoid. From fitzpadj at tcd.ie Fri Dec 18 13:22:56 2009 From: fitzpadj at tcd.ie (seafoid) Date: Fri, 18 Dec 2009 10:22:56 -0800 (PST) Subject: Line indexing in Python In-Reply-To: <26845253.post@talk.nabble.com> References: <26845253.post@talk.nabble.com> Message-ID: <26847598.post@talk.nabble.com> Hi Guys, It has been point out that it is difficult for anyone to provide suggestions if I do not outline more clearly my input file and an example of what I wish to do with it (Thanks Rory!). I mentioned it in this thread (Is creating different threads bad etiquette? If so, lesson learned!): http://old.nabble.com/Parsing-file-format-to-ensure-file-meets-criteria-to26837682.html Hope you guys may have some suggestions as I am stumped! Thanks, Seafoid :-) seafoid wrote: > > Hi Guys, > > When python reads in a file, can lines be referred to via an index? > > Example: > > for line in file: > if line[0] == '0': > a.write(line) > > This works, however, I am unsure if line[0] refers only to the first line > or the first character in all lines. > > Is there an easy way to refer to a line with the first character being a > single letter that you know? > > Thanks in advance, > Seafoid. > -- View this message in context: http://old.nabble.com/Line-indexing-in-Python-tp26845253p26847598.html Sent from the Python - python-list mailing list archive at Nabble.com. From dahl.joachim at gmail.com Fri Dec 18 13:28:56 2009 From: dahl.joachim at gmail.com (Joachim Dahl) Date: Fri, 18 Dec 2009 10:28:56 -0800 (PST) Subject: PyArg_ParseTupleAndKeywords in Python3.1 References: <0a0b822c-8d57-4816-8563-5fd8ff39f7f1@p8g2000yqb.googlegroups.com> <83f08b89-6b61-4005-9fbd-c9a01da36654@d9g2000prh.googlegroups.com> <408e4acd-3182-4d08-bcb4-d4ff1632d9c2@l13g2000yqb.googlegroups.com> <2a0f6103-3615-4d6a-bd6c-e0bfcbf37eb6@26g2000yqo.googlegroups.com> Message-ID: My mistake seems to be that I declared char a, b; instead of int a, b; Thank you for sorting this out. Joachim From sccolbert at gmail.com Fri Dec 18 13:29:52 2009 From: sccolbert at gmail.com (Chris Colbert) Date: Fri, 18 Dec 2009 19:29:52 +0100 Subject: doing cool stuff with Python and Industrial Robots.... Message-ID: <7f014ea60912181029j4481be89ob38a915d4145116d@mail.gmail.com> Im just finishing up some research work during a stint as a visiting researcher in Germany. I've made a short clip showing a KUKA robot performing object reconstruction using a single camera mounted on the robot. The entire system is written in Python (control, math, everything) and related infrastructure (Cython/NumPy/Scipy/Mayavi/etc...) I cant give any technical details yet, as I have a few papers still pending publication. But I thought you all might enjoy the video. Everyone likes big robots!!! ~60MB www.therealstevencolbert.com/dump/reco_demo.mpg The video begins by showing the ground-truth of the object rendered as a wireframe. The robot then captures three images of the object from various vantages. The software then reconstructs the shape of the object, and overlays the wireframe with the results. Cheers! Chris -------------- next part -------------- An HTML attachment was scrubbed... URL: From lie.1296 at gmail.com Fri Dec 18 13:31:19 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Sat, 19 Dec 2009 05:31:19 +1100 Subject: Raw string substitution problem In-Reply-To: References: <931375.44828.qm@web58902.mail.re1.yahoo.com> <2I-dnaKkY7MM_LfWnZ2dnUVZ_sGdnZ2d@rcn.net> <7p0q09F6qiU1@mid.individual.net> Message-ID: <4b2bca8d$1@dnews.tpgi.com.au> On 12/19/2009 4:59 AM, Alan G Isaac wrote: > On 12/18/2009 12:17 PM, MRAB wrote: >> In simple cases you might be replacing with the same string every time, >> but other cases you might want the replacement to contain substrings >> captured by the regex. > > > Of course that "conversion" is needed in the replacement. > But e.g. Vim substitutions handle this fine without the > odd (to non perlers) handling of backslashes in replacement. > > Alan Isaac Short answer: Python is not Perl, Python's re.sub is not Vim's :s. Slightly longer answer: Different environments have different need; vim-ers more often needs to escape with just a plain text. All in all, the decision for default behaviors are often made so that less backslash will be needed for the more common case in the particular environment. From pavlovevidence at gmail.com Fri Dec 18 13:39:15 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 18 Dec 2009 10:39:15 -0800 (PST) Subject: iterators and views of lists References: <89604fb4-9dfa-45f1-a3df-f676cd4353ea@x5g2000prf.googlegroups.com> <87b87511-744c-450e-a024-976f8c57f032@15g2000prz.googlegroups.com> <00b47124$0$15654$c3e8da3@news.astraweb.com> Message-ID: On Dec 17, 10:00?pm, Brendan Miller wrote: > On Thu, Dec 17, 2009 at 6:44 PM, Steven D'Aprano > > wrote: > > On Thu, 17 Dec 2009 12:07:59 -0800, Brendan Miller wrote: > > >> I was thinking it would be cool to make python more usable in > >> programming competitions by giving it its own port of the STL's > >> algorithm library, which needs something along the lines of C++'s more > >> powerful iterators. > > > For the benefit of those of us who aren't C++ programmers, what do its > > iterators do that Python's don't? > > Python iterators basically only have one operation: > > next(), which returns the next element or throws StopIteration. > > In C++ terminology this is a Input iterator. It is good for writing > "for each" loops or map reduce operations. Hmm. I guess the main thing that's bothering me about this whole thread is that the true power of Python iterators is being overlooked here, and I don't think you're being fair to call Python iterators "weak" (as you did in another thread) or say that they are only good for for-else type loops. The fact is, Python iterators have a whole range of powers that C++ iterators do not. C++ iterators, at least the ones that come in STL, are limited to iterating over pre-existing data structures. Python iterators don't have this limation--the data being "iterated" over can be virtual data like an infinite list, or data generated on the fly. This can be very powerful. Here's a cool slideshow on what can be done with iterators in Python (generators specifically): http://www.dabeaz.com/generators/ It is true that Python iterators can't be used to mutate the underlying structure--if there is actual underlying data structure-- but it doesn't mean they are weak or limited. Python and C++ iterators are similar in their most basic usage, but grow more powerful in different directions. Carl Banks From sturlamolden at yahoo.no Fri Dec 18 13:44:29 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Fri, 18 Dec 2009 10:44:29 -0800 (PST) Subject: shouldn't list comprehension be faster than for loops? References: <979c8ffe-dc39-4b2b-ab9b-12ecefc12d7a@y24g2000yqb.googlegroups.com> Message-ID: <8808c896-0bb9-42e0-aa61-319adadf31d1@b2g2000yqi.googlegroups.com> On 17 Des, 18:37, Carlos Grohmann wrote: > Tenting the time spent by each approach (using time.clock()), with a > file with about 100,000 entries, I get 0.03s for the loop and 0.05s > for the listcomp. > > thoughts? Anything else being equal, list comprehensions will be the faster becuase they incur fewer name and attribute lookups. It will be the same as the difference between a for loop and a call to map. A list comprehension is basically an enhancement of map. From sturlamolden at yahoo.no Fri Dec 18 13:49:52 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Fri, 18 Dec 2009 10:49:52 -0800 (PST) Subject: shouldn't list comprehension be faster than for loops? References: <979c8ffe-dc39-4b2b-ab9b-12ecefc12d7a@y24g2000yqb.googlegroups.com> Message-ID: On 17 Des, 18:42, "Alf P. Steinbach" wrote: > Have you tried this with > > ? ?dip1 = [dp - 0.01 if dp == 90 else dp for dp in dipList] And for comparison with map: map(lambda dp: dp - 0.01 if dp == 90 else dp, dipList) From pavlovevidence at gmail.com Fri Dec 18 13:50:00 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 18 Dec 2009 10:50:00 -0800 (PST) Subject: shouldn't list comprehension be faster than for loops? References: <979c8ffe-dc39-4b2b-ab9b-12ecefc12d7a@y24g2000yqb.googlegroups.com> Message-ID: On Dec 17, 9:37?am, Carlos Grohmann wrote: > Tenting the time spent by each approach (using time.clock()), with a > file with about 100,000 entries, I get 0.03s for the loop and 0.05s > for the listcomp. > > thoughts? You shouldn't trust your intuition in things like this. Some features were added to Python to make writing easier, not to make it run faster. This time your intuition was correct. Next time, who knows? Carl Banks From sturlamolden at yahoo.no Fri Dec 18 13:55:03 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Fri, 18 Dec 2009 10:55:03 -0800 (PST) Subject: shouldn't list comprehension be faster than for loops? References: <979c8ffe-dc39-4b2b-ab9b-12ecefc12d7a@y24g2000yqb.googlegroups.com> Message-ID: <19566c8e-09d7-41ed-9b4a-ea8f7b3aedd7@b2g2000yqi.googlegroups.com> On 17 Des, 18:37, Carlos Grohmann wrote: > Tenting the time spent by each approach (using time.clock()), with a > file with about 100,000 entries, I get 0.03s for the loop and 0.05s > for the listcomp. > > thoughts? Let me ask a retoric question: - How much do you really value 20 ms of CPU time? From victorsubervi at gmail.com Fri Dec 18 13:55:09 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Fri, 18 Dec 2009 14:55:09 -0400 Subject: How Do I...? Message-ID: <4dc0cfea0912181055o4da24927n4776b197efd5943@mail.gmail.com> Hi; I have this code: i = 0 nameNos = [] nos = [] for option in ourOptions(): nameNos.append('optionNo%d' % i) nos.append(i) i += 1 The idea is that through every iteration of option, I can create a new variable such as 'optionNo0', 'optionNo1' etc and assign values such as '0', '1' etc to them. Of course that code doesn't work. What would? TIA, Victor -------------- next part -------------- An HTML attachment was scrubbed... URL: From lie.1296 at gmail.com Fri Dec 18 13:57:21 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Sat, 19 Dec 2009 05:57:21 +1100 Subject: subprocess.Popen and ordering writes to stdout and stderr In-Reply-To: References: Message-ID: <4b2bd0a7$1@dnews.tpgi.com.au> On 12/18/2009 8:15 AM, Chris Withers wrote: > > ....the order of the writes isn't preserved. > How can I get this to be the case? > You'll need to flush the std{out|err} or set them unbuffered; or you can just forget about relying on std{out|err} being ordered per write-order. From albert at spenarnc.xs4all.nl Fri Dec 18 14:04:33 2009 From: albert at spenarnc.xs4all.nl (Albert van der Horst) Date: 18 Dec 2009 19:04:33 GMT Subject: How to create a docstring for a module? References: <26662729.post@talk.nabble.com> <50697b2c0912061306i29d5faf9q9c25357c85652e44@mail.gmail.com> Message-ID: In article , alex23 wrote: >"Phillip M. Feldman" wrote: >> It does seem as though IPython could be a bit more clever about this. =A0 > >I disagree. I _like_ that IPython is only reporting on the current >state of the interpreter and not trying to second guess what I meant. > >> If the user asks for documentation on xyz via "?xyz" and xyz is not >> defined, then I'd like to see IPython check for a module named "xyz" and >> if it exists, extract and display the docstring. > >How would you recommend IPython distinguish between which "xyz" you >meant: the one in site-packages, the one in some package on the python >path, or the one in the folder you're running IPython from? Alternatively, it could state that "xyz" is not loaded, but could be loaded from one of the places you summarize. (Kind of what Ubuntu does: hack?, I have no "hack" but such command could be installed from BSD classical games. ) Groetjes Albert. -- -- Albert van der Horst, UTRECHT,THE NETHERLANDS Economic growth -- being exponential -- ultimately falters. albert at spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst From tdoggette at gmail.com Fri Dec 18 14:04:44 2009 From: tdoggette at gmail.com (Thomas Doggette) Date: Fri, 18 Dec 2009 11:04:44 -0800 (PST) Subject: Using ZODB (or something else) for storing lots of metadata about RSS/Atom feeds and posts Message-ID: I'm working on (or rather, at this point, planning) a project that will involve keeping track of every post in a large number of Atom feeds, as well as a lot of metadata about how posts are linked and how users interact with them. The idea of having all of these be persistent objects is very appealing, but I'm not sure the ZODB is ideal for what I'm doing. Can people with more experience working with data sets like this give me some advice on what they've had luck using? From alfps at start.no Fri Dec 18 14:08:27 2009 From: alfps at start.no (Alf P. Steinbach) Date: Fri, 18 Dec 2009 20:08:27 +0100 Subject: iterators and views of lists In-Reply-To: References: <89604fb4-9dfa-45f1-a3df-f676cd4353ea@x5g2000prf.googlegroups.com> <87b87511-744c-450e-a024-976f8c57f032@15g2000prz.googlegroups.com> <00b47124$0$15654$c3e8da3@news.astraweb.com> Message-ID: * Carl Banks: > On Dec 17, 10:00 pm, Brendan Miller wrote: >> On Thu, Dec 17, 2009 at 6:44 PM, Steven D'Aprano >> >> wrote: >>> On Thu, 17 Dec 2009 12:07:59 -0800, Brendan Miller wrote: >>>> I was thinking it would be cool to make python more usable in >>>> programming competitions by giving it its own port of the STL's >>>> algorithm library, which needs something along the lines of C++'s more >>>> powerful iterators. >>> For the benefit of those of us who aren't C++ programmers, what do its >>> iterators do that Python's don't? >> Python iterators basically only have one operation: >> >> next(), which returns the next element or throws StopIteration. >> >> In C++ terminology this is a Input iterator. It is good for writing >> "for each" loops or map reduce operations. > > Hmm. I guess the main thing that's bothering me about this whole > thread is that the true power of Python iterators is being overlooked > here, and I don't think you're being fair to call Python iterators > "weak" (as you did in another thread) or say that they are only good > for for-else type loops. > > The fact is, Python iterators have a whole range of powers that C++ > iterators do not. C++ iterators, at least the ones that come in STL, > are limited to iterating over pre-existing data structures. Python > iterators don't have this limation--the data being "iterated" over can > be virtual data like an infinite list, or data generated on the fly. > This can be very powerful. It's good that Python iterators can do things. However, it's not the case that C++ iterators can't do those things. C++ iterators very much routinely do such things. However, C++ iterators are flawed in a way that Python iterators are not. You might say, in an analogy with control structures, that this flaw gives C++ iterators the power of "goto" but also with all the negative baggage... I'm too lazy to Google, but you might search for Alexandrescu and "ranges", and possibly throw in "iterators" among the search terms. Cheers & hth., - Alf From kevin.p.dwyer at gmail.com Fri Dec 18 14:18:12 2009 From: kevin.p.dwyer at gmail.com (Kev Dwyer) Date: Fri, 18 Dec 2009 19:18:12 +0000 (UTC) Subject: Help with invoking standard mail app in windows References: <4B2BC252.3060509@al.com.au> Message-ID: On Sat, 19 Dec 2009 04:56:34 +1100, Astan Chee wrote: > Hi, > I don't know if my last mail made it or not but here it is again. I'm > trying to launch standard mail app in windows and after looking around > most look like this: > > import urllib, webbrowser, win32api > def mailto_url(to=None,subject=None,body=None,cc=None): > """ > encodes the content as a mailto link as described on > http://www.faqs.org/rfcs/rfc2368.html """ > url = "mailto: " + urllib.quote(to.strip(),"@,") sep = "?" > if cc: > url+= sep + "cc=" + urllib.quote(cc,"@,") sep = "&" > if subject: > url+= sep + "subject=" + urllib.quote(subject,"") sep = "&" > if body: > # Also note that line breaks in the body of a message MUST be # > encoded with "%0D%0A". (RFC 2368) > body="\r\n".join(body.splitlines()) > url+= sep + "body=" + urllib.quote(body,"") sep = "&" > return url > > url = mailto_url(txtTo,txtSubject,body,txtCC) # > win32api.ShellExecute(0,'open',url,None,None,0) > webbrowser.open(url,new=1) > # os.startfile(url) > > all of these are having "WindowsError : [Error 5] Access is denied" > errors. I'm using windows xp and python 2.5. I have outlook 2007 > installed as a default mail client. Clicking on any mailto links in html > brings up the normal write mail from the mail client. Any ideas why this > is happening or how do I debug what access is being denied? Thanks for > any help > Astan Hello Astan, Your code executes without error for me on Win98 (!) with Python 2.5 or XP with Python 2.6. It would help people to help you if you could provide the *exact* console output from when you try to execute the code, *including* the traceback. That way we can work out which line of code is hitting the exception. Cheers, Kev From lie.1296 at gmail.com Fri Dec 18 14:20:41 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Sat, 19 Dec 2009 06:20:41 +1100 Subject: iterators and views of lists In-Reply-To: References: <89604fb4-9dfa-45f1-a3df-f676cd4353ea@x5g2000prf.googlegroups.com> <87b87511-744c-450e-a024-976f8c57f032@15g2000prz.googlegroups.com> Message-ID: <4b2bd61f$1@dnews.tpgi.com.au> On 12/18/2009 7:07 AM, Brendan Miller wrote: > As for copying pointers not taking much time... that depends on how > long the list is. if you are working with small sets of data, you can > do almost anything and it will be efficient. However, if you have > megabytes or gigabytes of data (say you are working with images or > video), than the difference between an O(1) or an O(n) operation is a > big deal. A 1-million member list takes ~130 msec, 10 million 1.3s. In many cases the algorithm would easily dwarf the copying itself. From fitzpadj at tcd.ie Fri Dec 18 14:21:14 2009 From: fitzpadj at tcd.ie (seafoid) Date: Fri, 18 Dec 2009 11:21:14 -0800 (PST) Subject: Creating Classes Message-ID: <26848375.post@talk.nabble.com> Hey Guys, I have started to read over classes as a brief respite from my parsing problem. When a class is defined, how does the class access the data upon which the class should act? Example: class Seq: def __init__(self, data, alphabet = Alphabet.generic_alphabet): self.data = data self.alphabet = alphabet def tostring(self): return self.data def tomutable(self): return MutableSeq(self.data, self.alphabet) def count(self, item): return len([x for x in self.data if x == item]) I know what it should do, but have no idea how to feed it the data. Methinks I need to invest in actual computing books as learning from biologists is hazy! Kind regards, Seafoid. -- View this message in context: http://old.nabble.com/Creating-Classes-tp26848375p26848375.html Sent from the Python - python-list mailing list archive at Nabble.com. From mailings at julianmoritz.de Fri Dec 18 14:25:09 2009 From: mailings at julianmoritz.de (Julian) Date: Fri, 18 Dec 2009 11:25:09 -0800 (PST) Subject: Design question about pretree classifier References: <7351dfbf-90a2-4303-b3d8-2377dcd2698e@o28g2000yqh.googlegroups.com> Message-ID: <363f760a-1032-4858-bcab-fba248f58c25@o28g2000yqh.googlegroups.com> On 18 Dez., 18:59, Steve Holden wrote: > Julian wrote: > > Hello, > > > I've got a design problem for a classifier. To make it short: it maps > > strings on strings. > > > Some strings have exactly one classification, some none and some more > > than one. > > > There's a method classify(self, word) wich classifies a word. For the > > first case there's no problem: > > > - one classification: return the value (it's a string) > > > But: > > > - none classification: return an exception or None? I think None is > > better, hence its not an exception that there is no classification but > > a defined state. What do you think? > > - many classifications: what to do? retun a sequence of strings? raise > > an exception and implement another method wich returns than the > > classifications? what should I do here? > > > thanks for your answers! > > Always return a list or tuple. For no classifications it should be > empty, for one classification it should have one element, ... , for N > classifications it should have N elements. > thanks, sounds simple and good! > regards > ?Steve > -- > Steve Holden ? ? ? ? ? +1 571 484 6266 ? +1 800 494 3119 > Holden Web LLC ? ? ? ? ? ? ? ?http://www.holdenweb.com/ > UPCOMING EVENTS: ? ? ? ?http://holdenweb.eventbrite.com/ From pavlovevidence at gmail.com Fri Dec 18 14:32:52 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 18 Dec 2009 11:32:52 -0800 (PST) Subject: iterators and views of lists References: <89604fb4-9dfa-45f1-a3df-f676cd4353ea@x5g2000prf.googlegroups.com> <87b87511-744c-450e-a024-976f8c57f032@15g2000prz.googlegroups.com> <00b47124$0$15654$c3e8da3@news.astraweb.com> Message-ID: On Dec 18, 11:08?am, "Alf P. Steinbach" wrote: > * Carl Banks: > > > > > On Dec 17, 10:00 pm, Brendan Miller wrote: > >> On Thu, Dec 17, 2009 at 6:44 PM, Steven D'Aprano > > >> wrote: > >>> On Thu, 17 Dec 2009 12:07:59 -0800, Brendan Miller wrote: > >>>> I was thinking it would be cool to make python more usable in > >>>> programming competitions by giving it its own port of the STL's > >>>> algorithm library, which needs something along the lines of C++'s more > >>>> powerful iterators. > >>> For the benefit of those of us who aren't C++ programmers, what do its > >>> iterators do that Python's don't? > >> Python iterators basically only have one operation: > > >> next(), which returns the next element or throws StopIteration. > > >> In C++ terminology this is a Input iterator. It is good for writing > >> "for each" loops or map reduce operations. > > > Hmm. ?I guess the main thing that's bothering me about this whole > > thread is that the true power of Python iterators is being overlooked > > here, and I don't think you're being fair to call Python iterators > > "weak" (as you did in another thread) or say that they are only good > > for for-else type loops. > > > The fact is, Python iterators have a whole range of powers that C++ > > iterators do not. ?C++ iterators, at least the ones that come in STL, > > are limited to iterating over pre-existing data structures. ?Python > > iterators don't have this limation--the data being "iterated" over can > > be virtual data like an infinite list, or data generated on the fly. > > This can be very powerful. > > It's good that Python iterators can do things. > > However, it's not the case that C++ iterators can't do those things. > > C++ iterators very much routinely do such things. STL Iterators? No. Maybe if you're talking about boost or homemade iterators or something I could buy it, though I'd still bs suspicious of "routinely". > However, C++ iterators are flawed in a way that Python iterators are not. > > You might say, in an analogy with control structures, that this flaw gives C++ > iterators the power of "goto" but also with all the negative baggage... That too. > I'm too lazy to Google, but you might search for Alexandrescu and "ranges", and > possibly throw in "iterators" among the search terms. Carl Banks From astan.chee at al.com.au Fri Dec 18 14:36:32 2009 From: astan.chee at al.com.au (Astan Chee) Date: Sat, 19 Dec 2009 06:36:32 +1100 Subject: Help with invoking standard mail app in windows In-Reply-To: References: <4B2BC252.3060509@al.com.au> Message-ID: <4B2BD9C0.7070509@al.com.au> Kev Dwyer wrote: > Hello Astan, > > Your code executes without error for me on Win98 (!) with Python 2.5 or > XP with Python 2.6. > > It would help people to help you if you could provide the *exact* console > output from when you try to execute the code, *including* the traceback. > That way we can work out which line of code is hitting the exception. > > Cheers, > > Kev > > Hi, My mistake. The length of body is over 1400 characters. Here is my updated code and result: import urllib, webbrowser, win32api def mailto_url(to=None,subject=None,body=None,cc=None): """ encodes the content as a mailto link as described on http://www.faqs.org/rfcs/rfc2368.html """ url = "mailto: " + urllib.quote(to.strip(),"@,") sep = "?" if cc: url+= sep + "cc=" + urllib.quote(cc,"@,") sep = "&" if subject: url+= sep + "subject=" + urllib.quote(subject,"") sep = "&" if body: # Also note that line breaks in the body of a message MUST be # encoded with "%0D%0A". (RFC 2368) body="\r\n".join(body.splitlines()) url+= sep + "body=" + urllib.quote(body,"") sep = "&" return url txtTo = "test at com.com" txtSubject = "Test Subject" body = "Test body" for t in range(278): body+="test " txtCC = "cc_test at com.com" url = mailto_url(txtTo,txtSubject,body,txtCC) #win32api.ShellExecute(0,'open',url,None,None,0) webbrowser.open(url,new=1) # os.startfile(url) result: Traceback (most recent call last): File "C:/stanc_home/python/mail_test.py", line 32, in webbrowser.open(url,new=1) File "C:\Python25\lib\webbrowser.py", line 61, in open if browser.open(url, new, autoraise): File "C:\Python25\lib\webbrowser.py", line 518, in open os.startfile(url) WindowsError: [Error 5] Access is denied: 'mailto: test at com.com?cc=cc_test at com.com&subject=Test%20Subject&body=Test%20bodytest%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test%20' Is there some sort of limitation here? If I shorten the string, it works fine. You're right, but I'm wondering if there is a way to go around this limitation. Thanks again Cheers Astan From rami.chowdhury at gmail.com Fri Dec 18 14:46:47 2009 From: rami.chowdhury at gmail.com (Rami Chowdhury) Date: Fri, 18 Dec 2009 11:46:47 -0800 Subject: How Do I...? In-Reply-To: <4dc0cfea0912181055o4da24927n4776b197efd5943@mail.gmail.com> References: <4dc0cfea0912181055o4da24927n4776b197efd5943@mail.gmail.com> Message-ID: <2f79f590912181146j4120a3e2ldb51a526026ac0cb@mail.gmail.com> On Fri, Dec 18, 2009 at 10:55, Victor Subervi wrote: > Hi; > I have this code: > > ??? i = 0 > ??? nameNos = [] > ??? nos = [] > ??? for option in ourOptions(): > ????? nameNos.append('optionNo%d' % i) > ????? nos.append(i) > ????? i += 1 > > The idea is that through every iteration of option, I can create a new > variable such as 'optionNo0', 'optionNo1' etc and assign values such as '0', > '1' etc to them. What are you expecting to do with those variables and values later? -- Rami Chowdhury "Never assume malice when stupidity will suffice." -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) From victorsubervi at gmail.com Fri Dec 18 14:51:04 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Fri, 18 Dec 2009 15:51:04 -0400 Subject: How Do I...? In-Reply-To: <2f79f590912181146j4120a3e2ldb51a526026ac0cb@mail.gmail.com> References: <4dc0cfea0912181055o4da24927n4776b197efd5943@mail.gmail.com> <2f79f590912181146j4120a3e2ldb51a526026ac0cb@mail.gmail.com> Message-ID: <4dc0cfea0912181151u3a5c6c4dm6d7ec096ed01438d@mail.gmail.com> On Fri, Dec 18, 2009 at 3:46 PM, Rami Chowdhury wrote: > On Fri, Dec 18, 2009 at 10:55, Victor Subervi > wrote: > > Hi; > > I have this code: > > > > i = 0 > > nameNos = [] > > nos = [] > > for option in ourOptions(): > > nameNos.append('optionNo%d' % i) > > nos.append(i) > > i += 1 > > > > The idea is that through every iteration of option, I can create a new > > variable such as 'optionNo0', 'optionNo1' etc and assign values such as > '0', > > '1' etc to them. > > What are you expecting to do with those variables and values later? > :-} I discovered after I wrote this that all I had to do was use the length of ourOptions. But it's an interesting academic question for future reference ;/ V -------------- next part -------------- An HTML attachment was scrubbed... URL: From python.list at tim.thechases.com Fri Dec 18 15:03:48 2009 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 18 Dec 2009 14:03:48 -0600 Subject: How Do I...? In-Reply-To: <4dc0cfea0912181055o4da24927n4776b197efd5943@mail.gmail.com> References: <4dc0cfea0912181055o4da24927n4776b197efd5943@mail.gmail.com> Message-ID: <4B2BE024.4010307@tim.thechases.com> Victor Subervi wrote: > How do I...? Well, you start by reading a book on how to program. You would then learn that what you want (in all likelihood) is a dictionary/map structure for dynamically created key/value pairs. Once you have progressed from your current apprenticeship and achieved the rank of third-degree journeyman programmer, the ways of dynamic variable creation will avail themselves. > i = 0 > nameNos = [] > nos = [] > for option in ourOptions(): > nameNos.append('optionNo%d' % i) > nos.append(i) > i += 1 > > The idea is that through every iteration of option, I can create a new > variable such as 'optionNo0', 'optionNo1' etc and assign values such as '0', > '1' etc to them. Of course that code doesn't work. What would? As stated above, you want a dictionary where your keys are 'optionNo%d' % i and your values are "i". You can also use the more idiomatic for i, option in enumerate(ourOptions()): ... and skip the manual initialization and incrementation of "i". Or even more succinctly, you could pass the above as a generator to the dict() initialization. But that's a level-2 apprentice bit of code. Patience grasshopper. And as additional weirdness, you don't actually make use of "option" in your for-loop... -tkc From alfps at start.no Fri Dec 18 15:18:04 2009 From: alfps at start.no (Alf P. Steinbach) Date: Fri, 18 Dec 2009 21:18:04 +0100 Subject: iterators and views of lists In-Reply-To: References: <89604fb4-9dfa-45f1-a3df-f676cd4353ea@x5g2000prf.googlegroups.com> <87b87511-744c-450e-a024-976f8c57f032@15g2000prz.googlegroups.com> <00b47124$0$15654$c3e8da3@news.astraweb.com> Message-ID: * Carl Banks: > On Dec 18, 11:08 am, "Alf P. Steinbach" wrote: >> * Carl Banks: >> >> >> >>> On Dec 17, 10:00 pm, Brendan Miller wrote: >>>> On Thu, Dec 17, 2009 at 6:44 PM, Steven D'Aprano >>>> wrote: >>>>> On Thu, 17 Dec 2009 12:07:59 -0800, Brendan Miller wrote: >>>>>> I was thinking it would be cool to make python more usable in >>>>>> programming competitions by giving it its own port of the STL's >>>>>> algorithm library, which needs something along the lines of C++'s more >>>>>> powerful iterators. >>>>> For the benefit of those of us who aren't C++ programmers, what do its >>>>> iterators do that Python's don't? >>>> Python iterators basically only have one operation: >>>> next(), which returns the next element or throws StopIteration. >>>> In C++ terminology this is a Input iterator. It is good for writing >>>> "for each" loops or map reduce operations. >>> Hmm. I guess the main thing that's bothering me about this whole >>> thread is that the true power of Python iterators is being overlooked >>> here, and I don't think you're being fair to call Python iterators >>> "weak" (as you did in another thread) or say that they are only good >>> for for-else type loops. >>> The fact is, Python iterators have a whole range of powers that C++ >>> iterators do not. C++ iterators, at least the ones that come in STL, >>> are limited to iterating over pre-existing data structures. Python >>> iterators don't have this limation--the data being "iterated" over can >>> be virtual data like an infinite list, or data generated on the fly. >>> This can be very powerful. >> It's good that Python iterators can do things. >> >> However, it's not the case that C++ iterators can't do those things. >> >> C++ iterators very much routinely do such things. > > STL Iterators? No. Maybe if you're talking about boost or homemade > iterators or something I could buy it, though I'd still bs suspicious > of "routinely". The intersection of STL and the C++ standard library is of nearly the same size as the STL, but I don't understand why you're limiting yourself to the STL. After all, the STL was first developed for the Ada language, IIRC. Using the standard C++ library, per the 1998 first (and current!) C++ standard, below is an idiomatic "copy Carl Banks to output" C++ program where, you might note, the "ostream_iterator" has a sister "istream_iterator" that definitely does not only iterat over a "pre-existing data structure", as you wrote. Of course, mostly one defines iterators in the source code or by using Boost or similar libraries; that's how C++ works. There's no special language support for iterators in C++; it's wholly a library and application defined concept. #include #include #include #include int main() { using namespace std; static char const* const words[] = { "Carl", "Banks", "is", "wrong", "on", "the", "Internet", "!" }; copy( words, words + sizeof(words)/sizeof(*words), ostream_iterator( cout, "\n" ) ); } Cheers & hth., - Alf From kevin.p.dwyer at gmail.com Fri Dec 18 15:24:06 2009 From: kevin.p.dwyer at gmail.com (Kev Dwyer) Date: Fri, 18 Dec 2009 20:24:06 +0000 (UTC) Subject: Help with invoking standard mail app in windows References: <4B2BC252.3060509@al.com.au> <4B2BD9C0.7070509@al.com.au> Message-ID: On Sat, 19 Dec 2009 06:36:32 +1100, Astan Chee wrote: > Kev Dwyer wrote: >> Hello Astan, >> >> Your code executes without error for me on Win98 (!) with Python 2.5 or >> XP with Python 2.6. >> >> It would help people to help you if you could provide the *exact* >> console output from when you try to execute the code, *including* the >> traceback. That way we can work out which line of code is hitting the >> exception. >> >> Cheers, >> >> Kev >> >> > Hi, > My mistake. The length of body is over 1400 characters. Here is my > updated code and result: > > import urllib, webbrowser, win32api > def mailto_url(to=None,subject=None,body=None,cc=None): > """ > encodes the content as a mailto link as described on > http://www.faqs.org/rfcs/rfc2368.html """ url = "mailto: " + > urllib.quote(to.strip(),"@,") sep = "?" > if cc: > url+= sep + "cc=" + urllib.quote(cc,"@,") sep = "&" > if subject: > url+= sep + "subject=" + urllib.quote(subject,"") sep = "&" > if body: > # Also note that line breaks in the body of a message MUST be # > encoded with "%0D%0A". (RFC 2368) > body="\r\n".join(body.splitlines()) > url+= sep + "body=" + urllib.quote(body,"") sep = "&" > return url > > txtTo = "test at com.com" > txtSubject = "Test Subject" > body = "Test body" > for t in range(278): > body+="test " > txtCC = "cc_test at com.com" > > url = mailto_url(txtTo,txtSubject,body,txtCC) > #win32api.ShellExecute(0,'open',url,None,None,0) > webbrowser.open(url,new=1) > # os.startfile(url) > > result: > > Traceback (most recent call last): > File "C:/stanc_home/python/mail_test.py", line 32, in > webbrowser.open(url,new=1) > File "C:\Python25\lib\webbrowser.py", line 61, in open > if browser.open(url, new, autoraise): > File "C:\Python25\lib\webbrowser.py", line 518, in open > os.startfile(url) > WindowsError: [Error 5] Access is denied: 'mailto: > test at com.com?cc=cc_test at com.com&subject=Test%20Subject&body=Test% 20bodytest%20test%20test%20test%20test%20test%20test%20test%20test%20test% 20test%20test%20test%20test%20test%20test%20test%20test%20test%20test% 20test%20test%20test%20test%20test%20test%20test%20test%20test%20test% 20test%20test%20test%20test%20test%20test%20test%20test%20test%20test% 20test%20test%20test%20test%20test%20test%20test%20test%20test%20test% 20test%20test%20test%20test%20test%20test%20test%20test%20test%20test% 20test%20test%20test%20test%20test%20test%20test%20test%20test%20test% 20test%20test%20test%20test%20test%20test%20test%20test%20test%20test% 20test%20test%20test%20test%20test%20test%20test%20test%20test%20test% 20test%20test%20test%20test%20test%20test%20test%20test%20test%20test% 20test%20test%20test%20test%20t > est%20test%20test%20test%20test%20test%20test%20test%20test%20test% 20test%20test%20test%20test%20test%20test%20test%20test%20test%20test% 20test%20test%20test%20test%20test%20test%20test%20te > st%20test%20test%20test%20test%20test%20test%20test%20test%20test% 20test%20test%20test%20test%20test%20test%20test%20test%20test%20test% 20test%20test%20test%20test%20test%20test%20test%20test%20test%20test% 20test%20test%20test%20test%20test%20test%20test%20test%20test%20test% 20test%20test%20test%20test%20test%20test%20test%20test%20test%20test% 20test%20test%20test%20test%20test%20test%20test%20test%20test%20test% 20test%20test%20test%20test%20test%20test%20test%20test%20test%20test% 20test%20test%20test%20test%20test%20test%20test%20test%20test%20test% 20test%20test%20test%20test%20test%20test%20test%20test%20test%20test% 20test%20test%20test%20test%20test%20test%20test%20test%20test%20test% 20test%20test%20test%20test%20test%20test%20test%20test%20test%20test% 20test%20test%20test%20test%20tes > t%20test%20test%20test%20test%20test%20test%20test%20test%20test%20test %20test%20test%20test%20test%20test%20test%20test%20test%20test%20test% 20test%20test%20test%20test%20test%20test%20test > %20test%20test%20test%20test%20test%20' > > Is there some sort of limitation here? If I shorten the string, it works > fine. You're right, but I'm wondering if there is a way to go around > this limitation. > Thanks again > Cheers > Astan Hmmm. For me, body < 1400 opens an outlook message form, body > 1400 opens IE7. No time to look into this right now, but perhaps this is a windows thing. Don't know why you get windowserror, perhaps permissions??? I'll try and look again later/tomorrow. Cheers, Kev From Brian.Mingus at Colorado.EDU Fri Dec 18 15:44:29 2009 From: Brian.Mingus at Colorado.EDU (Brian J Mingus) Date: Fri, 18 Dec 2009 13:44:29 -0700 Subject: shouldn't list comprehension be faster than for loops? In-Reply-To: <19566c8e-09d7-41ed-9b4a-ea8f7b3aedd7@b2g2000yqi.googlegroups.com> References: <979c8ffe-dc39-4b2b-ab9b-12ecefc12d7a@y24g2000yqb.googlegroups.com> <19566c8e-09d7-41ed-9b4a-ea8f7b3aedd7@b2g2000yqi.googlegroups.com> Message-ID: <9839a05c0912181244k1554856ateb0dc93ab1b6acd@mail.gmail.com> On Fri, Dec 18, 2009 at 11:55 AM, sturlamolden wrote: > On 17 Des, 18:37, Carlos Grohmann wrote: > > > Tenting the time spent by each approach (using time.clock()), with a > > file with about 100,000 entries, I get 0.03s for the loop and 0.05s > > for the listcomp. > > > > thoughts? > > Let me ask a retoric question: > > - How much do you really value 20 ms of CPU time? > If it takes 1 nanosecond to execute a single instruction then 20 milliseconds represents 20 million instructions. Therefore I value 20ms of CPU time very much indeed. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at holdenweb.com Fri Dec 18 16:09:28 2009 From: steve at holdenweb.com (Steve Holden) Date: Fri, 18 Dec 2009 16:09:28 -0500 Subject: Creating Classes In-Reply-To: <26848375.post@talk.nabble.com> References: <26848375.post@talk.nabble.com> Message-ID: seafoid wrote: > Hey Guys, > > I have started to read over classes as a brief respite from my parsing > problem. > > When a class is defined, how does the class access the data upon which the > class should act? > > Example: > > class Seq: > > def __init__(self, data, alphabet = Alphabet.generic_alphabet): > self.data = data > self.alphabet = alphabet > > def tostring(self): > return self.data > > def tomutable(self): > return MutableSeq(self.data, self.alphabet) > > def count(self, item): > return len([x for x in self.data if x == item]) > > I know what it should do, but have no idea how to feed it the data. > > Methinks I need to invest in actual computing books as learning from > biologists is hazy! > > Kind regards, > Seafoid. > Supposing you create an instance of your Seq class seq = Seq("aggadgaga") When you call (let's say) the tostring() method of the *instance* the interpreter automatically provides that as the first (self) argument to the method call. So in fact seq.tostring() is exactly the same as Seq.tostring(seq) but considerably shorter and easier to understand. Try asking the interpreter what Seq.tostring and seq.tostring are, and you will find one is an unbound method", the other is a "bound method" (which means "bound to a given instance" - in other words, it "knows" which instance it's a method *of*. Does this clarify it or make it more obscure? regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ UPCOMING EVENTS: http://holdenweb.eventbrite.com/ From catphive at catphive.net Fri Dec 18 16:10:28 2009 From: catphive at catphive.net (Brendan Miller) Date: Fri, 18 Dec 2009 13:10:28 -0800 Subject: iterators and views of lists In-Reply-To: References: <89604fb4-9dfa-45f1-a3df-f676cd4353ea@x5g2000prf.googlegroups.com> <87b87511-744c-450e-a024-976f8c57f032@15g2000prz.googlegroups.com> <00b47124$0$15654$c3e8da3@news.astraweb.com> Message-ID: On Fri, Dec 18, 2009 at 10:39 AM, Carl Banks wrote: > On Dec 17, 10:00?pm, Brendan Miller wrote: >> On Thu, Dec 17, 2009 at 6:44 PM, Steven D'Aprano >> >> wrote: >> > On Thu, 17 Dec 2009 12:07:59 -0800, Brendan Miller wrote: >> >> >> I was thinking it would be cool to make python more usable in >> >> programming competitions by giving it its own port of the STL's >> >> algorithm library, which needs something along the lines of C++'s more >> >> powerful iterators. >> >> > For the benefit of those of us who aren't C++ programmers, what do its >> > iterators do that Python's don't? >> >> Python iterators basically only have one operation: >> >> next(), which returns the next element or throws StopIteration. >> >> In C++ terminology this is a Input iterator. It is good for writing >> "for each" loops or map reduce operations. > > Hmm. ?I guess the main thing that's bothering me about this whole > thread is that the true power of Python iterators is being overlooked > here, and I don't think you're being fair to call Python iterators > "weak" (as you did in another thread) or say that they are only good > for for-else type loops. > > The fact is, Python iterators have a whole range of powers that C++ > iterators do not. ?C++ iterators, at least the ones that come in STL, > are limited to iterating over pre-existing data structures. ?Python > iterators don't have this limation--the data being "iterated" over can > be virtual data like an infinite list, or data generated on the fly. > This can be very powerful. > > Here's a cool slideshow on what can be done with iterators in Python > (generators specifically): > > http://www.dabeaz.com/generators/ > > It is true that Python iterators can't be used to mutate the > underlying structure--if there is actual underlying data structure-- > but it doesn't mean they are weak or limited. ?Python and C++ > iterators are similar in their most basic usage, but grow more > powerful in different directions. > When I said they are "weak" I meant it in sense that the algorithms writeable against an InputerIterator interface (which is what python's iterator protocol provides) is a proper subset of the algorithms that can be written against a RandomAccessIterator interface. The class of algorithms expressible against a python iterator is indeed limited to those that can be expressed with a for each loop or map/reduce operation. Yes, python iterators can indeed iterate over infinite lists. All that you need to do is have the next() operation never throw. The same thing can be done in c++, or any other language that has iterators. Generators provide a convenient way to write input iterators; however, the same thing can be done in any language. It just requires more boilerplate code to keep track of the iteration state. Of course, that's not to say generators aren't important. They make it that much easier to write your own iterators, so in a practical sense, people are more likely to write their own iterators in python than in C++. From fitzpadj at tcd.ie Fri Dec 18 16:19:28 2009 From: fitzpadj at tcd.ie (seafoid) Date: Fri, 18 Dec 2009 13:19:28 -0800 (PST) Subject: Creating Classes In-Reply-To: References: <26848375.post@talk.nabble.com> Message-ID: <26849864.post@talk.nabble.com> Steve, that has indeed clarified matters! Thanks! -- View this message in context: http://old.nabble.com/Creating-Classes-tp26848375p26849864.html Sent from the Python - python-list mailing list archive at Nabble.com. From rory at campbell-lange.net Fri Dec 18 16:22:54 2009 From: rory at campbell-lange.net (Rory Campbell-Lange) Date: Fri, 18 Dec 2009 21:22:54 +0000 Subject: Line indexing in Python In-Reply-To: <26847598.post@talk.nabble.com> References: <26845253.post@talk.nabble.com> <26847598.post@talk.nabble.com> Message-ID: <20091218212254.GA22180@campbell-lange.net> On 18/12/09, seafoid (fitzpadj at tcd.ie) wrote: > http://old.nabble.com/Parsing-file-format-to-ensure-file-meets-criteria-to26837682.html Your specification is confusing. However I suggest you break it down the code so that the steps in your programme are logical. Good luck. # example psuedocode headers = {} header_clauses = {} current_header = None def header_parser (input): split input into parts make unique header desciptor check not in headers else abort with error (?) add descriptor to headers hash # eg descriptor 1 = [attrib1, attrib2, attrib3] return descriptor def clause_parser (input, current_header): if current_header is None: abort split clause into parts store in array in header_clauses [current_header] # this will make a data structure like this: # header_clauses = { # descriptor1 = {[ clause parts ], [ clause parts ], ... } # descriptor2 = {[ clause parts ], [ clause parts ], ... } def comment_parser (input) pass # now run over the file for l in lines: if l[0] == 'c': comment_parser(l) elif l[0] == 'p': current_header = header_parser(l) else: clause_parser(l, current_header) # now that we have stored everything, check the data for h in headers: attrib1, attrib2, attrib3 = headers[h] for c in header_clauses: iterate over the arrays of clause parts either adding them up or comparing them to the header attributes -- Rory Campbell-Lange Director rory at campbell-lange.net Campbell-Lange Workshop www.campbell-lange.net 0207 6311 555 3 Tottenham Street London W1T 2AF Registered in England No. 04551928 From fitzpadj at tcd.ie Fri Dec 18 16:24:54 2009 From: fitzpadj at tcd.ie (seafoid) Date: Fri, 18 Dec 2009 13:24:54 -0800 (PST) Subject: Line indexing in Python In-Reply-To: <26845253.post@talk.nabble.com> References: <26845253.post@talk.nabble.com> Message-ID: <26849921.post@talk.nabble.com> Hey folks, Is it possible to assign a list within a nested list to a variable? Example: l = [['1', '2', '3'], ['4', '5', '6']] for i in l: if i[0][1] == '1': m = i Indeed, I generally do not understand how to assign variables within a loop! Is there an easy way to 'flatten' a nested list and assign the lists to variables? Thanks, Seafoid. -- View this message in context: http://old.nabble.com/Line-indexing-in-Python-tp26845253p26849921.html Sent from the Python - python-list mailing list archive at Nabble.com. From fitzpadj at tcd.ie Fri Dec 18 16:26:58 2009 From: fitzpadj at tcd.ie (seafoid) Date: Fri, 18 Dec 2009 13:26:58 -0800 (PST) Subject: Line indexing in Python In-Reply-To: <20091218212254.GA22180@campbell-lange.net> References: <26845253.post@talk.nabble.com> <26847598.post@talk.nabble.com> <20091218212254.GA22180@campbell-lange.net> Message-ID: <26849944.post@talk.nabble.com> Rory, You are a gentleman! Thank you very much for your suggestion! Kind Regards, Seafoid. Rory Campbell-Lange wrote: > > On 18/12/09, seafoid (fitzpadj at tcd.ie) wrote: >> http://old.nabble.com/Parsing-file-format-to-ensure-file-meets-criteria-to26837682.html > > Your specification is confusing. However I suggest you break it down > the code so that the steps in your programme are logical. Good luck. > > # example psuedocode > headers = {} > header_clauses = {} > current_header = None > > def header_parser (input): > split input into parts > make unique header desciptor > check not in headers else abort with error (?) > add descriptor to headers hash > # eg descriptor 1 = [attrib1, attrib2, attrib3] > return descriptor > > def clause_parser (input, current_header): > if current_header is None: abort > split clause into parts > store in array in header_clauses [current_header] > # this will make a data structure like this: > # header_clauses = { > # descriptor1 = {[ clause parts ], [ clause parts ], ... } > # descriptor2 = {[ clause parts ], [ clause parts ], ... } > > def comment_parser (input) > pass > > # now run over the file > for l in lines: > if l[0] == 'c': > comment_parser(l) > elif l[0] == 'p': > current_header = header_parser(l) > else: > clause_parser(l, current_header) > > # now that we have stored everything, check the data > for h in headers: > attrib1, attrib2, attrib3 = headers[h] > for c in header_clauses: > iterate over the arrays of clause parts either adding them > up or comparing them to the header attributes > > -- > Rory Campbell-Lange > Director > rory at campbell-lange.net > > Campbell-Lange Workshop > www.campbell-lange.net > 0207 6311 555 > 3 Tottenham Street London W1T 2AF > Registered in England No. 04551928 > -- > http://mail.python.org/mailman/listinfo/python-list > > -- View this message in context: http://old.nabble.com/Line-indexing-in-Python-tp26845253p26849944.html Sent from the Python - python-list mailing list archive at Nabble.com. From casevh at gmail.com Fri Dec 18 16:31:54 2009 From: casevh at gmail.com (casevh) Date: Fri, 18 Dec 2009 13:31:54 -0800 (PST) Subject: PyArg_ParseTupleAndKeywords in Python3.1 References: <0a0b822c-8d57-4816-8563-5fd8ff39f7f1@p8g2000yqb.googlegroups.com> <83f08b89-6b61-4005-9fbd-c9a01da36654@d9g2000prh.googlegroups.com> <408e4acd-3182-4d08-bcb4-d4ff1632d9c2@l13g2000yqb.googlegroups.com> <2a0f6103-3615-4d6a-bd6c-e0bfcbf37eb6@26g2000yqo.googlegroups.com> Message-ID: On Dec 18, 10:28?am, Joachim Dahl wrote: > My mistake seems to be that I declared > > char a, b; > > instead of > > int a, b; > > Thank you for sorting this out. > > Joachim I think you need to initialize them, too. From pavlovevidence at gmail.com Fri Dec 18 16:35:01 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 18 Dec 2009 13:35:01 -0800 (PST) Subject: iterators and views of lists References: <89604fb4-9dfa-45f1-a3df-f676cd4353ea@x5g2000prf.googlegroups.com> <87b87511-744c-450e-a024-976f8c57f032@15g2000prz.googlegroups.com> <00b47124$0$15654$c3e8da3@news.astraweb.com> Message-ID: <45122377-919c-4fd5-8ad2-d84f4b1e3ce7@z10g2000prh.googlegroups.com> On Dec 18, 12:18?pm, "Alf P. Steinbach" wrote: [lots of tangential information snipped] > ...but I don't understand why you're limiting yourself to the STL. Because I believe the vast majority of iterators used in C++ in practice are the ones provided by STL types, therefore I felt a statement about the STL iterators reflected the commonly used power (if not the ultimate capability) of iterators in C++. I suppose it was a bit hasty. > ... "ostream_iterator" ... Well that's a good example. I retract my statement that C++ iterators in general not having this power, but I still doubt that C++ iterators are used like this much. In most code I've seen people use STL or similar data structures, and then use the iterators for the particular data type, and/or pointers. Carl Banks From tjreedy at udel.edu Fri Dec 18 16:45:38 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 18 Dec 2009 16:45:38 -0500 Subject: iterators and views of lists In-Reply-To: References: <89604fb4-9dfa-45f1-a3df-f676cd4353ea@x5g2000prf.googlegroups.com> <87b87511-744c-450e-a024-976f8c57f032@15g2000prz.googlegroups.com> <00b47124$0$15654$c3e8da3@news.astraweb.com> Message-ID: On 12/18/2009 1:00 AM, Brendan Miller wrote: >> For the benefit of those of us who aren't C++ programmers, what do its >> iterators do that Python's don't? It depends on what one means by 'iterator'. Python iterators do not fit in the STL hierarchy. On the other hand, Python indexes are a form of random access iterator, the top of the hierarchy. > Python iterators basically only have one operation: > next(), which returns the next element or throws StopIteration. > > In C++ terminology this is a Input iterator. It is good for writing > "for each" loops or map reduce operations. > > An input iterator can't mutate the data it points to. For that, Python uses indexes. Random access 'iterators' are a generalization of sequence indexes. > C++ also has progressively stronger iterators: > http://www.sgi.com/tech/stl/Iterators.html > > InputIterator<- read only, one direction, single pass > ForwardIterator<- read/write, one direction, multi pass > BidirectionalIterator<- read/write, can move in either direction > RandomAccessIterator<- read/write, can move in either direction by an > arbitrary amount in constant time (as powerful as a pointer) An index can be incremented or decremented an arbitrary amount. Note that Python indexes are object pointers, not memory byte pointers, so that index + 1 points to the next object, not the next byte of memory in possibly the same object. They are, however, much safer than pointers in that x[i] can only retrieve objects of x and never, surprise, surprise, of some other collection. > Each only adds extra operations over the one before. So a > RandomAccessIterator can be used anywhere a InputIterator can, but not > vice versa. > > Also, this is a duck typing relationship, not a formal class > inheritance. Anything that quacks like a RandomAccessIterator is a > RandomAccessIterator, but there is no actual RandomAccessIterator > class. > > So, for instance stl sort function takes pair of random access > iterator delimiting a range, and can sort any datastructure that can > provide that powerful of an iterator (arrays, vectors, deques). Python, traditionally, only came with one mutable builtin sequence type, so the sort function was made a method of that type. There is also the importable array module. Apparently, there has been little demand for a generic array.sort method as there is none. One could easily write a function that took an array or other seqeunce and two indexes as args. The generic reversed() builtin function by default uses sequence indexes in the obvious manner to return a reversed version of *any* sequence, mutable or not. > http://www.sgi.com/tech/stl/sort.html > > MyCollection stuff; > // put some stuff in stuff > > sort(stuff.begin(), stuff.end()); > > Where begin() and end() by convention return iterators pointing to the > beginning and end of the sequence. start,stop = 0, len(seq) Terry Jan Reedy From tjreedy at udel.edu Fri Dec 18 16:56:41 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 18 Dec 2009 16:56:41 -0500 Subject: Setting Parameters inside of code In-Reply-To: <12ef9e020912180746o490b792dra6d71aa264be364f@mail.gmail.com> References: <12ef9e020912180746o490b792dra6d71aa264be364f@mail.gmail.com> Message-ID: On 12/18/2009 10:46 AM, Jim Valenza wrote: > Hello All - I have a very novice question for any of you out there. I > need to assign several parameters to a code in python. In Python, a 'parameter' is a function local name defined in the header of the function and bound to an argument when the function is called. I have an example > of a code that was in DOS that I would need to set as parameters in my > Python script. > SetLocal EnableDelayedExpansion > > SET OUTPUT=..\log OUTPUT = '../log/ > SET LOG=..\log > SET COMPLETED=..\Loaded > SET FAILED=..\Errors > SET REPORT=..\log\batch_projectdb.txt > SET SOURCE=..\InBox > SET BACKUP=..\Backup > SET SERVER=housdep01 > SET INSTANCE=port:5151 > SET DATASET=sde > SET /a LOADED=0 > SET /a POSTED=0 > :: If the directories don't exist, later commands run into problems. > > MD %OUTPUT% MD = make directory. Look for this in the os or os.path modules. Do read the tutorial. Terry Jan Reedy > MD %LOG% > MD %COMPLETED% > MD %FAILED% > MD %BACKUP% > I've been researching Parameters with the Python manuals and have not > found the help to be usefull as there is not much documentation for some > reason. I am new to the Python world so maybe I'm missing an important > piece of vocab. > Thanks A lot > Jim > From drobinow at gmail.com Fri Dec 18 17:24:39 2009 From: drobinow at gmail.com (David Robinow) Date: Fri, 18 Dec 2009 17:24:39 -0500 Subject: Setting Parameters inside of code In-Reply-To: <12ef9e020912180746o490b792dra6d71aa264be364f@mail.gmail.com> References: <12ef9e020912180746o490b792dra6d71aa264be364f@mail.gmail.com> Message-ID: <4eb0089f0912181424y77a299ceqf631a719e4325024@mail.gmail.com> On Fri, Dec 18, 2009 at 10:46 AM, Jim Valenza wrote: > Hello All - I have a very novice question for any of you out there.? I need > to assign several parameters to a code in python. I have an example of a > code that was in DOS that I would need to set as parameters in my Python > script. > > SetLocal EnableDelayedExpansion > SET OUTPUT=..\log > SET LOG=..\log > SET COMPLETED=..\Loaded You have an unusual use of the word "parameter". What you are doing is setting environment variables. You can read these values in Python import os outvar = os.getenv("OUTPUT") logvar = os.getenv("LOG") completevar = os.getenv("COMPLETED") # etc print outvar print logvar print completevar ------ You may also want to pass arguments (I think 'argument' is what you called 'parameter') to your script: myScript.py firstArg secondArg thirdArg hunt for sys.argv in the documentation. ---- For more sophisticated argument passing you may want to look at the 'optparse' module From gervaz at gmail.com Fri Dec 18 17:34:53 2009 From: gervaz at gmail.com (mattia) Date: 18 Dec 2009 22:34:53 GMT Subject: Sort the values of a dict Message-ID: <4b2c0386$0$1105$4fafbaef@reader4.news.tin.it> Hi all, I have a dictionary that uses dates and a tuples ad key, value pairs. I need to sort the values of the dict and insert everything in a tuple. The additional problem is that I need to sort the values looking at the i-th element of the list. I'm not that good at python (v3.1), but this is my solution: >>> d = {1:('a', 1, 12), 5:('r', 21, 10), 2:('u', 9, 8)} >>> t = [x for x in d.values()] >>> def third(mls): ... return mls[2] ... >>> s = sorted(t, key=third) >>> pres = [] >>> for x in s: ... for k in d.keys(): ... if d[k] == x: ... pres.append(k) ... break ... >>> res = [] >>> for x in pres: ... res.append((x, d[x])) ... >>> res [(2, ('u', 9, 8)), (5, ('r', 21, 10)), (1, ('a', 1, 12))] >>> Can you provide me a much pythonic solution (with comments if possible, so I can actually learn something)? Thanks, Mattia From ckaynor at zindagigames.com Fri Dec 18 17:42:10 2009 From: ckaynor at zindagigames.com (Chris Kaynor) Date: Fri, 18 Dec 2009 14:42:10 -0800 Subject: Sort the values of a dict In-Reply-To: <4b2c0386$0$1105$4fafbaef@reader4.news.tin.it> References: <4b2c0386$0$1105$4fafbaef@reader4.news.tin.it> Message-ID: I'd write it as: s = sorted(d.iteritems(), key=lambda i: i[1][2]) If using python 3, it should be d.items() instead of d.iteritems(). d.iteritems() is a generator yielding tuples of (key, value) from the dictionary 'd'. lambda i: i[1][2] is the same as: def sort_(i): return i[1][2] but in-line. Chris On Fri, Dec 18, 2009 at 2:34 PM, mattia wrote: > Hi all, I have a dictionary that uses dates and a tuples ad key, value > pairs. I need to sort the values of the dict and insert everything in a > tuple. The additional problem is that I need to sort the values looking > at the i-th element of the list. I'm not that good at python (v3.1), but > this is my solution: > > >>> d = {1:('a', 1, 12), 5:('r', 21, 10), 2:('u', 9, 8)} > >>> t = [x for x in d.values()] > >>> def third(mls): > ... return mls[2] > ... > >>> s = sorted(t, key=third) > >>> pres = [] > >>> for x in s: > ... for k in d.keys(): > ... if d[k] == x: > ... pres.append(k) > ... break > ... > >>> res = [] > >>> for x in pres: > ... res.append((x, d[x])) > ... > >>> res > [(2, ('u', 9, 8)), (5, ('r', 21, 10)), (1, ('a', 1, 12))] > >>> > > Can you provide me a much pythonic solution (with comments if possible, > so I can actually learn something)? > > Thanks, Mattia > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From gervaz at gmail.com Fri Dec 18 17:42:52 2009 From: gervaz at gmail.com (mattia) Date: 18 Dec 2009 22:42:52 GMT Subject: Sort the values of a dict References: <4b2c0386$0$1105$4fafbaef@reader4.news.tin.it> Message-ID: <4b2c056c$0$1105$4fafbaef@reader4.news.tin.it> Actually, in order to use duplicate values I need something like: >>> import copy >>> d = {1:('a', 1, 12), 5:('r', 21, 10), 2:('u', 9, 8), 3:('u', 9, 8) } >>> dc = copy.deepcopy(d) >>> t = [x for x in d.values()] >>> def third(mls): ... return mls[2] ... >>> s = sorted(t, key=third) >>> pres = [] >>> for x in s: ... for k in d.keys(): ... if d[k] == x: ... pres.append(k) ... del d[k] # speedup and use duplicate values ... break ... >>> res = [] >>> for x in pres: ... res.append((x, dc[x])) ... >>> res [(2, ('u', 9, 8)), (3, ('u', 9, 8)), (5, ('r', 21, 10)), (1, ('a', 1, 12))] >>> From bearophileHUGS at lycos.com Fri Dec 18 17:47:43 2009 From: bearophileHUGS at lycos.com (Bearophile) Date: Fri, 18 Dec 2009 14:47:43 -0800 (PST) Subject: iterators and views of lists References: <89604fb4-9dfa-45f1-a3df-f676cd4353ea@x5g2000prf.googlegroups.com> <87b87511-744c-450e-a024-976f8c57f032@15g2000prz.googlegroups.com> Message-ID: <7a50d745-34e7-4445-ba49-5d8d815ac2ba@l13g2000yqb.googlegroups.com> Brendan Miller: > I agree though, it doesn't matter to everyone and anyone. The reason I > was interested was because i was trying to solve some specific > problems in an elegant way. I was thinking it would be cool to make > python more usable in programming competitions by giving it its own > port of the STL's algorithm library, which needs something along the > lines of C++'s more powerful iterators. It seems you have missed my post, so here it is, more explicitly: http://www.boostcon.com/site-media/var/sphene/sphwiki/attachment/2009/05/08/iterators-must-go.pdf Bye, bearophie From drobinow at gmail.com Fri Dec 18 18:00:42 2009 From: drobinow at gmail.com (David Robinow) Date: Fri, 18 Dec 2009 18:00:42 -0500 Subject: Sort the values of a dict In-Reply-To: <4b2c0386$0$1105$4fafbaef@reader4.news.tin.it> References: <4b2c0386$0$1105$4fafbaef@reader4.news.tin.it> Message-ID: <4eb0089f0912181500t1408440fi671591125fcc2a22@mail.gmail.com> On Fri, Dec 18, 2009 at 5:34 PM, mattia wrote: > Hi all, I have a dictionary that uses dates and a tuples ad key, value > pairs. I need to sort the values of the dict and insert everything in a > tuple. The additional problem is that I need to sort the values looking > at the i-th element of the list. I'm not that good at python (v3.1), but > this is my solution: > >>>> d = {1:('a', 1, 12), 5:('r', 21, 10), 2:('u', 9, 8)} >>>> t = [x for x in d.values()] >>>> def third(mls): > ... ? ? return mls[2] > ... >>>> s = sorted(t, key=third) >>>> pres = [] >>>> for x in s: > ... ? ? for k in d.keys(): > ... ? ? ? ? if d[k] == x: > ... ? ? ? ? ? ? pres.append(k) > ... ? ? ? ? ? ? break > ... >>>> res = [] >>>> for x in pres: > ... ? ? res.append((x, d[x])) > ... >>>> res > [(2, ('u', 9, 8)), (5, ('r', 21, 10)), (1, ('a', 1, 12))] >>>> > > Can you provide me a much pythonic solution (with comments if possible, > so I can actually learn something)? > > Thanks, Mattia > -- > http://mail.python.org/mailman/listinfo/python-list > I won't engage in any arguments about pythonicity but it seems simpler if you convert to a list of tuples right away. d = {1:('a', 1, 12), 5:('r',21,10), 2:('u',9,8)} l = [(x, d[x]) for x in d.keys()] def third(q): return q[1][2] s = sorted(l, key=third) print s From gervaz at gmail.com Fri Dec 18 18:20:51 2009 From: gervaz at gmail.com (mattia) Date: 18 Dec 2009 23:20:51 GMT Subject: Sort the values of a dict References: <4b2c0386$0$1105$4fafbaef@reader4.news.tin.it> Message-ID: <4b2c0e53$0$823$4fafbaef@reader5.news.tin.it> Il Fri, 18 Dec 2009 18:00:42 -0500, David Robinow ha scritto: > On Fri, Dec 18, 2009 at 5:34 PM, mattia wrote: >> Hi all, I have a dictionary that uses dates and a tuples ad key, value >> pairs. I need to sort the values of the dict and insert everything in a >> tuple. The additional problem is that I need to sort the values looking >> at the i-th element of the list. I'm not that good at python (v3.1), >> but this is my solution: >> >>>>> d = {1:('a', 1, 12), 5:('r', 21, 10), 2:('u', 9, 8)} t = [x for x in >>>>> d.values()] >>>>> def third(mls): >> ... ? ? return mls[2] >> ... >>>>> s = sorted(t, key=third) >>>>> pres = [] >>>>> for x in s: >> ... ? ? for k in d.keys(): >> ... ? ? ? ? if d[k] == x: >> ... ? ? ? ? ? ? pres.append(k) >> ... ? ? ? ? ? ? break >> ... >>>>> res = [] >>>>> for x in pres: >> ... ? ? res.append((x, d[x])) >> ... >>>>> res >> [(2, ('u', 9, 8)), (5, ('r', 21, 10)), (1, ('a', 1, 12))] >>>>> >>>>> >> Can you provide me a much pythonic solution (with comments if possible, >> so I can actually learn something)? >> >> Thanks, Mattia >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > I won't engage in any arguments about pythonicity but it seems simpler > if you convert to a list of tuples right away. > > d = {1:('a', 1, 12), 5:('r',21,10), 2:('u',9,8)} l = [(x, d[x]) for x in > d.keys()] > def third(q): > return q[1][2] > > s = sorted(l, key=third) > print s Thanks, I'm not yet aware of all the wonderful conversions python can do, amazing. From mensanator at aol.com Fri Dec 18 18:26:05 2009 From: mensanator at aol.com (Mensanator) Date: Fri, 18 Dec 2009 15:26:05 -0800 (PST) Subject: Programming intro book ch1 and ch2 (Windows/Python 3) - Request For Comments References: Message-ID: > The second deviation is that since most names are constants, Really? Does that mean you don't use literals, to save the time required to convert them to integers? Isn't that done at compile time? So, instead of doing the Collatz Conjecture as while a>1: f = gmpy.scan1(a,0) if f>0: a = a >> f else: a = a*3 + 1 You would do this? zed = 0 one = 1 two = 2 twe = 3 while a>one: f = gmpy.scan1(a,zed) if f>zed: a = a >> f else: a = a*twe + one Does this really save any time? Now, it's a different story if you're using the gmpy module. You DON'T want to use literals in loops involving gmpy, because they would have to be coerced to .mpz's on every pass through the loop. In that case, you DO want to use constants as opposed to literals: ZED = gmpy.mpz(0) ONE = gmpy.mpz(1) TWO = gmpy.mpz(2) TWE = gmpy.mpz(3) while a>ONE: f = gmpy.scan1(a,0) # int used here, so it can be a literal if f>ZED: a = a >> f else: a = a*TWE + ONE And yes, the time savings can be tremendous, especially when 'a' has over 50,000 decimal digits. . I do not follow PEP > 8's recommendation to use uppercase names of constants. In fact almost no Python > code does, Mine does when I use gmpy. Otherwise, the notion that "most names are constants" is generally false. From mailtome200420032002 at gmail.com Fri Dec 18 18:55:15 2009 From: mailtome200420032002 at gmail.com (aj) Date: Fri, 18 Dec 2009 15:55:15 -0800 (PST) Subject: Acceesing python httplib2 over a network share in windows 7 Message-ID: <5dcfe4de-b460-4eca-9f1c-27a7b89fc6c9@u18g2000pro.googlegroups.com> I am trying to run python from a network share on windows 7. The network share is T: >t:\python-2.6.1\python Python 2.6.1 (r261:67517, Dec 4 2008, 16:51:00) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import httplib2 httplib2\__init__.py:29: DeprecationWarning: the md5 module is deprecated; use hashlib instead import md5 Traceback (most recent call last): File "", line 1, in File "T:\python-2.6.1\lib\python2.6\site-packages \httplib2\__init__.py", line 36, in import httplib File "T:\python-2.6.1\lib\httplib.py", line 77, in import mimetools File "T:\python-2.6.1\lib\mimetools.py", line 6, in import tempfile File "T:\python-2.6.1\lib\tempfile.py", line 34, in from random import Random as _Random File "T:\python-2.6.1\lib\random.py", line 871, in _inst = Random() File "T:\python-2.6.1\lib\random.py", line 96, in __init__ self.seed(x) File "T:\python-2.6.1\lib\random.py", line 110, in seed a = long(_hexlify(_urandom(16)), 16) WindowsError: [Error 127] The specified procedure could not be found When I copy python-2.6.1 to my local drive it works fine. It also works fine on my windows XP machine using the same network share. From rory at campbell-lange.net Fri Dec 18 19:00:54 2009 From: rory at campbell-lange.net (Rory Campbell-Lange) Date: Sat, 19 Dec 2009 00:00:54 +0000 Subject: Sort the values of a dict In-Reply-To: <4b2c0386$0$1105$4fafbaef@reader4.news.tin.it> References: <4b2c0386$0$1105$4fafbaef@reader4.news.tin.it> Message-ID: <20091219000054.GE22180@campbell-lange.net> On 18/12/09, mattia (gervaz at gmail.com) wrote: > Hi all, I have a dictionary that uses dates and a tuples ad key, value > pairs. I need to sort the values of the dict and insert everything in a > tuple. The additional problem is that I need to sort the values looking > at the i-th element of the list. I'm not that good at python (v3.1), but > this is my solution: > > >>> d = {1:('a', 1, 12), 5:('r', 21, 10), 2:('u', 9, 8)} > >>> t = [x for x in d.values()] > >>> def third(mls): > ... return mls[2] > ... > >>> s = sorted(t, key=third) > >>> pres = [] > >>> for x in s: > ... for k in d.keys(): > ... if d[k] == x: > ... pres.append(k) > ... break > ... > >>> res = [] > >>> for x in pres: > ... res.append((x, d[x])) > ... > >>> res > [(2, ('u', 9, 8)), (5, ('r', 21, 10)), (1, ('a', 1, 12))] How about >>> mylist = [z for z in zip(list(d), list(d.values()))] and then sort on your sort criteria, either i[0], i[0][1], i[0][2] or i[0][3]. Rory -- Rory Campbell-Lange Director rory at campbell-lange.net Campbell-Lange Workshop www.campbell-lange.net 0207 6311 555 3 Tottenham Street London W1T 2AF Registered in England No. 04551928 From python at mrabarnett.plus.com Fri Dec 18 19:19:15 2009 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 19 Dec 2009 00:19:15 +0000 Subject: Sort the values of a dict In-Reply-To: <20091219000054.GE22180@campbell-lange.net> References: <4b2c0386$0$1105$4fafbaef@reader4.news.tin.it> <20091219000054.GE22180@campbell-lange.net> Message-ID: <4B2C1C03.8040108@mrabarnett.plus.com> Rory Campbell-Lange wrote: > On 18/12/09, mattia (gervaz at gmail.com) wrote: >> Hi all, I have a dictionary that uses dates and a tuples ad key, value >> pairs. I need to sort the values of the dict and insert everything in a >> tuple. The additional problem is that I need to sort the values looking >> at the i-th element of the list. I'm not that good at python (v3.1), but >> this is my solution: >> >>>>> d = {1:('a', 1, 12), 5:('r', 21, 10), 2:('u', 9, 8)} >>>>> t = [x for x in d.values()] >>>>> def third(mls): >> ... return mls[2] >> ... >>>>> s = sorted(t, key=third) >>>>> pres = [] >>>>> for x in s: >> ... for k in d.keys(): >> ... if d[k] == x: >> ... pres.append(k) >> ... break >> ... >>>>> res = [] >>>>> for x in pres: >> ... res.append((x, d[x])) >> ... >>>>> res >> [(2, ('u', 9, 8)), (5, ('r', 21, 10)), (1, ('a', 1, 12))] > > How about > >>>> mylist = [z for z in zip(list(d), list(d.values()))] > The Pythonic way for the above line is: >>> mylist = list(d.items()) > and then sort on your sort criteria, either i[0], i[0][1], i[0][2] or > i[0][3]. > > Rory > > > From greg.ewing at canterbury.ac.nz Fri Dec 18 19:21:10 2009 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Sat, 19 Dec 2009 13:21:10 +1300 Subject: Raw string substitution problem In-Reply-To: References: <931375.44828.qm@web58902.mail.re1.yahoo.com> <2I-dnaKkY7MM_LfWnZ2dnUVZ_sGdnZ2d@rcn.net> <7p0q09F6qiU1@mid.individual.net> Message-ID: <7p2juvFu8tU1@mid.individual.net> MRAB wrote: > In simple cases you might be replacing with the same string every time, > but other cases you might want the replacement to contain substrings > captured by the regex. But you can give it a function that has access to the match object and can produce whatever replacement string it wants. You already have a complete programming language at your disposal. There's no need to invent yet another mini-language for the replacement string. -- Greg From alfps at start.no Fri Dec 18 19:25:48 2009 From: alfps at start.no (Alf P. Steinbach) Date: Sat, 19 Dec 2009 01:25:48 +0100 Subject: Programming intro book ch1 and ch2 (Windows/Python 3) - Request For Comments In-Reply-To: References: Message-ID: * Mensanator: >> The second deviation is that since most names are constants, > > Really? Does that mean you don't use literals, to save the time > required to convert them to integers? Isn't that done at compile > time? > > So, instead of doing the Collatz Conjecture as > > while a>1: > f = gmpy.scan1(a,0) > if f>0: > a = a >> f > else: > a = a*3 + 1 > > You would do this? > > zed = 0 > one = 1 > two = 2 > twe = 3 > while a>one: > f = gmpy.scan1(a,zed) > if f>zed: > a = a >> f > else: > a = a*twe + one That seems to have no relation to what you quoted / responded to. On the other hand, if there is some specific r?le played by the 3 above, where some other value (like e.g. 5) might be used instead, then a self descriptive name for that r?le might be good. Such reasonable naming (not what you did above) then allows easier modification of and makes it easier to understand the code. That said, and a bit off-tangent to your comment's main thrust, the time spent on coding that repeated-division-by-2 optimization would, I think, be better spent googling "Collatz Conjecture" -- avoiding writing /any/ code. ;-) > Does this really save any time? If by "it" you mean the silly naming, no it doesn't. On the contrary, it wastes time, both for writing the code and reading it. Generally, IMO, think about the clarity of your code. If naming something increases clarity, then name the thing. If it doesn't increase clarity, don't. > Now, it's a different story if you're using the gmpy module. > You DON'T want to use literals in loops involving gmpy, because > they would have to be coerced to .mpz's on every pass through the > loop. > > In that case, you DO want to use constants as opposed to literals: > > ZED = gmpy.mpz(0) > ONE = gmpy.mpz(1) > TWO = gmpy.mpz(2) > TWE = gmpy.mpz(3) > while a>ONE: > f = gmpy.scan1(a,0) # int used here, so it can be a literal > if f>ZED: > a = a >> f > else: > a = a*TWE + ONE > > And yes, the time savings can be tremendous, especially when 'a' > has over 50,000 decimal digits. Yeah, good point. Few languages have compile time evaluation of logically constant expressions. C++0x will have that feature (called 'constexpr' IIRC) but in Python, current C++ etc. it's just a good idea to precompute values, and name them, rather than computing them again and again where they're needed. > . I do not follow PEP >> 8's recommendation to use uppercase names of constants. In fact almost no Python >> code does, > > Mine does when I use gmpy. Otherwise, the notion that "most names > are constants" is generally false. No, it depends on what you mean by "constant". The problem with Python, as Google noted, is that the language is so excessively dynamic: even names of routines are variables, and there /are/ no named user defined constants except logically, in the programmer's mind. And logically (that is, at the "in the programmer's mind" level), if you define "constant" as a name whose value will not change after initialization, then routine names are constants. However, if you define "constant" as only a global scope (that is, module scope) name that denotes a boolean, numerical or string or Null value and that doesn't change after initialization, then your statement about the scarcity of constants appears to be true, but using a practically useless definition. I think for such constants exported by modules it's a good idea to at least provide uppercase names so as conform to very firmly established convention. There might even be tools that rely on that convention. But for application code the uppercase names are just distracting, and they don't help you... Cheers & hth., - Alf From greg.ewing at canterbury.ac.nz Fri Dec 18 19:26:53 2009 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Sat, 19 Dec 2009 13:26:53 +1300 Subject: Eclipse Carriage Return Workaround In-Reply-To: References: Message-ID: <7p2k9qFvr6U1@mid.individual.net> Steve Holden wrote: > > Can anyone think of a simple way work around this issue by overriding > __builtins__.input() with a function that calls input() and then returns > an rstrip()ped version of the input string? I though of setting a > PYTHONSTARTUP environment variable, but that only affects interactive > interpreter instances. Maybe you could put something in site.py? -- Greg From steve at REMOVE-THIS-cybersource.com.au Fri Dec 18 20:12:18 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 19 Dec 2009 01:12:18 GMT Subject: iterators and views of lists References: <89604fb4-9dfa-45f1-a3df-f676cd4353ea@x5g2000prf.googlegroups.com> <87b87511-744c-450e-a024-976f8c57f032@15g2000prz.googlegroups.com> <00b47124$0$15654$c3e8da3@news.astraweb.com> Message-ID: <00b5ad20$0$15654$c3e8da3@news.astraweb.com> On Fri, 18 Dec 2009 10:39:15 -0800, Carl Banks wrote: > It is true that Python iterators can't be used to mutate the underlying > structure--if there is actual underlying data structure-- An iterator is a protocol. So long as you have __iter__ and next (or __next__ in Python 3) methods, your class is an iterator. What you do in those methods are up to you. If you want to mutate the underlying data, you're free to do so. Just for chuckles, here's a quick-and-dirty iterator version of the Tower of Hanoi that mutates itself as needed. (I make no promise that it is either efficient or bug-free.) class Hanoi: def __init__(self, n=5): self.a = range(n, 0, -1) self.b = [] self.c = [] self.num = 0 def __str__(self): template = "Needle %d: %s" d = [template % (i, data) for (i,data) in enumerate([self.a, self.b, self.c])] return '\n'.join(d) + '\n' def __iter__(self): return self def next(self): if [] == self.a == self.c: raise StopIteration self.num += 1 if self.num % 2: # Odd-numbered move: move the smallest disk one # position clockwise. needle = self.find_smallest() nxt = "bca"["abc".find(needle)] else: # Even-numbered move: make the only legal move of the # next-smallest disk. needle, nxt = self.find_legal() self.move(needle, nxt) return str(self) def move(self, frm, to): """Move the top disk from needle `frm` to needle `to`.""" from_needle = getattr(self, frm) to_needle = getattr(self, to) to_needle.append(from_needle[-1]) del from_needle[-1] def find_smallest(self): for needle in 'abc': if 1 in getattr(self, needle): return needle def find_legal(self): """Find the only legal move not using the smallest disk.""" ignore = self.find_smallest() if ignore == 'a': disks = 'bc' elif ignore == 'b': disks = 'ac' else: disks = 'ab' left_needle = getattr(self, disks[0]) right_needle = getattr(self, disks[1]) if left_needle == []: return disks[1], disks[0] elif right_needle == []: return disks[0], disks[1] elif left_needle[-1] < right_needle[-1]: return disks[0], disks[1] else: return disks[1], disks[0] And in use: >>> p = Hanoi() >>> for state in p: ... print state ... Needle 0: [5, 4, 3, 2] Needle 1: [1] Needle 2: [] Needle 0: [5, 4, 3] Needle 1: [1] Needle 2: [2] [ rest of output skipped for brevity ] Python iterators don't generally mutate the thing they are iterating over, not because they can't, but because it's generally a bad idea to do so. In general, it really only makes sense as an optimization in situations where you have so much data that you can't afford to make a copy of it. For the occasional time where it does make sense, Python iterators are perfectly capable of doing so. -- Steven From ryan at rfk.id.au Fri Dec 18 20:21:57 2009 From: ryan at rfk.id.au (Ryan Kelly) Date: Sat, 19 Dec 2009 12:21:57 +1100 Subject: ANN: withrestart 0.2.1 In-Reply-To: References: <1261114527.2759.4.camel@durian> Message-ID: <1261185717.2701.27.camel@durian> On Fri, 2009-12-18 at 07:12 -0500, Neal Becker wrote: > I haven't tried it, but it sounds really cool. I suppose I should expect a > lot more overhead compared to try/except, since it's not built-in to python? It's a pretty thin layer on top of try/except so I'll be surprised if there is *too* much overhead. The only overhead is at establishment and/or invocation time - calling some extra functions, walking a few stack frames, etc. I've attached a highly scientific benchmark I threw together this morning. Results: Establishing a restart/tryexcept but not using it: test_tryexcept0: 1.23 usec test_restarts0: 34.90 usec Establishing a restart/tryexcept, returning a new value: test_tryexcept1: 3.56 usec test_restarts1: 67.30 usec Establishing a restart/tryexcept, raising a new error: test_tryexcept2: 5.86 usec test_restarts2: 90.20 usec Not having to pass status flags or callback functions through every layer of your API to properly recover from errors: tryexcept: impossible :-( withrestart: priceless :-) Cheers, Ryan -- Ryan Kelly http://www.rfk.id.au | This message is digitally signed. Please visit ryan at rfk.id.au | http://www.rfk.id.au/ramblings/gpg/ for details -------------- next part -------------- A non-text attachment was scrubbed... Name: timetest.py Type: text/x-python Size: 1833 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 197 bytes Desc: This is a digitally signed message part URL: From tekion at gmail.com Fri Dec 18 20:27:10 2009 From: tekion at gmail.com (tekion) Date: Fri, 18 Dec 2009 17:27:10 -0800 (PST) Subject: tarfiles usage on python 2.4.4 Message-ID: <205e4ce0-adda-4153-aa4f-d18eecefca40@z40g2000vba.googlegroups.com> All, I am using tarfile module and my python is version 2.4.4. When I call method extractall, I am getting error method does not exist. Could someone confirm if the method exist on python 2.4.4? Thanks From ryan at rfk.id.au Fri Dec 18 20:28:32 2009 From: ryan at rfk.id.au (Ryan Kelly) Date: Sat, 19 Dec 2009 12:28:32 +1100 Subject: shouldn't list comprehension be faster than for loops? In-Reply-To: <8808c896-0bb9-42e0-aa61-319adadf31d1@b2g2000yqi.googlegroups.com> References: <979c8ffe-dc39-4b2b-ab9b-12ecefc12d7a@y24g2000yqb.googlegroups.com> <8808c896-0bb9-42e0-aa61-319adadf31d1@b2g2000yqi.googlegroups.com> Message-ID: <1261186112.2701.31.camel@durian> > > Tenting the time spent by each approach (using time.clock()), with a > > file with about 100,000 entries, I get 0.03s for the loop and 0.05s > > for the listcomp. > > Anything else being equal, list comprehensions will be the faster > becuase they incur fewer name and attribute lookups. It will be the > same as the difference between a for loop and a call to map. A list > comprehension is basically an enhancement of map. Not so. If you use the "dis" module to peek at the bytecode generated for a list comprehension, you'll see it's very similar to that generated for an explicit for-loop. The byte-code for a call to map is very different. Basically: both a for-loop and a list-comp do the looping in python bytecode, while a call to map will do the actual looping in C. >>> def comper(): ... return [i*2 for i in xrange(10)] ... >>> >>> dis.dis(comper) 2 0 BUILD_LIST 0 3 DUP_TOP 4 STORE_FAST 0 (_[1]) 7 LOAD_GLOBAL 0 (xrange) 10 LOAD_CONST 1 (10) 13 CALL_FUNCTION 1 16 GET_ITER >> 17 FOR_ITER 17 (to 37) 20 STORE_FAST 1 (i) 23 LOAD_FAST 0 (_[1]) 26 LOAD_FAST 1 (i) 29 LOAD_CONST 2 (2) 32 BINARY_MULTIPLY 33 LIST_APPEND 34 JUMP_ABSOLUTE 17 >> 37 DELETE_FAST 0 (_[1]) 40 RETURN_VALUE >>> >>> >>> >>> def maper(): ... return map(lambda i: i*2,xrange(10)) ... >>> dis.dis(maper) 2 0 LOAD_GLOBAL 0 (map) 3 LOAD_CONST 1 (>> Cheers, Ryan -- Ryan Kelly http://www.rfk.id.au | This message is digitally signed. Please visit ryan at rfk.id.au | http://www.rfk.id.au/ramblings/gpg/ for details -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 197 bytes Desc: This is a digitally signed message part URL: From steve at REMOVE-THIS-cybersource.com.au Fri Dec 18 20:56:23 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 19 Dec 2009 01:56:23 GMT Subject: Programming intro book ch1 and ch2 (Windows/Python 3) - Request For Comments References: Message-ID: <00b5b774$0$15654$c3e8da3@news.astraweb.com> On Fri, 18 Dec 2009 19:00:48 +0100, Alf P. Steinbach wrote: > In fact almost no Python > code does, but then it seems that people are not aware of how many of > their names are constants and think that they're uppercasing constants > when in fact they're not. E.g. routine arguments Routine arguments are almost never constants, since by definition they will vary according to the value passed by the caller. (The exception is that some formal parameters in Python are given default values and flagged as "do not use", e.g. some methods in the random module. One might argue that they are constants in the sense that the caller is warned not to use them at all.) > and in particular > routine NAMES are usually constants, absolutely not meant to be > modified, but it would be silly to UC... [emphasis added by me] The only thing sillier than uppercasing routine names is to confuse the name of a thing for the thing it represents. The names of *all* entities, whether of constants, variables or routines, are "not meant to be modified". As a general rule, programs will no more work if you rename a variable 'x' to 'y' than if you rename a function 'f' to 'g' -- that's why refactoring requires that any renamings be done carefully. There's no need to single out routines for special treatment in that regard. As far as I know, no programming language provides a standard facility for renaming entities, be they data or routines: the closest we have is something like Python where you can do this: # make an entity x x = 23 # use it x += 1 # make a new name that refers to the same entity as x y = x # delete the old name del x # now use the new name y += 1 So while it is true that routine names are not meant to be modified, neither are variable names (that is, the names of variables) or the names of anything else either. But this is not what is meant by "constant": being a constant means that the *value*, not the *name*, is never meant to change. It is true that, usually, the names of certain types of object (usually functions, classes, methods and modules) are typically expected to not be re-bound. Having done this: def parrot(colour='blue'): return "Norwegian %s" % colour.titlecase() I would *rarely* rebind the name parrot to another object. Rarely, but not quite never: I might monkey-patch the function, or decorate it in some way, or change the implementation, so such routines aren't quite constant in the sense you mean. While it's unusual to vary a function, it isn't forbidden. Even in languages where routines are "first class objects" like ints and strings, we treat such objects as special. Even if the function named parrot above was expected to never change, I wouldn't describe it as a constant. "Constant" and "variable" refer to *data*, not routines or other special objects like modules. It's illustrative to consider what we might do when writing a program that does treat functions as data, say, a program that integrated other functions. One might very well do something like this: function_to_be_integrated = math.sin # a variable SIMPSONS = integrators.simpsons_method # a constant UPPER_RECT = monkey_patch(integrators.upper) LOWER_RECT = monkey_patch(integrators.lower) integrate(function_to_be_integrated, limits=(-math.pi/2, math.pi), method=SIMPSONS ) This would clearly indicate that `function_to_be_integrated` holds variable data (which happens to be a function) while `SIMPSONS` etc are expected to hold constant data (which also happen to be functions). -- Steven From python at mrabarnett.plus.com Fri Dec 18 21:21:53 2009 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 19 Dec 2009 02:21:53 +0000 Subject: tarfiles usage on python 2.4.4 In-Reply-To: <205e4ce0-adda-4153-aa4f-d18eecefca40@z40g2000vba.googlegroups.com> References: <205e4ce0-adda-4153-aa4f-d18eecefca40@z40g2000vba.googlegroups.com> Message-ID: <4B2C38C1.2070608@mrabarnett.plus.com> tekion wrote: > All, > I am using tarfile module and my python is version 2.4.4. When I call > method extractall, I am getting error method does not exist. Could > someone confirm if the method exist on python 2.4.4? Thanks It's new in Python 2.5. From python at mrabarnett.plus.com Fri Dec 18 21:24:00 2009 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 19 Dec 2009 02:24:00 +0000 Subject: Raw string substitution problem In-Reply-To: <7p2juvFu8tU1@mid.individual.net> References: <931375.44828.qm@web58902.mail.re1.yahoo.com> <2I-dnaKkY7MM_LfWnZ2dnUVZ_sGdnZ2d@rcn.net> <7p0q09F6qiU1@mid.individual.net> <7p2juvFu8tU1@mid.individual.net> Message-ID: <4B2C3940.6010605@mrabarnett.plus.com> Gregory Ewing wrote: > MRAB wrote: > >> In simple cases you might be replacing with the same string every >> time, but other cases you might want the replacement to contain >> substrings captured by the regex. > > But you can give it a function that has access to the match object > and can produce whatever replacement string it wants. > > You already have a complete programming language at your disposal. > There's no need to invent yet another mini-language for the > replacement string. > There's no need for list comprehensions either, but they're much-used shorthand. From steve at REMOVE-THIS-cybersource.com.au Fri Dec 18 22:03:50 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 19 Dec 2009 03:03:50 GMT Subject: Programming intro book ch1 and ch2 (Windows/Python 3) - Request For Comments References: Message-ID: <00b5c744$0$15654$c3e8da3@news.astraweb.com> On Sat, 19 Dec 2009 01:25:48 +0100, Alf P. Steinbach wrote: > That said, and a bit off-tangent to your comment's main thrust, the time > spent on coding that repeated-division-by-2 optimization would, I think, > be better spent googling "Collatz Conjecture" -- avoiding writing > /any/ code. ;-) That's a strange thing to say. >> Now, it's a different story if you're using the gmpy module. You DON'T >> want to use literals in loops involving gmpy, because they would have >> to be coerced to .mpz's on every pass through the loop. [...] > Yeah, good point. Few languages have compile time evaluation of > logically constant expressions. Surely that's an implementation issue rather than a language issue. > C++0x will have that feature (called > 'constexpr' IIRC) but in Python, current C++ etc. it's just a good idea > to precompute values, and name them, rather than computing them again > and again where they're needed. CPython 2.5 and on has a keyhole optimizer that replaces many constant expressions with pre-computed values. # Python 2.4 >>> dis.dis(compile('1+1', '', 'eval')) 0 0 LOAD_CONST 0 (1) 3 LOAD_CONST 0 (1) 6 BINARY_ADD 7 RETURN_VALUE # Python 2.5 >>> dis.dis(compile('1+1', '', 'eval')) 1 0 LOAD_CONST 1 (2) 3 RETURN_VALUE Unfortunately it doesn't help Mensanator's case, because there's no way to tell the compiler to generate mpz objects instead of int objects, and expressions such as gmpy.mpz(0) are not recognised as compile-time constants. >> Mine does when I use gmpy. Otherwise, the notion that "most names are >> constants" is generally false. > > No, it depends on what you mean by "constant". All names are constant. Always. The Python language does not support renaming names -- as far as I know, no language does. > The problem with Python, > as Google noted, is that the language is so excessively dynamic: even > names of routines are variables, Don't say that, that is confusing the name with the value. The terms "constant" and "variable" refer to the values bound to a name, not the name itself: what you mean is that even routines are variables. Consider the following Pascal declaration: const a = 1; var b: integer; Neither name 'a' nor 'b' ever change; a is always a and b is always b. You wouldn't describe b as a constant because the name never changes, would you? What matters is that the value assigned to the name can, or can't, be changed by the caller. Like any other language, Python *names* are always constant: you can create them at will (without needing a declaration); you can delete them (with the del statement, something Pascal doesn't allow you to do); but there's no way to change a name once it exists. Obviously it would be misleading to claim that Python name/object bindings ("variables") are therefore constant because of this. So how would I say what you are trying to say, but in a less-misleading fashion? Names can always (well, almost -- there are a few exceptions) be rebound, regardless of whether they are currently bound to a data object (string, int, float...) or a routine (function, method...). Since the name by which we refer to a function can be rebound, we refer to the name/object binding as variable rather than constant -- exactly the same as any other name/object binding. Or the shorter way: Since all names can be rebound, regardless of what value they have (int, string, function, whatever) all names are variables and Python has no constants other than special pre-defined names like None. > and there /are/ no named user defined > constants except logically, in the programmer's mind. Yes, that is correct, although there are tricks you can do to make slightly-more-constant-like constants, such as Alex Martelli's "constant module" recipe in the Cookbook, but there are no true constants in Python. > And logically > (that is, at the "in the programmer's mind" level), if you define > "constant" as a name whose value will not change after initialization, > then routine names are constants. Some languages enforce that, and in those languages, it makes sense to describe functions as constants. Python is not one of those languages. > However, if you define "constant" as only a global scope (that is, > module scope) name that denotes a boolean, numerical or string or Null > value and that doesn't change after initialization, then your statement > about the scarcity of constants appears to be true, but using a > practically useless definition. I won't speak for Mensanator, but I wouldn't be so restrictive about the *types* of data that constants can hold. Not in Python, at least, other languages can and do limit the types of constants to a handful of predefined types known to the compiler. Nor would I say that "constants" (note the scare-quotes) can only occur in module scope. There's nothing wrong with naming "constants" in other scopes, although I must admit I'm a tad less consistent about doing so than I should. -- Steven From alfps at start.no Fri Dec 18 22:04:51 2009 From: alfps at start.no (Alf P. Steinbach) Date: Sat, 19 Dec 2009 04:04:51 +0100 Subject: Programming intro book ch1 and ch2 (Windows/Python 3) - Request For Comments In-Reply-To: <00b5b774$0$15654$c3e8da3@news.astraweb.com> References: <00b5b774$0$15654$c3e8da3@news.astraweb.com> Message-ID: * Steven D'Aprano: > On Fri, 18 Dec 2009 19:00:48 +0100, Alf P. Steinbach wrote: > >> In fact almost no Python >> code does, but then it seems that people are not aware of how many of >> their names are constants and think that they're uppercasing constants >> when in fact they're not. E.g. routine arguments > > Routine arguments are almost never constants, since by definition they > will vary according to the value passed by the caller. I'm sorry, but that requires a definition of "constant" that explicitly excludes routine arguments, which is like saying horses are not mammals, just "because". There are two sensible definitions of "constant": compile time constant, and constant-after-initialization. And since Python doesn't have or support user defined compile time (named) constants even in the way that a programmer views the execution of a program, only the const after initialization meaning can /reasonably/ apply. I hope you see that with the constant-after-initialization meaning it's rather irrelevant that an argument's value "will vary according to [the actual argument]" -- for an argument A, id(A) does in general not vary after initialization, after creation of A; and it can certainly not vary before! Consider some C++ code: void foo( SomeType const v ) { // Here the name v is constant: that name's value can't change. // (Except that in C++ you can do anything by using low-level stuff.) } As the comment there exemplifies, in addition to the 2 main meanings of constness one can differentiate between constness at different levels of an expression, e.g., in Python, with respect to what the language enforces, s = "blah" is a non-constant name referring to a constant (immutable value), while a = ["blah"] is a non-constant name referring to a non-constant value (a Python 'list') containing a constant value -- but with respect to intended constness there might be more constness here, although there can't be less. Since Python doesn't support constness enforcement, your statement that routine arguments are almost never constants must refer to their actual usage, i.e. intention. It may be the case that in most code you're familiar with routine arguments are generally modified. And/or it may be that in code you're familiar with routines regularly modify the objecs that their arguments refer to, i.e. that the arguments are constant names referring to mutable objects. In code that I'm familiar with, but that's admittedly mostly in other languages, most argument names are constant at the top level of constness, i.e., translated to Python, id(A) does generally not change when A is a formal argument. > (The exception is that some formal parameters in Python are given default > values and flagged as "do not use", e.g. some methods in the random > module. One might argue that they are constants in the sense that the > caller is warned not to use them at all.) Huh. >> and in particular >> routine NAMES are usually constants, absolutely not meant to be >> modified, but it would be silly to UC... > [emphasis added by me] > > > The only thing sillier than uppercasing routine names is to confuse the > name of a thing for the thing it represents. The names of *all* entities, > whether of constants, variables or routines, are "not meant to be > modified". As a general rule, programs will no more work if you rename a > variable 'x' to 'y' than if you rename a function 'f' to 'g' -- that's > why refactoring requires that any renamings be done carefully. There's no > need to single out routines for special treatment in that regard. To be pedantic, original routine names are usually absolutely not meant to be assigned to. If you have def foo(): whatever() you simply shouldn't, in general, do foo = bar I think you understood that, i.e., that the above comment of yours is just rhetoric? > As far as I know, no programming language provides a standard facility > for renaming entities, be they data or routines: Eiffel (IIRC) and C++ come pretty close. E.g., in C++: int a; int& b = a; // A new name for a. b = 123; // Assigns to a. > the closest we have is > something like Python where you can do this: > > # make an entity x > x = 23 > # use it > x += 1 > # make a new name that refers to the same entity as x > y = x > # delete the old name > del x > # now use the new name > y += 1 Well, you're off on the wrong track as far as convincing me about something is concerned. First, your belief about renaming not being supported by any languages is largely incorrect, as shown above. Secondly, I was not talking about renaming things -- that creative interpretation is pretty meaningless... [snipped the rest, irrelevant] Cheers & hth., - Alf From kursat.kutlu at gmail.com Fri Dec 18 22:06:18 2009 From: kursat.kutlu at gmail.com (ShoqulKutlu) Date: Fri, 18 Dec 2009 19:06:18 -0800 (PST) Subject: Cookie name and expiration References: Message-ID: I'd already found my problem, that I had to set the "path" propert of a cookie object something like below: myCookie.path = '/' This is not the cookie content and not documented in the mod_python cookie module documentation. I hope this will help anyone else.. Regards, Kutlu On Nov 26, 1:32?am, ShoqulKutlu wrote: > Hi, > > I'm testing the Cookie module's MarshalCookie in mod_python on my > localhost environment. Everything looks ok and cookie set, get and > update operations work well. But I'm not sure about the cookie name > could be set by Cookie module. I mean the name of cookie file saved in > the Temporary Internet Files directory of Internet Explorer. Consider > that I run the script ashttp://localhost:8080/myScripts/myScript > When I look at the Temporary Internet Files dir, not like other > cookies came from normal websites, the cookie file was saved as > "myScript/" and the cookie address is shown ashttp://localhost:8080/myScripts/ > I don't know this is normal behaviour of the browser or there is an > option to set the name of cookie file. > > I mentioned the expiration in the subject but maybe it's not related > to expiration. For example if I run directlyhttp://localhost:8080/myScripts/myScript2 > after a day and look for the temporary internet directory again, I see > a second cookie named "myScript2/" and the first cookie (myScript/) > still exists there. But the first cookie seems no longer valid for > this domain although I set the expire range for 30 days. > > Do I miss something about cookies concept and behaviour of browsers? > Could anyone please clarify? > > Thanks and regards,Kutlu From vmail at mycircuit.org Fri Dec 18 22:18:26 2009 From: vmail at mycircuit.org (Peter) Date: Sat, 19 Dec 2009 04:18:26 +0100 Subject: AttributeError: logging module bug ? In-Reply-To: References: <4dc0cfea0912151005g7cf389ddx2e3d9d5a62338344@mail.gmail.com> <4B27D721.2010707@mrabarnett.plus.com> <4dc0cfea0912151112n235fa28vd509a36ddfc4ade9@mail.gmail.com> Message-ID: <4B2C4602.2070401@mycircuit.org> > ./of/logger.py > > from logging import Formatter > > class RootFormatter(Formatter): > pass > class ModuleFormatter(Formatter): > pass > class ClassFormatter(Formatter): > pass > class DataFormatter(Formatter): > pass > > (and an empty ./of/__init__.py) your initial script runs without error. If > you want external help please > > (1) make sure that you provide all necessary files needed to reproduce the > error > > (2) remove as much of the code as possible that does not contribute to the > problem. (This is also an effective debugging technique) > > Peter > (1), (2): That is sometimes easier said than done, especially if you still lack experience in a given language. You are right, though, my request lacked precision, sorry for the noise ! Your answer helped me to find the problem: given the minimal files above, in my logging.cfg file , I specified: [formatter_root] format=%(levelname)s %(name)s %(message)s datefmt=%S # does not work: class = of.logger.RootFormatter based on my misunderstanding, that the path to the RootFormatter could be specfied as a normal python class defined in a package.module . It seems that I have to say instead: .... # works: class = logger.RootFormatter This was somehow unexpected for me, since in a module using logger.py, I could use either import: from mylogger import logger # without package name or from of.mylogger import logger # with package name but this does not seem to work for the class specification in the config file (only the former works). Again, thanks a lot ! Peter From davea at ieee.org Fri Dec 18 22:18:34 2009 From: davea at ieee.org (Dave Angel) Date: Fri, 18 Dec 2009 22:18:34 -0500 Subject: Webpy and UnicodeDecodeError In-Reply-To: <630903f9-bd71-4e4a-a8ac-acbf3c8976c0@21g2000yqj.googlegroups.com> References: <5f704b6c-bc94-40cd-ae71-3d6b363e8c9e@p8g2000yqb.googlegroups.com> <630903f9-bd71-4e4a-a8ac-acbf3c8976c0@21g2000yqj.googlegroups.com> Message-ID: <4B2C460A.1080606@ieee.org> Oscar Del Ben wrote: > >> You'll notice that one of the strings is a unicode one, and another one >> has the character 0x82 in it. Once join() discovers Unicode, it needs >> to produce a Unicode string, and by default, it uses the ASCII codec to >> get it. >> >> If you print your 'l' list (bad name, by the way, looks too much like a >> '1'), you can see which element is Unicode, and which one has the \xb7 >> in position 42. You'll have to decide which is the problem, and solve >> it accordingly. Was the fact that one of the strings is unicode an >> oversight? Or did you think that all characters would be 0x7f or less? >> Or do you want to handle all possible characters, and if so, with what >> encoding? >> >> DaveA >> > > Thanks for your reply DaveA. > > Since I'm dealing with file uploads, I guess I should only care about > those. I understand the fact that I'm trying to concatenate a unicode > string with a binary, but I don't know how to deal with this. Perhaps > the uploaded file should be encoded in some way? I don't think this is > the case though. > > You have to decide what the format of the file is to be. If you have some in bytes, and some in Unicode, you have to be explicit about how you merge them. And that depends who's going to use the file, and for what purpose. Before you try to do a join(), you have to do a conversion of the Unicode string(s) to bytes. Try str.encode(), where you get to specify what encoding to use. In general, you want to use the same encoding for all the bytes in a given file. But as I just said, that's entirely up to you. DaveA From alfps at start.no Fri Dec 18 22:29:22 2009 From: alfps at start.no (Alf P. Steinbach) Date: Sat, 19 Dec 2009 04:29:22 +0100 Subject: Programming intro book ch1 and ch2 (Windows/Python 3) - Request For Comments In-Reply-To: <00b5c744$0$15654$c3e8da3@news.astraweb.com> References: <00b5c744$0$15654$c3e8da3@news.astraweb.com> Message-ID: * Steven D'Aprano: > On Sat, 19 Dec 2009 01:25:48 +0100, Alf P. Steinbach wrote: > >> That said, and a bit off-tangent to your comment's main thrust, the time >> spent on coding that repeated-division-by-2 optimization would, I think, >> be better spent googling "Collatz Conjecture" -- avoiding writing >> /any/ code. ;-) > > That's a strange thing to say. No. The code shown was like attacking Fermat's last theorem with a little Python script checking out number triplets. It's already been done (not to mention that that theorem's been proven, although that's, AFAIK, not the case for Collatz'). >>> Now, it's a different story if you're using the gmpy module. You DON'T >>> want to use literals in loops involving gmpy, because they would have >>> to be coerced to .mpz's on every pass through the loop. > [...] >> Yeah, good point. Few languages have compile time evaluation of >> logically constant expressions. > > Surely that's an implementation issue rather than a language issue. No, it isn't. An optimizer can only do so much, as you yourself note below! With language support it's a very different matter because guarantees propagate so that sophisticated analysis is no longer necessary: the compiler /knows/, because it's explicitly being told. >> C++0x will have that feature (called >> 'constexpr' IIRC) but in Python, current C++ etc. it's just a good idea >> to precompute values, and name them, rather than computing them again >> and again where they're needed. > > CPython 2.5 and on has a keyhole optimizer that replaces many constant > expressions with pre-computed values. > > # Python 2.4 >>>> dis.dis(compile('1+1', '', 'eval')) > 0 0 LOAD_CONST 0 (1) > 3 LOAD_CONST 0 (1) > 6 BINARY_ADD > 7 RETURN_VALUE > > # Python 2.5 >>>> dis.dis(compile('1+1', '', 'eval')) > 1 0 LOAD_CONST 1 (2) > 3 RETURN_VALUE > > > Unfortunately it doesn't help Mensanator's case, because there's no way > to tell the compiler to generate mpz objects instead of int objects, and > expressions such as gmpy.mpz(0) are not recognised as compile-time > constants. See? ;-) >>> Mine does when I use gmpy. Otherwise, the notion that "most names are >>> constants" is generally false. >> No, it depends on what you mean by "constant". > > All names are constant. Always. The Python language does not support > renaming names -- as far as I know, no language does. No-ones been talking about renaming names. I think that's purely rhetorical on your part but it may be that you really believe so. In the latter case, just try to interpret statements so that they're meaningful instead of meaningless. :-) >> The problem with Python, >> as Google noted, is that the language is so excessively dynamic: even >> names of routines are variables, > > Don't say that, that is confusing the name with the value. Nope. > The terms > "constant" and "variable" refer to the values bound to a name, not the > name itself: I'm sorry, that's incorrect. Quote from ?4.1 "Naming and binding" of the Python 3.1.1 language spec: "If a name is bound in a block, it is a local variable of that block, unless declared as nonlocal. If a name is bound at the module level, it is a global variable. (The variables of the module code block are local and global.) If a variable is used in a code block but not defined there, it is a free variable." > what you mean is that even routines are variables. I'm sorry but I can't make sense of what you write here. In addition I'm not sure what you mean because there are two main interpretations. If you mean that user defined Python routines are mutable, yes that's right, but not what I was talking about (which you can easily see by checking whether it makes sense in context; it doesn't). If you mean that a routine of itself is a variable, no it isn't, but the name of a routine, like "foo" in def foo: print( "uh" ) or "bar" in bar = lambda: print( "oh" ) is a variable, per the language specification's definition quoted above (and also by any reasonable meaning of "variable"!). The meaning of "variable" for Python terminology is specified by the language specification, as quoted above: a variable is a name. [snipped rest, irrelevant] Cheers & hth., - Alf From john at castleamber.com Fri Dec 18 22:29:27 2009 From: john at castleamber.com (John Bokma) Date: Fri, 18 Dec 2009 21:29:27 -0600 Subject: Programming intro book ch1 and ch2 (Windows/Python 3) - Request For Comments References: <00b5c744$0$15654$c3e8da3@news.astraweb.com> Message-ID: <87ljgzwsiw.fsf@castleamber.com> Steven D'Aprano writes: > CPython 2.5 and on has a keyhole optimizer that replaces many constant ^^^^^^^ Shouldn't that be peephole? > expressions with pre-computed values. And that's called constant folding. Unless I misread your post (or have been out of touch with compiler building too long) -- John Bokma Read my blog: http://johnbokma.com/ Hire me (Perl/Python): http://castleamber.com/ From steve at REMOVE-THIS-cybersource.com.au Fri Dec 18 22:29:32 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 19 Dec 2009 03:29:32 GMT Subject: Raw string substitution problem References: <931375.44828.qm@web58902.mail.re1.yahoo.com> <2I-dnaKkY7MM_LfWnZ2dnUVZ_sGdnZ2d@rcn.net> <7p0q09F6qiU1@mid.individual.net> <7p2juvFu8tU1@mid.individual.net> Message-ID: <00b5cd4b$0$15654$c3e8da3@news.astraweb.com> On Sat, 19 Dec 2009 02:24:00 +0000, MRAB wrote: > Gregory Ewing wrote: >> MRAB wrote: >> >>> In simple cases you might be replacing with the same string every >>> time, but other cases you might want the replacement to contain >>> substrings captured by the regex. >> >> But you can give it a function that has access to the match object and >> can produce whatever replacement string it wants. >> >> You already have a complete programming language at your disposal. >> There's no need to invent yet another mini-language for the replacement >> string. >> > There's no need for list comprehensions either, but they're much-used > shorthand. The same can't be said for regex replacement strings, which are far more specialised. And list comps don't make anything *harder*, they just make things easier. In contrast, the current behaviour of regex replacements makes it difficult to use special characters as part of the replacement string. That's not good. -- Steven From steve at REMOVE-THIS-cybersource.com.au Fri Dec 18 22:36:51 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 19 Dec 2009 03:36:51 GMT Subject: Programming intro book ch1 and ch2 (Windows/Python 3) - Request For Comments References: Message-ID: <00b5cf01$0$15654$c3e8da3@news.astraweb.com> On Fri, 18 Dec 2009 15:26:05 -0800, Mensanator wrote: >> The second deviation is that since most names are constants, > > Really? Does that mean you don't use literals, to save the time required > to convert them to integers? Isn't that done at compile time? > > So, instead of doing the Collatz Conjecture as > > while a>1: > f = gmpy.scan1(a,0) > if f>0: > a = a >> f > else: > a = a*3 + 1 > > You would do this? > > zed = 0 > one = 1 > two = 2 > twe = 3 > while a>one: > f = gmpy.scan1(a,zed) > if f>zed: > a = a >> f > else: > a = a*twe + one > > Does this really save any time? There are some people who might argue that using *any* magic constants in code is wrong, and that *all* such values should be declared as a constant. It's easy to take the mickey out of such an extreme position: zed = 0 # in case we need to redefine 0 as something else one = 1 # likewise two = 3 # changed from 2 to 3 to reflect the end of the Mayan calendar # The following is guaranteed to pass unless the world is ending. assert one+one == two-zed -- Steven From davea at ieee.org Fri Dec 18 23:05:33 2009 From: davea at ieee.org (Dave Angel) Date: Fri, 18 Dec 2009 23:05:33 -0500 Subject: Creating Classes In-Reply-To: <26848375.post@talk.nabble.com> References: <26848375.post@talk.nabble.com> Message-ID: <4B2C510D.80102@ieee.org> seafoid wrote: > Hey Guys, > > I have started to read over classes as a brief respite from my parsing > problem. > > When a class is defined, how does the class access the data upon which the > class should act? > > Example: > > class Seq: > > def __init__(self, data, alphabet = Alphabet.generic_alphabet): > self.data = data > self.alphabet = alphabet > > def tostring(self): > return self.data > > def tomutable(self): > return MutableSeq(self.data, self.alphabet) > > def count(self, item): > return len([x for x in self.data if x == item]) > > I know what it should do, but have no idea how to feed it the data. > > Methinks I need to invest in actual computing books as learning from > biologists is hazy! > > Kind regards, > Seafoid. > > Steve's message was good, but I feel he kind of jumped in the middle. A class is a description of a type of object, and the behaviors and data that each instance of the object supports. You create the object by using the class name like a function call. The arguments to that "call" are passed to the __init__ method. So obj = Seq("abcd") or obj = Seq("defg", "abcdefg") would each create an object of the class. But generally, many objects will exist, each with different data. The data in the object is accessed in what appears to be the "self" namespace. The name self is just a convention, but it's the first argument of each method of the class. So when somebody calls the count() method, they pass 'item' a value, but self is used to refer to that particular object's data. So how does 'self' get assigned? That's what Steve was describing. When you use the syntax: obj.count("value") you actually call the count method with self referring to "obj" and item referring to "value". obj does double-duty here, both defining which class' count() method will be called, and also supplying the first parameter to the call, the "self" parameter. There are more complex things that can go on, like creating "bound" function objects, but I think this should get you pretty far. One other point: you should always derive a class from some other class, or 'object' by default. So you should being the class definition by: class Seq(object): Why? It mainly has to do with super(). But in any case if you omit the 'object' it's an "old style" class, and that's not even supported in 3.x, so it's better to just get in the habit before it matters. DaveA From nobody at nowhere.com Fri Dec 18 23:16:55 2009 From: nobody at nowhere.com (Nobody) Date: Sat, 19 Dec 2009 04:16:55 +0000 Subject: Seek support for new slice syntax PEP. References: <8e5054b1-8424-4633-a52e-1d9dcd1637b6@c34g2000yqn.googlegroups.com> <4B2B9676.4070206@gmail.com> Message-ID: On Fri, 18 Dec 2009 09:49:26 -0500, Colin W. wrote: > You don't say, but seem to imply that the slice components include None. That's how missing components are implemented at the language level: > class foo: = def __getitem__(self, s): = return s = > x = foo() > x[::] slice(None, None, None) > x[1::2] slice(1, None, 2) The defaults of zero, sys.maxint and one apply to built-in types, but nothing forces user-defined types to behave this way. Or maybe I misunderstood your point. From alfps at start.no Fri Dec 18 23:21:10 2009 From: alfps at start.no (Alf P. Steinbach) Date: Sat, 19 Dec 2009 05:21:10 +0100 Subject: Creating Classes In-Reply-To: References: <26848375.post@talk.nabble.com> Message-ID: * Dave Angel -> seafoid: > > One other point: you should always derive a class from some other > class, or 'object' by default. So you should being the class definition > by: > > class Seq(object): > > Why? It mainly has to do with super(). But in any case if you omit the > 'object' it's an "old style" class, and that's not even supported in > 3.x, so it's better to just get in the habit before it matters. I think it's best to mention that the above applies to Python 2.x. In Python 3.x, writing class Seq: is equivalent to writing class Seq( object ): E.g., >>> class A: pass ... >>> A.__bases__ (,) >>> >>> class B( object ): pass ... >>> B.__bases__ (,) >>> _ Curiously I can't find anything about 'object' in the language spec, but in the 3.1.1 standard library spec ?2 "Built-in functions" it says "object is a base for all classes." Cheers, - Alf From davea at ieee.org Fri Dec 18 23:49:16 2009 From: davea at ieee.org (Dave Angel) Date: Fri, 18 Dec 2009 23:49:16 -0500 Subject: Creating Classes In-Reply-To: References: <26848375.post@talk.nabble.com> Message-ID: <4B2C5B4C.2000103@ieee.org> Alf P. Steinbach wrote: >
        * Dave > Angel -> seafoid: >> >> One other point: you should always derive a class from some other >> class, or 'object' by default. So you should being the class >> definition by: >> >> class Seq(object): >> >> Why? It mainly has to do with super(). But in any case if you omit >> the 'object' it's an "old style" class, and that's not even supported >> in 3.x, so it's better to just get in the habit before it matters. > > I think it's best to mention that the above applies to Python 2.x. > > In Python 3.x, writing > > class Seq: > > is equivalent to writing > > class Seq( object ): > > We were talking about 2.x And I explicitly mentioned 3.x because if one develops code that depends on old-style classes, they'll be in trouble with 3.x, which has no way to specify old-style classes. In 3.x, all classes are new-style. And although it'll no longer matter whether you specify (object), it doesn't do any harm. As I said, it's a good habit for a beginner to get into when defining classes. DaveA From greg.ewing at canterbury.ac.nz Sat Dec 19 00:10:17 2009 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Sat, 19 Dec 2009 18:10:17 +1300 Subject: iterators and views of lists In-Reply-To: References: <89604fb4-9dfa-45f1-a3df-f676cd4353ea@x5g2000prf.googlegroups.com> <87b87511-744c-450e-a024-976f8c57f032@15g2000prz.googlegroups.com> <00b47124$0$15654$c3e8da3@news.astraweb.com> Message-ID: <7p34t6F5u7U1@mid.individual.net> Terry Reedy wrote: > On the other hand, Python indexes are a form of > random access iterator, the top of the hierarchy. The term "random access iterator" seems oxymoronic to me. Iteration is all about operating on things in sequence. If you're accessing elements arbitrarily, then you're not iterating. > Python, traditionally, only came with one mutable builtin sequence type, > so the sort function was made a method of that type. Also it probably operates rather more efficiently than a generic one would, as it doesn't have to go through a general mechanism to access elements, but can take advantage of its knowledge of the internal structure of a list. -- Greg From greg.ewing at canterbury.ac.nz Sat Dec 19 00:15:18 2009 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Sat, 19 Dec 2009 18:15:18 +1300 Subject: Dangerous behavior of list(generator) In-Reply-To: References: Message-ID: <7p356kF750U1@mid.individual.net> Albert van der Horst wrote: > An important feature that is not documented is a severe defect. This isn't something that I would expect to find documented under the heading of generator expressions, because it doesn't have anything to do with them. It's an interaction between the iterator protocol and the list() constructor. Any other iterable that leaked a StopIteration exception would cause the same effect. -- Greg From greg.ewing at canterbury.ac.nz Sat Dec 19 00:39:28 2009 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Sat, 19 Dec 2009 18:39:28 +1300 Subject: Programming intro book ch1 and ch2 (Windows/Python 3) - Request For Comments In-Reply-To: References: Message-ID: <7p36juFcrpU1@mid.individual.net> Mensanator wrote: > Really? Does that mean you don't use literals, to save the time > required to convert them to integers? I think all he means is that when he *does* use a named constant, he spells it in lower case rather than upper case, e.g. 'twopi' rather than 'TWOPI'. I don't think there's anything much wrong with that. It can be useful sometimes to visually distinguish constants from variables, but it's not a necessity. Also the all- uppercase convention isn't the only way to do that -- it's a C-ism that isn't universally followed in Python. An alternative often used is just to uppercase the first character. Python itself uses that for many of its built-in constants, such as None, True, False. Arguing that functions are usually constants and should therefore have uppercase names is missing the point -- everyone expects them to be constant anyway, so there's no need for a typographical convention to indicate that. In the rare cases where they're not constant, they can usually be named in a way that makes this obvious. (And BTW, looking up a global name is *slower* than using a literal. Although a local name is probably about the same speed as a literal, as they're both array accesses.) -- Greg From steve at REMOVE-THIS-cybersource.com.au Sat Dec 19 00:41:51 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 19 Dec 2009 05:41:51 GMT Subject: Programming intro book ch1 and ch2 (Windows/Python 3) - Request For Comments References: <00b5c744$0$15654$c3e8da3@news.astraweb.com> <87ljgzwsiw.fsf@castleamber.com> Message-ID: <00b5ec4d$0$15654$c3e8da3@news.astraweb.com> On Fri, 18 Dec 2009 21:29:27 -0600, John Bokma wrote: > Steven D'Aprano writes: > >> CPython 2.5 and on has a keyhole optimizer that replaces many constant > ^^^^^^^ > Shouldn't that be peephole? Alternate names for the same thing. >> expressions with pre-computed values. > > And that's called constant folding. Yes. > Unless I misread your post (or have been out of touch with compiler > building too long) No :) -- Steven From greg.ewing at canterbury.ac.nz Sat Dec 19 00:49:24 2009 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Sat, 19 Dec 2009 18:49:24 +1300 Subject: shouldn't list comprehension be faster than for loops? In-Reply-To: References: <979c8ffe-dc39-4b2b-ab9b-12ecefc12d7a@y24g2000yqb.googlegroups.com> <8808c896-0bb9-42e0-aa61-319adadf31d1@b2g2000yqi.googlegroups.com> Message-ID: <7p376iFf4aU1@mid.individual.net> Ryan Kelly wrote: >Someone else wrote: >>It will be the >>same as the difference between a for loop and a call to map. > > Not so. If you use the "dis" module to peek at the bytecode generated > for a list comprehension, you'll see it's very similar to that generated > for an explicit for-loop. The usual advice is that if you have a built-in function that does what you want done for each element, then using map() is probably the fastest way. However, if you need to create a Python function to pass to map(), the list comprehension may well be faster, because it avoids the cost of a Python function call per element. -- Greg From catphive at catphive.net Sat Dec 19 00:51:46 2009 From: catphive at catphive.net (Brendan Miller) Date: Fri, 18 Dec 2009 21:51:46 -0800 Subject: iterators and views of lists In-Reply-To: <7a50d745-34e7-4445-ba49-5d8d815ac2ba@l13g2000yqb.googlegroups.com> References: <89604fb4-9dfa-45f1-a3df-f676cd4353ea@x5g2000prf.googlegroups.com> <87b87511-744c-450e-a024-976f8c57f032@15g2000prz.googlegroups.com> <7a50d745-34e7-4445-ba49-5d8d815ac2ba@l13g2000yqb.googlegroups.com> Message-ID: On Fri, Dec 18, 2009 at 2:47 PM, Bearophile wrote: > Brendan Miller: >> I agree though, it doesn't matter to everyone and anyone. The reason I >> was interested was because i was trying to solve some specific >> problems in an elegant way. I was thinking it would be cool to make >> python more usable in programming competitions by giving it its own >> port of the STL's algorithm library, which needs something along the >> lines of C++'s more powerful iterators. > > It seems you have missed my post, so here it is, more explicitly: > > http://www.boostcon.com/site-media/var/sphene/sphwiki/attachment/2009/05/08/iterators-must-go.pdf > > Bye, > bearophie > -- > http://mail.python.org/mailman/listinfo/python-list > Andrei is arguing for replacing iterators with ranges, which are equivalently powerful to C++ iterators but easier to use. Actually, what I want in python is something like this. If you look at Anh Hai Trinh's posts he implemented something basically like a python version of andre's ranges, which he called listagents. That pdf is interesting though because he's thought through what an interface for bidrectional ranges should look like which I had not yet. However, you should note that andrei's ranges allow mutation of the original datastructure they are a range over. My impression from your earlier post was that you disagreed with that idea of mutating algorithms and wanted something more functional, whereas I, and andrei in that pdf, are more concerned with imperative programming and in place algorithms. I don't want to get into a big discussion about FP vs imperative programming, as that is simply too large a topic and I have had that discussion many times before. I'm more of a turing machine than a lambda calculus guy myself, but if other people make other choices that's fine with me. From steve at REMOVE-THIS-cybersource.com.au Sat Dec 19 01:02:51 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 19 Dec 2009 06:02:51 GMT Subject: Programming intro book ch1 and ch2 (Windows/Python 3) - Request For Comments References: <00b5b774$0$15654$c3e8da3@news.astraweb.com> Message-ID: <00b5f13a$0$15654$c3e8da3@news.astraweb.com> On Sat, 19 Dec 2009 04:04:51 +0100, Alf P. Steinbach wrote: > * Steven D'Aprano: >> On Fri, 18 Dec 2009 19:00:48 +0100, Alf P. Steinbach wrote: >> >>> In fact almost no Python >>> code does, but then it seems that people are not aware of how many of >>> their names are constants and think that they're uppercasing constants >>> when in fact they're not. E.g. routine arguments >> >> Routine arguments are almost never constants, since by definition they >> will vary according to the value passed by the caller. > > I'm sorry, but that requires a definition of "constant" that explicitly > excludes routine arguments, /s/explicitly/implicitly > which is like saying horses are not mammals, just "because". No, it's like saying that horses are not apes, because the definition of apes excludes horses. But in any case, rather than continue my argument (which was absolutely brilliant and flawless, I might add... *wink*), I'm going to skip ahead to the place where the penny drops and I understand what you were trying, but failed, to say. > Consider some C++ code: > > void foo( SomeType const v ) > { > // Here the name v is constant: that name's value can't change. > // (Except that in C++ you can do anything by using low-level > stuff.) > } *penny drops* Ahaha!!! Now I get it! You want to make the *parameter* of the function a constant, rather than the *argument* passed to the function. In other words, you want to prohibit something like this: def f(x): y = x + 1 # do something with the value passed by the caller x = 0 # changing the binding will fail INSIDE the function while still allowing the caller to call the function with variables. Right -- now what you say makes sense, and is a perfectly reasonable thing to do in languages that support constants. You weren't clear about what you wanted, and the only thing I could think of which matched your description was something completely bizarre: given some function f with one parameter, you wanted to declare that parameter as a constant with some value (say 42), so that calling the function with an argument of any other value would be an error, e.g.: x = 42 f(x) # succeeds x = 43 f(x) # fails E.g. implemented something like this: def f(x): if x != 42: raise ConstantError('x is not the constant 42') ... except that the test is done automatically by the compiler. > To be pedantic, original routine names are usually absolutely not meant > to be assigned to. > > If you have > > def foo(): whatever() > > you simply shouldn't, in general, do > > foo = bar > > I think you understood that, i.e., that the above comment of yours is > just rhetoric? First of all, I think you're underestimating the usefulness and frequency of rebinding names to functions. I'll accept that it's uncommon, but it's not *that* uncommon to justify "absolutely not meant to be assigned to". In fact, it's so common that we have special syntax for one special case of it. Instead of: def f(): ... f = g(f) we can write: @g def f(): ... While decorator syntax can only be used at function-definition time, the concept of function decoration is far more general. You can decorate any function, at any time, and doing so is very, very useful for (e.g.) debugging, logging, monkey-patching, introspection, error-checking, and others. And decoration itself is only one special case of function rebinding. As for your second point, my earlier comment is mostly aimed at what I see as your misleading habit of referring to *names* as being constants, rather than the value assigned to the name. Such terminology is misleading. So if you want to call that rhetoric, I won't argue. >> As far as I know, no programming language provides a standard facility >> for renaming entities, be they data or routines: > > Eiffel (IIRC) and C++ come pretty close. > > E.g., in C++: > > int a; > int& b = a; // A new name for a. > > b = 123; // Assigns to a. No, that's not a renaming operation. a still exists; you haven't told the compiler "stop accepting a as the name for this memory location, and accept b instead". It's an aliasing operation: name b and name a both refer to the same memory location and hence the same value. Even if C++ had an operation for "delete this name from the compiler's symbol table" (equivalent to del in Python), that's still a two-step process: create a new name that co-exists with the original name, then delete the original name. The fact that the C++ designers didn't see fit to give the language a way to change a name demonstrates that it's not the mutability of *names* which matter, but of *values* assigned to the names. I can think of a language where it would probably be possible, but non- standard, to write a rename instruction: Forth. It should be possible to use the tick instruction to get the address of a variable, constant or function, then directly manipulate the compiler's dictionary (not like Python dictionaries!) to change the name. But even Forth doesn't provide a rename instruction as standard. > Well, you're off on the wrong track as far as convincing me about > something is concerned. First, your belief about renaming not being > supported by any languages is largely incorrect, as shown above. > Secondly, I was not talking about renaming things -- that creative > interpretation is pretty meaningless... But if you talk about mutating *names*, then what else could it mean than that you want to change the *name*? I can only respond to what you write, not what you were thinking. You wrote "routine names are usually constants, absolutely not meant to be modified". Forget all about routines. If you had written: "int names are usually constants, absolutely not meant to be modified" then I'm sure you and I would agree: such a claim confuses the name with the value assigned to the name. It's literally true that given an int n, it is not usual to modify the *name* n regardless of whether n is a variable or a constant. But that's irrelevant to the question of whether n is a variable or a constant. That depends on the *value* assigned to n, not the name itself. Exactly the same applies to functions. If you think I'm harping on a trivial point of terminology, I guess you're half-right: I can *guess* what you mean to say, namely that function objects themselves are meant to be unmodified, and in Python it is unusual to rebind names once they have been bound to a function. (Unusual but not vanishingly so.) But that's just an assumption, and you know what they say about assumptions. Judging by what you actually say, and not what I assume you mean, your reason for believing functions are constants is incorrect and illogical. In languages that treat functions as constants, functions aren't treated as constant because the name of the function is unchangeable (since variables have unchangeable names too). They do so because the value (the function itself) is unchangeable. -- Steven From mensanator at aol.com Sat Dec 19 01:06:51 2009 From: mensanator at aol.com (Mensanator) Date: Fri, 18 Dec 2009 22:06:51 -0800 (PST) Subject: Programming intro book ch1 and ch2 (Windows/Python 3) - Request For Comments References: Message-ID: On Dec 18, 6:25?pm, "Alf P. Steinbach" wrote: > * Mensanator: > > >> The second deviation is that since most names are constants, > > > Really? Does that mean you don't use literals, to save the time > > required to convert them to integers? Isn't that done at compile > > time? > > > So, instead of doing the Collatz Conjecture as > > > while a>1: > > ? f = gmpy.scan1(a,0) > > ? if f>0: > > ? ? a = a >> f > > ? else: > > ? ? a = a*3 + 1 > > > You would do this? > > > zed = 0 > > one = 1 > > two = 2 > > twe = 3 > > while a>one: > > ? f = gmpy.scan1(a,zed) > > ? if f>zed: > > ? ? a = a >> f > > ? else: > > ? ? a = a*twe + one > > That seems to have no relation to what you quoted / responded to. Whose fault is that? Here's a hint: when people's replies don't make any sense, it's because they don't understand your prattle. That's not good for someone who fancies himself a teacher of programming. > > On the other hand, if there is some specific r?le played by the 3 above, where > some other value (like e.g. 5) might be used instead, then a self descriptive > name for that r?le might be good. > > Such reasonable naming (not what you did above) then allows easier modification > of and makes it easier to understand the code. > > That said, and a bit off-tangent to your comment's main thrust, the time spent > on coding that repeated-division-by-2 optimization would, I think, be better > spent googling "Collatz Conjecture" ?-- ?avoiding writing /any/ code. ;-) Ha! I know more about Collatz than you can ever find by Googling! And how did I achieve that? By writing such code. Be a good boy and maybe I'll show you how to do Ulam's Spiral with Turtle Graphics. > > > Does this really save any time? > > If by "it" you mean the silly naming, no it doesn't. > > On the contrary, it wastes time, both for writing the code and reading it. > > Generally, IMO, think about the clarity of your code. If naming something > increases clarity, then name the thing. If it doesn't increase clarity, don't. > > > > > > > Now, it's a different story if you're using the gmpy module. > > You DON'T want to use literals in loops involving gmpy, because > > they would have to be coerced to .mpz's on every pass through the > > loop. > > > In that case, you DO want to use constants as opposed to literals: > > > ZED = gmpy.mpz(0) > > ONE = gmpy.mpz(1) > > TWO = gmpy.mpz(2) > > TWE = gmpy.mpz(3) > > while a>ONE: > > ? f = gmpy.scan1(a,0) # int used here, so it can be a literal > > ? if f>ZED: > > ? ? a = a >> f > > ? else: > > ? ? a = a*TWE + ONE > > > And yes, the time savings can be tremendous, especially when 'a' > > has over 50,000 decimal digits. > > Yeah, good point. Few languages have compile time evaluation of logically > constant expressions. C++0x will have that feature (called 'constexpr' IIRC) but > in Python, current C++ etc. it's just a good idea to precompute values, and name > them, rather than computing them again and again where they're needed. > > > . I do not follow PEP > >> 8's recommendation to use uppercase names of constants. In fact almost no Python > >> code does, > > > Mine does when I use gmpy. Otherwise, the notion that "most names > > are constants" is generally false. > > No, it depends on what you mean by "constant". Why don't you try using what PEP 8 means by "constant". > The problem with Python, as > Google noted, is that the language is so excessively dynamic: even names of > routines are variables, and there /are/ no named user defined constants except > logically, in the programmer's mind. And logically (that is, at the "in the > programmer's mind" level), if you define "constant" as a name whose value will > not change after initialization, then routine names are constants. You're sitting too close to the fire. Why don't you back off and quit overanalizing things. > > However, if you define "constant" as only a global scope (that is, module scope) > name that denotes a boolean, numerical or string or Null value and that doesn't > change after initialization, then your statement about the scarcity of constants > appears to be true, but using a practically useless definition. > > I think for such constants exported by modules it's a good idea to at least > provide uppercase names so as conform to very firmly established convention. > There might even be tools that rely on that convention. But for application code > the uppercase names are just distracting, and they don't help you... They help when I look at something like a = (i-ONE)*NIN**(k-ONE) + (NIN**(k-ONE) - ONE)//TWO + ONE > > Cheers & hth., > > - Alf From alfps at start.no Sat Dec 19 01:21:18 2009 From: alfps at start.no (Alf P. Steinbach) Date: Sat, 19 Dec 2009 07:21:18 +0100 Subject: Programming intro book ch1 and ch2 (Windows/Python 3) - Request For Comments In-Reply-To: References: Message-ID: * Mensanator: >> >> That said, and a bit off-tangent to your comment's main thrust, the time spent >> on coding that repeated-division-by-2 optimization would, I think, be better >> spent googling "Collatz Conjecture" -- avoiding writing /any/ code. ;-) > > Ha! I know more about Collatz than you can ever find by Googling! > And how did I achieve that? By writing such code. Be a good boy and > maybe I'll show you how to do Ulam's Spiral with Turtle Graphics. It's probably good for you that you know so much about Collatz. I fail to see the relevance to anything. Cheers & hth., - Alf From lie.1296 at gmail.com Sat Dec 19 01:30:27 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Sat, 19 Dec 2009 17:30:27 +1100 Subject: Sort the values of a dict In-Reply-To: <4b2c0386$0$1105$4fafbaef@reader4.news.tin.it> References: <4b2c0386$0$1105$4fafbaef@reader4.news.tin.it> Message-ID: <4b2c7303@dnews.tpgi.com.au> On 12/19/2009 9:34 AM, mattia wrote: > Can you provide me a much pythonic solution (with comments if possible, > so I can actually learn something)? If you only need to get i'th element sometimes, sorting the dict is fine. Otherwise, you might want to use collections.OrderedDict. From mensanator at aol.com Sat Dec 19 01:35:58 2009 From: mensanator at aol.com (Mensanator) Date: Fri, 18 Dec 2009 22:35:58 -0800 (PST) Subject: Programming intro book ch1 and ch2 (Windows/Python 3) - Request For Comments References: Message-ID: <514c360a-6a0d-48a5-839b-3b69590b93c5@y24g2000yqb.googlegroups.com> On Dec 19, 12:21?am, "Alf P. Steinbach" wrote: > * Mensanator: > > > > >> That said, and a bit off-tangent to your comment's main thrust, the time spent > >> on coding that repeated-division-by-2 optimization would, I think, be better > >> spent googling "Collatz Conjecture" ?-- ?avoiding writing /any/ code. ;-) > > > Ha! I know more about Collatz than you can ever find by Googling! > > And how did I achieve that? By writing such code. Be a good boy and > > maybe I'll show you how to do Ulam's Spiral with Turtle Graphics. > > It's probably good for you that you know so much about Collatz. > > I fail to see the relevance to anything. No kidding. Here let me explain it: You said my time would be better spent googling "Collatz Conjecture". I said I know more than can be found by googling. Therefore, it follows that my time could NOT be better spent googling. Thus, your staement is shown to be false. QED > > Cheers & hth., > > - Alf From lie.1296 at gmail.com Sat Dec 19 01:40:04 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Sat, 19 Dec 2009 17:40:04 +1100 Subject: Programming intro book ch1 and ch2 (Windows/Python 3) - RequestFor Comments In-Reply-To: <00b5b774$0$15654$c3e8da3@news.astraweb.com> References: <00b5b774$0$15654$c3e8da3@news.astraweb.com> Message-ID: <4b2c7543$1@dnews.tpgi.com.au> On 12/19/2009 12:56 PM, Steven D'Aprano wrote: > As far as I know, no programming language provides a standard facility > for renaming entities, be they data or routines: The C-preprocessor does to C/C++, in a limited fashion. From steve at REMOVE-THIS-cybersource.com.au Sat Dec 19 01:40:11 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 19 Dec 2009 06:40:11 GMT Subject: Programming intro book ch1 and ch2 (Windows/Python 3) - Request For Comments References: <00b5c744$0$15654$c3e8da3@news.astraweb.com> Message-ID: <00b5f9fa$0$15654$c3e8da3@news.astraweb.com> On Sat, 19 Dec 2009 04:29:22 +0100, Alf P. Steinbach wrote: > * Steven D'Aprano: >> On Sat, 19 Dec 2009 01:25:48 +0100, Alf P. Steinbach wrote: >> >>> That said, and a bit off-tangent to your comment's main thrust, the >>> time spent on coding that repeated-division-by-2 optimization would, I >>> think, be better spent googling "Collatz Conjecture" -- avoiding >>> writing /any/ code. ;-) >> >> That's a strange thing to say. > > No. The code shown was like attacking Fermat's last theorem with a > little Python script checking out number triplets. It's already been > done (not to mention that that theorem's been proven, although that's, > AFAIK, not the case for Collatz'). You're assuming that Mensanator's motive for writing code is to challenge the Collatz Conjecture, rather than to just have fun doing maths and programming, or to build up his skills for a serious effort at extending the domain of values for which it is known to be true. Or just because he needs a function that calculates the hailstone numbers. >>>> Now, it's a different story if you're using the gmpy module. You >>>> DON'T want to use literals in loops involving gmpy, because they >>>> would have to be coerced to .mpz's on every pass through the loop. >> [...] >>> Yeah, good point. Few languages have compile time evaluation of >>> logically constant expressions. >> >> Surely that's an implementation issue rather than a language issue. > > No, it isn't. > > An optimizer can only do so much, as you yourself note below! You make no sense here. What I note below is the existence of an implementation-specific optimizer. And your conclusion? That such optimization is language specific! How does that make sense? Obviously it wouldn't be sensible for CPython to optimize numeric literals as mpz objects, because that would be a lot of overhead for very little gain. But it might make sense for somebody to create a "Numeric Python" implementation which used mpz as the standard integer type. A slightly more tricky case is optimizing away more complex runtime expressions. len("abc") is not necessarily the constant 3, because the function len may have been replaced by something else, thus requiring it to be calculated at runtime rather than compile-time. But an implementation might relax that condition and treat built-ins as constants. Guido probably will never allow such a thing in CPython, but other implementations are free to do things differently. Even if people argue that such a behavioural change is "no longer Python", there's nothing preventing an optimizing implementation from replacing "abc".__len__() with the constant 3 except the complexity of implementation and the diminishing returns of doing so. > With language support it's a very different matter because guarantees > propagate so that sophisticated analysis is no longer necessary: the > compiler /knows/, because it's explicitly being told. Of course if a language makes a certain guarantee (for example, that calls to math.exp(0) will be replaced at compile-time with 1.0) then the compiler can make that substitution. But such optimizations tend not to be specified by the language (in fact languages like C often tend to leave large amounts of behaviour as implementation-defined), and even when languages do make certain guarantees, implementations are free to implement any behaviour not implicitly or explicitly forbidden. >>>> Mine does when I use gmpy. Otherwise, the notion that "most names are >>>> constants" is generally false. >>> No, it depends on what you mean by "constant". >> >> All names are constant. Always. The Python language does not support >> renaming names -- as far as I know, no language does. > > No-ones been talking about renaming names. I think that's purely > rhetorical on your part but it may be that you really believe so. In the > latter case, just try to interpret statements so that they're meaningful > instead of meaningless. :-) (1) It's not meaningless to talk about renaming names. (2) I will not try to guess what you mean on the basis of what I consider sensible, rather than respond to what you actually say. (3) I've already gone over the name/value thing to death in another post, so I'll do everyone a favour and not continue it here. [...] >> The terms >> "constant" and "variable" refer to the values bound to a name, not the >> name itself: > > I'm sorry, that's incorrect. > > Quote from ?4.1 "Naming and binding" of the Python 3.1.1 language spec: > > "If a name is bound in a block, it is a local variable of that block, > unless declared as nonlocal. If a name is bound at the module level, it > is a global variable. (The variables of the module code block are local > and global.) If a variable is used in a code block but not defined > there, it is a free variable." Since the above quote doesn't mention "constant", how on earth can you use it as evidence for what "constant" refers to? In any case, the words "constant" and "variable" have multiple meanings. They can be either nouns or adjectives. Constants (nouns) are called constants because of the value is constant (adjective) -- and similar for variables. -- Steven From app at godeck.com Sat Dec 19 01:42:31 2009 From: app at godeck.com (AppRe Godeck) Date: Sat, 19 Dec 2009 00:42:31 -0600 Subject: Anybody use web2py? Message-ID: <6oidnWzFKdtK6LHWnZ2dnUVZ_opi4p2d@supernews.com> Just curious if anybody prefers web2py over django, and visa versa. I know it's been discussed on a flame war level a lot. I am looking for a more intellectual reasoning behind using one or the other. From lie.1296 at gmail.com Sat Dec 19 01:51:30 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Sat, 19 Dec 2009 17:51:30 +1100 Subject: Object Relational Mappers are evil (a meditation) In-Reply-To: <858wd2xmi4.fsf@agentultra.com> References: <06532563-3f2b-4cca-802f-34cb326e6d9f@v20g2000vbs.googlegroups.com> <16a44521-1f07-454a-ace7-9ba5d5db4b9c@y28g2000prd.googlegroups.com> <50f98a4c0910060810k3a4fa910vabc5bf51381d00f9@mail.gmail.com> <00ac7cf3$0$15654$c3e8da3@news.astraweb.com> <85hbrrxaf9.fsf@agentultra.com> <85d42eyag8.fsf@agentultra.com> <7osvd9F3r79lcU1@mid.individual.net> <858wd2xmi4.fsf@agentultra.com> Message-ID: <4b2c77f1$1@dnews.tpgi.com.au> On 12/17/2009 3:17 PM, J Kenneth King wrote: > A language is a thing. It may have syntax and semantics that bias it > towards the conventions and philosophies of its designers. But in the > end, a language by itself would have a hard time convincing a human > being to adopt bad practises. Perhaps someone should make a research whether if you teach a language to kids, where one group is taught the language filtered from "bad words" and another group is taught all the languages' "bad words" on purpose. Will one group have more behavioral problems compared to the other? From lie.1296 at gmail.com Sat Dec 19 01:57:42 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Sat, 19 Dec 2009 17:57:42 +1100 Subject: iterators and views of lists In-Reply-To: <33e302a5-b509-4fa1-949a-b2123116c1b5@19g2000vbq.googlegroups.com> References: <10d50933-c1e8-44a8-af35-dce39c444778@u18g2000pro.googlegroups.com> <33e302a5-b509-4fa1-949a-b2123116c1b5@19g2000vbq.googlegroups.com> Message-ID: <4b2c7965$1@dnews.tpgi.com.au> On 12/17/2009 4:44 AM, Francesco Bochicchio wrote: > On Dec 16, 1:58 pm, Anh Hai Trinh wrote: > >> >> You might be interested in this library> stream>. >> >> You can easily create arbitrary "slice", for example >> >> i = mylist>> takei(primes()) >> >> will return an iterator over the items of mylist with a prime number >> index, given that primes() return an iterator over prime numbers. >> > > > Nice :-) > > I was starting to experiment data flow programming with python myself, > although I'm just playing with it.. > I find the idea of data flow programming fascinatin, and wonder if it > can be considered a general-purpose program paradigm. It is actually. http://en.wikipedia.org/wiki/Pipeline_programming http://en.wikipedia.org/wiki/Flow-based_programming From alfps at start.no Sat Dec 19 02:17:12 2009 From: alfps at start.no (Alf P. Steinbach) Date: Sat, 19 Dec 2009 08:17:12 +0100 Subject: Programming intro book ch1 and ch2 (Windows/Python 3) - Request For Comments In-Reply-To: <00b5f13a$0$15654$c3e8da3@news.astraweb.com> References: <00b5b774$0$15654$c3e8da3@news.astraweb.com> <00b5f13a$0$15654$c3e8da3@news.astraweb.com> Message-ID: <4B2C7DF8.5030300@start.no> * Steven D'Aprano: > On Sat, 19 Dec 2009 04:04:51 +0100, Alf P. Steinbach wrote: > >> * Steven D'Aprano: >>> On Fri, 18 Dec 2009 19:00:48 +0100, Alf P. Steinbach wrote: >>> >>>> In fact almost no Python >>>> code does, but then it seems that people are not aware of how many of >>>> their names are constants and think that they're uppercasing constants >>>> when in fact they're not. E.g. routine arguments >>> Routine arguments are almost never constants, since by definition they >>> will vary according to the value passed by the caller. >> I'm sorry, but that requires a definition of "constant" that explicitly >> excludes routine arguments, > > /s/explicitly/implicitly > > >> which is like saying horses are not mammals, just "because". > > No, it's like saying that horses are not apes, because the definition of > apes excludes horses. On the contrary. Apes are not superclass of horses. > But in any case, rather than continue my argument (which was absolutely > brilliant and flawless, I might add... *wink*), I'm going to skip ahead > to the place where the penny drops and I understand what you were trying, > but failed, to say. > > >> Consider some C++ code: >> >> void foo( SomeType const v ) >> { >> // Here the name v is constant: that name's value can't change. >> // (Except that in C++ you can do anything by using low-level >> stuff.) >> } > > *penny drops* > > Ahaha!!! Now I get it! You want to make the *parameter* of the function a > constant, rather than the *argument* passed to the function. In other > words, you want to prohibit something like this: > > def f(x): > y = x + 1 # do something with the value passed by the caller > x = 0 # changing the binding will fail INSIDE the function > > while still allowing the caller to call the function with variables. I would want the possibility of having that enforced, of course, because the more you know about what can't take place in the code, i.e. the more easy-to-see constraints there are, the easier it is to understand and reason about the code, not to mention modifying it without breaking original assumptions. But I wasn't talking about such a language feature (which I believe could also greatly improve Python's efficiency by removing the need for many lookups). Rather, I was remarking that in the absence of such a language feature, to be consistent those who insist on using naming conventions to indicate design level constraints should use those naming conventions also for this case and others. For there's little point in making some occurrences of a constraint visually explicit and others not. That just means that one cannot rely on the convention to tell where the constraint is (meant to be) in effect or not. > Right -- now what you say makes sense, and is a perfectly reasonable > thing to do in languages that support constants. > > You weren't clear about what you wanted, and the only thing I could think > of which matched your description was something completely bizarre: given > some function f with one parameter, you wanted to declare that parameter > as a constant with some value (say 42), so that calling the function with > an argument of any other value would be an error, e.g.: > > x = 42 > f(x) # succeeds > x = 43 > f(x) # fails > > E.g. implemented something like this: > > def f(x): > if x != 42: > raise ConstantError('x is not the constant 42') > ... > > except that the test is done automatically by the compiler. > > >> To be pedantic, original routine names are usually absolutely not meant >> to be assigned to. >> >> If you have >> >> def foo(): whatever() >> >> you simply shouldn't, in general, do >> >> foo = bar >> >> I think you understood that, i.e., that the above comment of yours is >> just rhetoric? > > First of all, I think you're underestimating the usefulness and frequency > of rebinding names to functions. I'll accept that it's uncommon, but it's > not *that* uncommon to justify "absolutely not meant to be assigned to". Yeah, hence the weasel term "in general". > In fact, it's so common that we have special syntax for one special case > of it. Instead of: > > def f(): > ... > > f = g(f) > > we can write: > > @g > def f(): > ... > > While decorator syntax can only be used at function-definition time, the > concept of function decoration is far more general. You can decorate any > function, at any time, and doing so is very, very useful for (e.g.) > debugging, logging, monkey-patching, introspection, error-checking, and > others. And decoration itself is only one special case of function > rebinding. But usually this wrapping occurs before the function is first used by other code, i.e. it's usually part of initialization -- isn't it? For debugging purposes you might want to replace a function on-the-fly, in the middle of the program execution. But debugging does all sorts of things not commonly accepted for normal execution. > As for your second point, my earlier comment is mostly aimed at what I > see as your misleading habit of referring to *names* as being constants, > rather than the value assigned to the name. Such terminology is > misleading. So if you want to call that rhetoric, I won't argue. Not sure what that second point was (lost in response stack and snippage somewhere), but as I remarked else-thread, in response to you, I'm sorry, but your view about names is incorrect. Quote from ?4.1 "Naming and binding" of the Python 3.1.1 language spec: "If a name is bound in a block, it is a local variable of that block, unless declared as nonlocal. If a name is bound at the module level, it is a global variable. (The variables of the module code block are local and global.) If a variable is used in a code block but not defined there, it is a free variable." It's not just terminology that a Python name "is" a variable, and vice versa. Constness of the referred to value is an appropriate concept when that value is conceptually mutable, like v = [1, 2, 3] This particular case is supported for the referent, v = (1, 2, 3) # Voila, constant referent which expresses and enforces the constness of the referent. But to express the constness of the variable, which is what matters most of all (for without that top level constness all other constness, such as of direct referent, can be easily and inadvertently circumvented) all you can do is to e.g. name it V instead of v, or put its creation in a region of text clearly signalling "these are constants", or some such -- conventions. Since a variable is a name, and in Python a name is a variable, "constness of a variable" means "constness of a name". In Python. And as discussed above it's about any name binding whatsoever, while the PEP 8 naming convention is limited to communicating the intended constraint in just a few special cases, and hence is unreliable by design (in addition to introducing lots of visual gruff). >>> As far as I know, no programming language provides a standard facility >>> for renaming entities, be they data or routines: >> Eiffel (IIRC) and C++ come pretty close. >> >> E.g., in C++: >> >> int a; >> int& b = a; // A new name for a. >> >> b = 123; // Assigns to a. > > No, that's not a renaming operation. a still exists; you haven't told the > compiler "stop accepting a as the name for this memory location, and > accept b instead". It's an aliasing operation: name b and name a both > refer to the same memory location and hence the same value. Well, you can always do int& b = a; #define a __NO_SUCH_NAME__ He he. :-) Without the preprocessor you can do things like (or more elaborate) int a = 666; { int& b = a; struct a; // Only name b useful at this point. Most uses of a will be flagged. } And with the preprocessor that kind of renaming can be automated. But seriously I thought you were referring to aliasing, because changing a name mid-code generally makes no sense -- other than perhaps in an obfuscation contest (where of course techniques like the #define shown above /are/ employed, although typically with single letter names; it's a yearly contest for C...). [snip] > >> Well, you're off on the wrong track as far as convincing me about >> something is concerned. First, your belief about renaming not being >> supported by any languages is largely incorrect, as shown above. >> Secondly, I was not talking about renaming things -- that creative >> interpretation is pretty meaningless... > > But if you talk about mutating *names*, then what else could it mean than > that you want to change the *name*? I can only respond to what you write, > not what you were thinking. In Python names are variables, per the language spec and in practice. The language spec's saying: "If a name is bound in a block, it is a local variable of that block, unless declared as nonlocal. If a name is bound at the module level, it is a global variable. (The variables of the module code block are local and global.) If a variable is used in a code block but not defined there, it is a free variable." Plus that of course, given this, the spec generally uses "variable" and "name" as interchangeable synonyms, with just a little context-dependent favoring of one or the other -- if you want example quotes I can provide a host of them. And most variables, at least in code I'm familiar with, are constants, in the sense that they're not intended to be re-bound after initialization. And that's what I wrote, "most names are constants", and it was actually meant to be precise: I was not talking about referred to objects, only about name re-binding, that is, about changing what you get by id(N) for a name N. Cheers & hth. (all cleared up now?), - Alf From alfps at start.no Sat Dec 19 02:44:42 2009 From: alfps at start.no (Alf P. Steinbach) Date: Sat, 19 Dec 2009 08:44:42 +0100 Subject: Programming intro book ch1 and ch2 (Windows/Python 3) - Request For Comments In-Reply-To: <00b5f9fa$0$15654$c3e8da3@news.astraweb.com> References: <00b5c744$0$15654$c3e8da3@news.astraweb.com> <00b5f9fa$0$15654$c3e8da3@news.astraweb.com> Message-ID: * Steven D'Aprano: > On Sat, 19 Dec 2009 04:29:22 +0100, Alf P. Steinbach wrote: > >> * Steven D'Aprano: >>> On Sat, 19 Dec 2009 01:25:48 +0100, Alf P. Steinbach wrote: >>> >>>> That said, and a bit off-tangent to your comment's main thrust, the >>>> time spent on coding that repeated-division-by-2 optimization would, I >>>> think, be better spent googling "Collatz Conjecture" -- avoiding >>>> writing /any/ code. ;-) >>> That's a strange thing to say. >> No. The code shown was like attacking Fermat's last theorem with a >> little Python script checking out number triplets. It's already been >> done (not to mention that that theorem's been proven, although that's, >> AFAIK, not the case for Collatz'). > > You're assuming that Mensanator's motive for writing code is to challenge > the Collatz Conjecture, rather than to just have fun doing maths and > programming, or to build up his skills for a serious effort at extending > the domain of values for which it is known to be true. Or just because he > needs a function that calculates the hailstone numbers. I would rather not speculate about motives. I can say things about the code that was presented, and I did, but as for the motives that went into creating it or presenting it in this thread, well I'm not telepathic. >>>>> Now, it's a different story if you're using the gmpy module. You >>>>> DON'T want to use literals in loops involving gmpy, because they >>>>> would have to be coerced to .mpz's on every pass through the loop. >>> [...] >>>> Yeah, good point. Few languages have compile time evaluation of >>>> logically constant expressions. >>> Surely that's an implementation issue rather than a language issue. >> No, it isn't. >> >> An optimizer can only do so much, as you yourself note below! > > You make no sense here. What I note below is the existence of an > implementation-specific optimizer. And your conclusion? That such > optimization is language specific! How does that make sense? No, I meant exactly what I wrote, that an optimizer only can do so much, which you also noted yourself; that language support facilitates this optimization; and that few languages have that support (but e.g. C++0x will have it). [snip] >> With language support it's a very different matter because guarantees >> propagate so that sophisticated analysis is no longer necessary: the >> compiler /knows/, because it's explicitly being told. > > Of course if a language makes a certain guarantee (for example, that > calls to math.exp(0) will be replaced at compile-time with 1.0) then the > compiler can make that substitution. Yes, that's what C++0x 'constexpr' is about. But I've lost the context here, not sure what this is all about. [snip] > (1) It's not meaningless to talk about renaming names. Well, as good as meaningless, IMHO. In fact, earlier, when you wrote under the assumption that I was talking about such renaming, you seemed to maintain that it was pretty meaningless. I conclude from that that also this is relative. > (2) I will not try to guess what you mean on the basis of what I consider > sensible, rather than respond to what you actually say. I rather hoped you would try to employ the "sensible" heuristic. The problem so far has, apparently, been that you refuse to accept the language specification's definition, in ?4.1, of variable as name and vice versa. An "is-it-sensible" heuristic could have cleared that up, I think. > (3) I've already gone over the name/value thing to death in another post, > so I'll do everyone a favour and not continue it here. But when that is the problem, a basic misunderstanding of what a word means, then it's worth uh, harping on the issue, I think: > [...] >>> The terms >>> "constant" and "variable" refer to the values bound to a name, not the >>> name itself: >> I'm sorry, that's incorrect. >> >> Quote from ?4.1 "Naming and binding" of the Python 3.1.1 language spec: >> >> "If a name is bound in a block, it is a local variable of that block, >> unless declared as nonlocal. If a name is bound at the module level, it >> is a global variable. (The variables of the module code block are local >> and global.) If a variable is used in a code block but not defined >> there, it is a free variable." > > Since the above quote doesn't mention "constant", how on earth can you > use it as evidence for what "constant" refers to? I don't. I use it as evidence for what "name" refers to. A constant "name" is then, logically, a constant such thing, to wit, a constant variable. You may find that terminology paradoxical. For C++, which has the means of enforcing it, it's a FAQ (many novices have some trouble accepting constant /variables/...). If it helps let's adopt Java's terminology and talk about "final" variables. Or, as Bjarne had it in original C++, "readonly" variables. > In any case, the words "constant" and "variable" have multiple meanings. > They can be either nouns or adjectives. Constants (nouns) are called > constants because of the value is constant (adjective) -- and similar for > variables. Yeah, but you're not seriously suggesting that any global variable initialized to a constant (immutable value) should be uppercased. So "constant" in this regard does not refer to the refererred to value. It refers to the id(v). Cheers & hth., - Alf From steve at REMOVE-THIS-cybersource.com.au Sat Dec 19 03:04:55 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 19 Dec 2009 08:04:55 GMT Subject: shouldn't list comprehension be faster than for loops? References: <979c8ffe-dc39-4b2b-ab9b-12ecefc12d7a@y24g2000yqb.googlegroups.com> <8808c896-0bb9-42e0-aa61-319adadf31d1@b2g2000yqi.googlegroups.com> Message-ID: <00b60dd7$0$15654$c3e8da3@news.astraweb.com> On Sat, 19 Dec 2009 12:28:32 +1100, Ryan Kelly wrote: >> Anything else being equal, list comprehensions will be the faster >> becuase they incur fewer name and attribute lookups. It will be the >> same as the difference between a for loop and a call to map. A list >> comprehension is basically an enhancement of map. > > Not so. If you use the "dis" module to peek at the bytecode generated > for a list comprehension, you'll see it's very similar to that generated > for an explicit for-loop. The byte-code for a call to map is very > different. "Very similar" and "very different" byte-code mean very little regarding speed. > Basically: both a for-loop and a list-comp do the looping in python > bytecode, while a call to map will do the actual looping in C. This is a classic example of the confirmation fallacy -- if you say that for-loops and list-comps are very similar, you need to actually check the byte-code of both. You don't. You need to compare the byte-code of all three operations, not just two of them, e.g.: dis.dis(compile("map(f, seq)", '', 'exec')) dis.dis(compile("[f(x) for x in seq]", '', 'exec')) dis.dis(compile("L = []\nfor x in seq: L.append(f(x))", '', 'exec')) But in fact just looking at the byte-code isn't helpful, because it tells you nothing about the relative speed of each operation. You need to actually time the operations. >>> from timeit import Timer >>> t1 = Timer("map(len, 'abcdefgh')", setup='') >>> t2 = Timer("[len(c) for c in 'abcdefgh']", setup='') >>> t3 = Timer("""L = [] ... for c in 'abcdefgh': ... L.append(len(c)) ... """, setup='') >>> >>> min(t1.repeat()) 3.9076540470123291 >>> min(t2.repeat()) 4.5931642055511475 >>> min(t3.repeat()) 7.4744069576263428 So, on my PC, with Python 2.5, with this example, a for-loop is about 60% slower than a list comp and about 90% slower than map; the list comp is about 20% slower than map. But that only holds for *that* example. Here's another one: >>> def f(x): ... return 1+2*x+3*x**2 ... >>> values = [1,2,3,4,5,6] >>> t1 = Timer("map(f, values)", setup='from __main__ import f, values') >>> t2 = Timer("[f(x) for x in values]", ... setup='from __main__ import f, values') >>> >>> t3 = Timer("""L = [] ... for x in values: ... L.append(f(x)) ... """, setup='from __main__ import f, values') >>> >>> min(t1.repeat()) 7.0339860916137695 >>> min(t2.repeat()) 6.8053178787231445 >>> min(t3.repeat()) 9.1957418918609619 For this example map and the list comp are nearly the same speed, with map slightly slower; but the for-loop is still significantly worse. Of course, none of these timing tests are terribly significant. The actual difference in time is of the order of a millionth of a second per call to map compared to the list comp or the for-loop, for these small examples. Most of the time you shouldn't care about time differences of that magnitude, and write whatever is easiest. -- Steven From tjreedy at udel.edu Sat Dec 19 03:15:06 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 19 Dec 2009 03:15:06 -0500 Subject: iterators and views of lists In-Reply-To: <7p34t6F5u7U1@mid.individual.net> References: <89604fb4-9dfa-45f1-a3df-f676cd4353ea@x5g2000prf.googlegroups.com> <87b87511-744c-450e-a024-976f8c57f032@15g2000prz.googlegroups.com> <00b47124$0$15654$c3e8da3@news.astraweb.com> <7p34t6F5u7U1@mid.individual.net> Message-ID: On 12/19/2009 12:10 AM, Gregory Ewing wrote: > Terry Reedy wrote: >> On the other hand, Python indexes are a form of random access >> iterator, the top of the hierarchy. > > The term "random access iterator" seems oxymoronic to > me. Iteration is all about operating on things in > sequence. If you're accessing elements arbitrarily, > then you're not iterating. > >> Python, traditionally, only came with one mutable builtin sequence >> type, so the sort function was made a method of that type. > > Also it probably operates rather more efficiently > than a generic one would, as it doesn't have to go > through a general mechanism to access elements, but > can take advantage of its knowledge of the internal > structure of a list. I presume there is no array sort because it is O(n) to copy array to list and back again with tolist and fromlist methods. Anyone needed space-saving of in place in array can write array sort with generic quicksort or whatever is appropriate to peculiarities of specific data. tjr From frank at chagford.com Sat Dec 19 03:38:18 2009 From: frank at chagford.com (Frank Millman) Date: Sat, 19 Dec 2009 10:38:18 +0200 Subject: Minor bug in multiprocessing? Message-ID: Hi all This is a minor issue, but I thought I would mention it. I am on Python 2.6.2. I have 'from __future__ import unicode_literals' at the top of my programs. I am experimenting with multiprocessing, and in particular subclassing the Process class. If I create a subclass and pass "name='test'" as one of the arguments, I get the following - Traceback (most recent call last): File "F:\junk\multiprocess\mp5.py", line 37, in p = Frank(name='test') File "F:\junk\multiprocess\mp5.py", line 18, in __init__ self.name = name File "C:\Python26\lib\multiprocessing\process.py", line 141, in name assert isinstance(name, str), 'name must be a string' AssertionError: name must be a string If I change the argument to "name=str('test')" there is no error. For Python 2.x I think the assertion should be "isinstance(name, basestring)" to prevent this from happening. Is this worth reporting, if it has not been reported already? Thanks Frank Millman From app at godeck.com Sat Dec 19 03:45:40 2009 From: app at godeck.com (AppRe Godeck) Date: Sat, 19 Dec 2009 02:45:40 -0600 Subject: Moving from PHP to Python. Is it Possible References: <7ole38F3qetj5U1@mid.uni-berlin.de> <4b2603bc$0$30660$426a34cc@news.free.fr> <4b26209b$0$7608$426a74cc@news.free.fr> Message-ID: On Mon, 14 Dec 2009 12:25:16 +0100, Bruno Desthuilliers wrote: > r0g a ?crit : >> Bruno Desthuilliers wrote: >>> Sancar Saran a ?crit : >>> (snip) >>>> My problem is with PHP syntax and performance. I'm just trying to >>>> replicate my recepies in python... >>> Python is not PHP, and trying to write PHP in Python won't buy you >>> much except pain and frustration. >> >> >> I think people are being a little harsh here. Replicating exactly what >> PHP code does on a micro level i.e. line by line is probably a bad idea >> but for all we know a lot of the macro level stuff might be fine, or >> mostly fine i.e. structures, algorithms, classes and functions etc. > > I was talking about trying to replicate PHP's execution model and idioms > in Python - the "framework" part -, not about application specific > algos, data structures etc. Try web2py I think you will surprise yourself with its simplicity and speed :) From gervaz at gmail.com Sat Dec 19 04:50:19 2009 From: gervaz at gmail.com (mattia) Date: 19 Dec 2009 09:50:19 GMT Subject: Sort the values of a dict References: <4b2c0386$0$1105$4fafbaef@reader4.news.tin.it> <4b2c7303@dnews.tpgi.com.au> Message-ID: <4b2ca1db$0$1117$4fafbaef@reader1.news.tin.it> Il Sat, 19 Dec 2009 17:30:27 +1100, Lie Ryan ha scritto: > On 12/19/2009 9:34 AM, mattia wrote: >> Can you provide me a much pythonic solution (with comments if possible, >> so I can actually learn something)? > > If you only need to get i'th element sometimes, sorting the dict is > fine. Otherwise, you might want to use collections.OrderedDict. Well, in the python doc OrderedDict is described as a dict that remembers the order that keys were first inserted and I don't need this. The fact is that I use a structure composed by a date and a list of possible solutions found, like (2009/12/21, (('e', 12, 33), ('r', 4, 11), ('r', 1, 33))) then every solution is inserted concurrently in a dictionary. I want to sort the solution found to provide, e.g., the first 10 dates found and the best result of every date based on the i-th element of the date's list. From care02 at gmail.com Sat Dec 19 05:05:17 2009 From: care02 at gmail.com (Carl Johan Rehn) Date: Sat, 19 Dec 2009 02:05:17 -0800 (PST) Subject: numpy performance and random numbers Message-ID: Dear friends, I plan to port a Monte Carlo engine from Matlab to Python. However, when I timed randn(N1, N2) in Python and compared it with Matlab's randn, Matlab came out as a clear winner with a speedup of 3-4 times. This was truly disappointing. I ran tthis test on a Win32 machine and without the Atlas library. Why is there such a large difference in speed and how can I improve the speed of randn in Python! Any help with this matter is truly appreciated since I really would like to get away from Matlab and move over to Python instead. Yours Carl From victorsubervi at gmail.com Sat Dec 19 05:10:00 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Sat, 19 Dec 2009 05:10:00 -0500 Subject: How Do I...? In-Reply-To: <4B2BE024.4010307@tim.thechases.com> References: <4dc0cfea0912181055o4da24927n4776b197efd5943@mail.gmail.com> <4B2BE024.4010307@tim.thechases.com> Message-ID: <4dc0cfea0912190210h3be56c85r34dbb93c672519cb@mail.gmail.com> On Fri, Dec 18, 2009 at 3:03 PM, Tim Chase wrote: > Victor Subervi wrote: > >> How do I...? >> > > Well, you start by reading a book on how to program. You would then learn > that what you want (in all likelihood) is a dictionary/map structure for > dynamically created key/value pairs. Once you have progressed from your > current apprenticeship and achieved the rank of third-degree journeyman > programmer, the ways of dynamic variable creation will avail themselves. Why the arrogance? Why talk down to me? > > As stated above, you want a dictionary where your keys are > > 'optionNo%d' % i > > and your values are "i". You can also use the more idiomatic > > for i, option in enumerate(ourOptions()): > ... > > and skip the manual initialization and incrementation of "i". Or even more > succinctly, you could pass the above as a generator to the dict() > initialization. But that's a level-2 apprentice bit of code. Patience > grasshopper. > Why the arrogance? > > And as additional weirdness, you don't actually make use of "option" in > your for-loop... > The variable was tied to another set of variables that iterated through the options. Why be so judgmental? I appreciate your advice, after having filtered out the attitude. V -------------- next part -------------- An HTML attachment was scrubbed... URL: From fabiofz at gmail.com Sat Dec 19 05:36:51 2009 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Sat, 19 Dec 2009 08:36:51 -0200 Subject: Eclipse Carriage Return Workaround In-Reply-To: References: Message-ID: On Fri, Dec 18, 2009 at 1:38 PM, Steve Holden wrote: > I've written a Python 3 course that uses an Eclipse-based teaching > system. The school is telling me that their version of Eclipse/pydev > appears to have an input() function that appends a carriage return > character to the user's input. This makes several things go screwy, as > it's definitely not the way the standalone interpreter works, even on > Windows. > > Can anyone think of a simple way work around this issue by overriding > __builtins__.input() with a function that calls input() and then returns > an rstrip()ped version of the input string? I though of setting a > PYTHONSTARTUP environment variable, but that only affects interactive > interpreter instances. In my opinion that's a python bug (because it should be able to remove the \r\n and not only \n). Anyway, Pydev also had that problem and it was fixed by having a custom sitecustomize.py: See: http://github.com/aptana/Pydev/tree/master/plugins/org.python.pydev/PySrc/pydev_sitecustomize/ It just has to added to the pythonpath before the run (and it'll remove itself and call the default later on) -- the only catch is that it has to be on a folder called "pydev_sitecustomize" -- you can probably change the code if you don't want to follow that. It'll fix input(), raw_input() and will also fix encoding problems when writing non ASCII to the console (you may set a 'PYDEV_CONSOLE_ENCODING' in the environment or let it try to find a default on) -- should be compatible with python 2 or 3. Cheers, Fabio From emekamicro at gmail.com Sat Dec 19 05:36:59 2009 From: emekamicro at gmail.com (Emeka) Date: Sat, 19 Dec 2009 10:36:59 +0000 Subject: PyArg_ParseTupleAndKeywords in Python3.1 In-Reply-To: References: <0a0b822c-8d57-4816-8563-5fd8ff39f7f1@p8g2000yqb.googlegroups.com> <83f08b89-6b61-4005-9fbd-c9a01da36654@d9g2000prh.googlegroups.com> <408e4acd-3182-4d08-bcb4-d4ff1632d9c2@l13g2000yqb.googlegroups.com> <2a0f6103-3615-4d6a-bd6c-e0bfcbf37eb6@26g2000yqo.googlegroups.com> Message-ID: <89c38c820912190236k3cbf2a69kb556e614c921dfb@mail.gmail.com> Okay if that is the case, why do we need it? By having int a = 65, b = 66 , why should we also have *kwlist[]? static PyObject* foo(PyObject *self, PyObject *args, PyObject *kwrds) { int a=65, b=66; char *kwlist[] = {"a", "b", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwrds, "|CC", kwlist, &a, &b)) return NULL; return Py_BuildValue("(CC)", a, b); } On Fri, Dec 18, 2009 at 9:31 PM, casevh wrote: > On Dec 18, 10:28 am, Joachim Dahl wrote: > > My mistake seems to be that I declared > > > > char a, b; > > > > instead of > > > > int a, b; > > > > Thank you for sorting this out. > > > > Joachim > > I think you need to initialize them, too. > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From fabiofz at gmail.com Sat Dec 19 05:39:19 2009 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Sat, 19 Dec 2009 08:39:19 -0200 Subject: Eclipse Carriage Return Workaround In-Reply-To: References: Message-ID: On Sat, Dec 19, 2009 at 8:36 AM, Fabio Zadrozny wrote: > On Fri, Dec 18, 2009 at 1:38 PM, Steve Holden wrote: >> I've written a Python 3 course that uses an Eclipse-based teaching >> system. The school is telling me that their version of Eclipse/pydev >> appears to have an input() function that appends a carriage return >> character to the user's input. This makes several things go screwy, as >> it's definitely not the way the standalone interpreter works, even on >> Windows. >> >> Can anyone think of a simple way work around this issue by overriding >> __builtins__.input() with a function that calls input() and then returns >> an rstrip()ped version of the input string? I though of setting a >> PYTHONSTARTUP environment variable, but that only affects interactive >> interpreter instances. > > In my opinion that's a python bug (because it should be able to remove > the \r\n and not only \n). > > Anyway, Pydev also had that problem and it was fixed by having a > custom sitecustomize.py: > > See: http://github.com/aptana/Pydev/tree/master/plugins/org.python.pydev/PySrc/pydev_sitecustomize/ > > It just has to added to the pythonpath before the run (and it'll > remove itself and call the default later on) -- the only catch is that > it has to be on a folder called "pydev_sitecustomize" -- you can > probably change the code if you don't want to follow that. > > It'll fix input(), raw_input() and will also fix encoding problems > when writing non ASCII to the console (you may set a > 'PYDEV_CONSOLE_ENCODING' in the environment or let it try to find a > default on) -- should be compatible with python 2 or 3. > I just noted that you said they are already using pydev -- maybe it's an old version? Or maybe you're doing a custom launcher that overrides the usual pythonpath and for some reason is not passing the pydev_sitecustomize folder? Cheers, Fabio From cjwilliams43 at gmail.com Sat Dec 19 05:50:10 2009 From: cjwilliams43 at gmail.com (Colin W.) Date: Sat, 19 Dec 2009 05:50:10 -0500 Subject: Seek support for new slice syntax PEP. In-Reply-To: References: <8e5054b1-8424-4633-a52e-1d9dcd1637b6@c34g2000yqn.googlegroups.com> <4B2B9676.4070206@gmail.com> Message-ID: On 18-Dec-09 23:16 PM, Nobody wrote: > On Fri, 18 Dec 2009 09:49:26 -0500, Colin W. wrote: > >> You don't say, but seem to imply that the slice components include None. > > That's how missing components are implemented at the language level: > > > class foo: > = def __getitem__(self, s): > = return s > = > > x = foo() > > x[::] > slice(None, None, None) > > x[1::2] > slice(1, None, 2) > > The defaults of zero, sys.maxint and one apply to built-in types, but > nothing forces user-defined types to behave this way. > > Or maybe I misunderstood your point. > No, it seems that the implementation is a little different from the doc. You are right: *** Python 2.6.4 (r264:75708, Oct 26 2009, 08:23:19) [MSC v.1500 32 bit (Intel)] on win32. *** >>> a= range(10) >>> a[2:8:2] [2, 4, 6] >>> a[2::2] [2, 4, 6, 8] >>> a[2:None:2] [2, 4, 6, 8] >>> I had expected the last to be rejected, but it fits with the overall philosophy. Colin W From gervaz at gmail.com Sat Dec 19 05:54:58 2009 From: gervaz at gmail.com (mattia) Date: 19 Dec 2009 10:54:58 GMT Subject: py itertools? Message-ID: <4b2cb101$0$1112$4fafbaef@reader1.news.tin.it> Hi all, I need to create the permutation of two strings but without repeat the values, e.g. 'ab' for me is equal to 'ba'. Here is my solution, but maybe the python library provides something better: >>> def mcd(a, b): ... if b == 0: ... return a ... else: ... return mcd(b, a % b) ... >>> def mcm(a, b): ... return int((a * b) / mcd(a, b)) ... >>> s1 = 'abc' >>> s2 = 'wt' >>> m = mcm(len(s1), len(s2)) >>> set(zip(s1*m, s2*m)) {('a', 'w'), ('a', 't'), ('b', 'w'), ('c', 't'), ('b', 't'), ('c', 'w')} Any help? Thanks, Mattia From malte.usenet at web.de Sat Dec 19 06:08:19 2009 From: malte.usenet at web.de (Malte Dik) Date: Sat, 19 Dec 2009 12:08:19 +0100 Subject: comparing dialects of csv-module Message-ID: <7p3q78F8o2U1@mid.dfncis.de> Hi out there! I want to put some intelligence into a csv reading script and in order to do so I want to compare possible different dialects I collect with some random d = csv.Sniffer().sniff("1,2,3,4"), because the csv is kinda dirty. Now sniff() returns a class object and those aren't comparable in the "if dialect_1 == dialect_2: count something" sense. Has anyone around here already dealt with this kind of problem and maybe even a solution I could utilize? That would be great. If not - I guess I would just write a quick function comparing the attributes of those dialects ... - but just out of educational curiosity: Would it be the right way to implement an __eq__(...) function into the Dialect class or how would someone who would want to make it right do it? Sincerest greetings, Malte From bdesth.quelquechose at free.quelquepart.fr Sat Dec 19 06:15:33 2009 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 19 Dec 2009 12:15:33 +0100 Subject: Using ZODB (or something else) for storing lots of metadata about RSS/Atom feeds and posts In-Reply-To: References: Message-ID: <4b2cc360$0$28468$426a74cc@news.free.fr> Thomas Doggette a ?crit : > I'm working on (or rather, at this point, planning) a project that > will involve keeping track of every post in a large number of Atom > feeds, as well as a lot of metadata about how posts are linked and how > users interact with them. > > The idea of having all of these be persistent objects is very > appealing, but I'm not sure the ZODB is ideal for what I'm doing. Can > people with more experience working with data sets like this give me > some advice on what they've had luck using? My own experience with the ZODB for large number of small objects, lot of metadata and indexes, frequent updates, and querying the whole thing, has been at least very disappointing. RDBMS are possibly not the perfect solution for each and any kind of problem datastructures, but unless you have to deal with complex heterogenous trees or graphs, they sure are a safe bet for most data storage, retrieval and analysis jobs. Also, I don't have ant experience with Google's AppEngine's datastore nor Apache CouchDB, but given the description of your project they might be appropriate solutions. My 2 cents. From steve at REMOVE-THIS-cybersource.com.au Sat Dec 19 06:29:18 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 19 Dec 2009 11:29:18 GMT Subject: numpy performance and random numbers References: Message-ID: <00b63dbe$0$15654$c3e8da3@news.astraweb.com> On Sat, 19 Dec 2009 02:05:17 -0800, Carl Johan Rehn wrote: > Dear friends, > > I plan to port a Monte Carlo engine from Matlab to Python. However, when > I timed randn(N1, N2) in Python and compared it with Matlab's randn, What's randn? I don't know that function. I know the randint, random, and randrange functions, but not randn. Where does it come from? > Matlab came out as a clear winner with a speedup of 3-4 times. This was > truly disappointing. I ran tthis test on a Win32 machine and without the > Atlas library. > > Why is there such a large difference in speed and how can I improve the > speed of randn in Python! Any help with this matter is truly appreciated > since I really would like to get away from Matlab and move over to > Python instead. Could be many reasons. Python could be generally slower than Matlab. Your timing code might have been faulty and you weren't comparing equal amounts of work (if your Python code was doing four times as much work as the Matlab code, then naturally it will be four times slower). Perhaps the Matlab random number generator is a low-quality generator which is fast but not very random. Python uses a very high quality RNG which is not cheap. But does it really matter if the RNG is slower? Your Monte Carlo engine is a lot more than just a RNG. What matters is whether the engine as a whole is faster or slower, not whether one small component is slower. -- Steven From emekamicro at gmail.com Sat Dec 19 06:56:25 2009 From: emekamicro at gmail.com (Emeka) Date: Sat, 19 Dec 2009 11:56:25 +0000 Subject: Creating Classes In-Reply-To: <4B2C510D.80102@ieee.org> References: <26848375.post@talk.nabble.com> <4B2C510D.80102@ieee.org> Message-ID: <89c38c820912190356n27e7fd0bybbcacbbd0c7b17aa@mail.gmail.com> Hello Dave > > There are more complex things that can go on, like creating "bound" > function objects, but I think this should get you pretty far. > > Could explain the complex things for me? Regards, Janus -------------- next part -------------- An HTML attachment was scrubbed... URL: From kevin.p.dwyer at gmail.com Sat Dec 19 07:19:23 2009 From: kevin.p.dwyer at gmail.com (Kev Dwyer) Date: Sat, 19 Dec 2009 12:19:23 +0000 (UTC) Subject: Help with invoking standard mail app in windows References: <4B2BC252.3060509@al.com.au> <4B2BD9C0.7070509@al.com.au> Message-ID: On Sat, 19 Dec 2009 06:36:32 +1100, Astan Chee wrote: > Kev Dwyer wrote: >> Hello Astan, >> >> Your code executes without error for me on Win98 (!) with Python 2.5 or >> XP with Python 2.6. >> >> It would help people to help you if you could provide the *exact* >> console output from when you try to execute the code, *including* the >> traceback. That way we can work out which line of code is hitting the >> exception. >> >> Cheers, >> >> Kev >> >> > Hi, > My mistake. The length of body is over 1400 characters. Here is my > updated code and result: > > import urllib, webbrowser, win32api > def mailto_url(to=None,subject=None,body=None,cc=None): > """ > encodes the content as a mailto link as described on > http://www.faqs.org/rfcs/rfc2368.html """ url = "mailto: " + > urllib.quote(to.strip(),"@,") sep = "?" > if cc: > url+= sep + "cc=" + urllib.quote(cc,"@,") sep = "&" > if subject: > url+= sep + "subject=" + urllib.quote(subject,"") sep = "&" > if body: > # Also note that line breaks in the body of a message MUST be # > encoded with "%0D%0A". (RFC 2368) > body="\r\n".join(body.splitlines()) > url+= sep + "body=" + urllib.quote(body,"") sep = "&" > return url > > txtTo = "test at com.com" > txtSubject = "Test Subject" > body = "Test body" > for t in range(278): > body+="test " > txtCC = "cc_test at com.com" > > url = mailto_url(txtTo,txtSubject,body,txtCC) > #win32api.ShellExecute(0,'open',url,None,None,0) > webbrowser.open(url,new=1) > # os.startfile(url) > > result: > > Traceback (most recent call last): > File "C:/stanc_home/python/mail_test.py", line 32, in > webbrowser.open(url,new=1) > File "C:\Python25\lib\webbrowser.py", line 61, in open > if browser.open(url, new, autoraise): > File "C:\Python25\lib\webbrowser.py", line 518, in open > os.startfile(url) > WindowsError: [Error 5] Access is denied: 'mailto: > test at com.com?cc=cc_test at com.com&subject=Test%20Subject&body=Test% > > Is there some sort of limitation here? If I shorten the string, it works > fine. You're right, but I'm wondering if there is a way to go around > this limitation. > Thanks again > Cheers > Astan Hello Astan, After a bit of experimentation I find I get the same problem on XP using 2.6 for len(body) > 1973, using the os.startfile method. Some light googling suggests this is probably a limit within Outlook itself. If you just want a way to start Outlook programmatically you may be able to work around this by automating Outlook - try googling python outlook automation. If you want to start a default mail client on any machine using the mailto protocol then you'll have to limit the size of your message bodies. You may find that other mail clients have limits too - I doubt that any client (or browser) will accept urls of unlimited size. Cheers, Kev From clp2 at rebertia.com Sat Dec 19 07:48:22 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Sat, 19 Dec 2009 04:48:22 -0800 Subject: py itertools? In-Reply-To: <4b2cb101$0$1112$4fafbaef@reader1.news.tin.it> References: <4b2cb101$0$1112$4fafbaef@reader1.news.tin.it> Message-ID: <50697b2c0912190448y3aac772dt31faf1eafe8ad755@mail.gmail.com> On Sat, Dec 19, 2009 at 2:54 AM, mattia wrote: > Hi all, I need to create the permutation of two strings but without > repeat the values, e.g. 'ab' for me is equal to 'ba'. Here is my > solution, but maybe the python library provides something better: > >>>> def mcd(a, b): > ... ? ? if b == 0: > ... ? ? ? ? return a > ... ? ? else: > ... ? ? ? ? return mcd(b, a % b) > ... >>>> def mcm(a, b): > ... ? ? return int((a * b) / mcd(a, b)) > ... >>>> s1 = 'abc' >>>> s2 = 'wt' >>>> m = mcm(len(s1), len(s2)) >>>> set(zip(s1*m, s2*m)) > {('a', 'w'), ('a', 't'), ('b', 'w'), ('c', 't'), ('b', 't'), ('c', 'w')} > > Any help? Surprised you didn't think of the seemingly obvious approach: def permute_chars(one, two): for left in set(one): for right in set(two): yield (left, right) >>> list(permute_chars('abc', 'wt')) [('a', 'w'), ('a', 't'), ('b', 'w'), ('b', 't'), ('c', 'w'), ('c', 't')] Cheers, Chris -- http://blog.rebertia.com From care02 at gmail.com Sat Dec 19 08:06:53 2009 From: care02 at gmail.com (Carl Johan Rehn) Date: Sat, 19 Dec 2009 05:06:53 -0800 (PST) Subject: numpy performance and random numbers References: <00b63dbe$0$15654$c3e8da3@news.astraweb.com> Message-ID: On Dec 19, 12:29?pm, Steven D'Aprano wrote: > On Sat, 19 Dec 2009 02:05:17 -0800, Carl Johan Rehn wrote: > > Dear friends, > > > I plan to port a Monte Carlo engine from Matlab to Python. However, when > > I timed randn(N1, N2) in Python and compared it with Matlab's randn, > > What's randn? I don't know that function. I know the randint, random, and > randrange functions, but not randn. Where does it come from? > > > Matlab came out as a clear winner with a speedup of 3-4 times. This was > > truly disappointing. I ran tthis test on a Win32 machine and without the > > Atlas library. > > > Why is there such a large difference in speed and how can I improve the > > speed of randn in Python! Any help with this matter is truly appreciated > > since I really would like to get away from Matlab and move over to > > Python instead. > > Could be many reasons. Python could be generally slower than Matlab. Your > timing code might have been faulty and you weren't comparing equal > amounts of work (if your Python code was doing four times as much work as > the Matlab code, then naturally it will be four times slower). Perhaps > the Matlab random number generator is a low-quality generator which is > fast but not very random. Python uses a very high quality RNG which is > not cheap. > > But does it really matter if the RNG is slower? Your Monte Carlo engine > is a lot more than just a RNG. What matters is whether the engine as a > whole is faster or slower, not whether one small component is slower. > > -- > Steven randn is given by >> import numpy >>> numpy.random.randn(2,3) array([[-2.66435181, -0.32486419, 0.12742156], [-0.2387061 , -0.55894044, 1.20750493]]) Generally, at least in my MC application, I need a large number of random numbers. Usually I execute, for example, r = randn(100, 10000) sequentially a relatively large number of times until sufficient accuracy has been reached. Thus, randn is in my case a mission critical component for obtaining an acceptable overall run time. Matlab and numpy have (by chance?) the exact names for the same functionality, so I was very happy with numpy's implementation until I timed it. So the basioc question is, how can I speed up random number generation? Carl From sturlamolden at yahoo.no Sat Dec 19 08:49:17 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Sat, 19 Dec 2009 05:49:17 -0800 (PST) Subject: numpy performance and random numbers References: Message-ID: <89e91529-3488-4162-a2ca-d18e3f0b891e@o28g2000yqh.googlegroups.com> On 19 Des, 11:05, Carl Johan Rehn wrote: > I plan to port a Monte Carlo engine from Matlab to Python. However, > when I timed randn(N1, N2) in Python and compared it with Matlab's > randn, Matlab came out as a clear winner with a speedup of 3-4 times. > This was truly disappointing. I ran tthis test on a Win32 machine and > without the Atlas library. This is due to the algorithm. Matlab is using Marsaglia's ziggurat method. Is is the fastest there is for normal and gamma random variates. NumPy uses the Mersenne Twister to produce uniform random deviates, and then applies trancendental functions to transform to the normal distribution. Marsaglia's C code for ziggurat is freely available, so you can compile it yourself and call from ctypes, Cython or f2py. The PRNG does not use BLAS/ATLAS. From sturlamolden at yahoo.no Sat Dec 19 08:53:52 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Sat, 19 Dec 2009 05:53:52 -0800 (PST) Subject: numpy performance and random numbers References: <00b63dbe$0$15654$c3e8da3@news.astraweb.com> Message-ID: On 19 Des, 12:29, Steven D'Aprano wrote: > Perhaps > the Matlab random number generator is a low-quality generator which is > fast but not very random. Python uses a very high quality RNG which is > not cheap. Marsaglia and Matlab's implementation of ziggurat uses a slightly lower quality RNG for uniform deviates than NumPy's Mersenne Twister. But the real speed advantage comes from avoiding trancendental functions. I have for some time thought of contributing a ziggurat generator to NumPy, while retaining the Mersenne Twister internally, but I have not got around to do it. From __peter__ at web.de Sat Dec 19 09:06:58 2009 From: __peter__ at web.de (Peter Otten) Date: Sat, 19 Dec 2009 15:06:58 +0100 Subject: comparing dialects of csv-module References: <7p3q78F8o2U1@mid.dfncis.de> Message-ID: Malte Dik wrote: > Hi out there! > > I want to put some intelligence into a csv reading script and in order to > do so I want to compare possible different dialects I collect with some > random > > d = csv.Sniffer().sniff("1,2,3,4"), > > because the csv is kinda dirty. > > Now sniff() returns a class object and those aren't comparable in the "if > dialect_1 == dialect_2: count something" sense. > > Has anyone around here already dealt with this kind of problem and maybe > even a solution I could utilize? That would be great. An implementation for the lazy >>> import csv >>> d = csv.Sniffer().sniff("1,2,3") >>> def eq(a, b, attributes=[name for name in dir(d) if not name.startswith("_")]): ... return all(getattr(a, n, None) == getattr(b, n, None) for n in attributes) ... >>> eq(d, csv.Sniffer().sniff("3,4,5")) True >>> eq(d, csv.Sniffer().sniff("'3','4','5'")) False >>> eq(d, csv.Sniffer().sniff("3;4;5")) False >>> eq(d, csv.Sniffer().sniff("3,4,' 5'")) True > If not - I guess I would just write a quick function comparing the > attributes of those dialects ... - but just out of educational curiosity: > Would it be the right way to implement an __eq__(...) function into the > Dialect class or how would someone who would want to make it right do it? I don't know if you can do it for classic classes; for newstyle classes you'd have to reimplement comparison in the metaclass: >>> class Dialect: ... class __metaclass__(type): ... def __eq__(self, other): ... return self._key() == other._key() ... def __ne__(self, other): ... return self._key() != other._key() ... def _key(self): ... return self.quotechar, self.delimiter #,... ... >>> class A(Dialect): ... quotechar = "'" ... delimiter = ":" ... >>> class B(Dialect): ... quotechar = "'" ... delimiter = "," ... >>> A == B False >>> B.delimiter = ":" >>> A == B True On a side note, I think it's a C++ism that dialects are classes rather than class instances. That's a superfluous complication since in Python no work will be moved from compile time to runtime anyway. Peter From sturlamolden at yahoo.no Sat Dec 19 09:16:16 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Sat, 19 Dec 2009 06:16:16 -0800 (PST) Subject: numpy performance and random numbers References: <00b63dbe$0$15654$c3e8da3@news.astraweb.com> Message-ID: On 19 Des, 14:06, Carl Johan Rehn wrote: > Matlab and numpy have (by chance?) the exact names for the same > functionality, Common ancenstry, NumPy and Matlab borrowed the name from IDL. LabView, Octave and SciLab uses the name randn as well. > So the basioc question is, how can I speed up random number > generation? The obvious thing would be to compile ziggurat yourself, and turn on optimization flags for your hardware. http://www.jstatsoft.org/v05/i08/ P.S. Be careful if you consider using more than one processor. Multithreading is a very difficult issue with PRNGs, becuase it is difficult to guarrantee they are truely independent. But you can use a producer-consumer pattern, though: one thread constantly producing random numbers (writing into a buffer or pipe) and another thread(s) consuming them. From sturlamolden at yahoo.no Sat Dec 19 09:18:57 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Sat, 19 Dec 2009 06:18:57 -0800 (PST) Subject: shouldn't list comprehension be faster than for loops? References: <979c8ffe-dc39-4b2b-ab9b-12ecefc12d7a@y24g2000yqb.googlegroups.com> <8808c896-0bb9-42e0-aa61-319adadf31d1@b2g2000yqi.googlegroups.com> Message-ID: <470880cd-6b92-4ceb-90ac-2a45e7e9984e@21g2000yqj.googlegroups.com> On 19 Des, 02:28, Ryan Kelly wrote: > Not so. ?If you use the "dis" module to peek at the bytecode generated > for a list comprehension, you'll see it's very similar to that generated > for an explicit for-loop. ?The byte-code for a call to map is very > different. First, you failed to realize that the bytecode is different because map is doing the work in C. Second, you did not provide bytecode for the for-loop. From lie.1296 at gmail.com Sat Dec 19 09:52:17 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Sun, 20 Dec 2009 01:52:17 +1100 Subject: py itertools? In-Reply-To: References: <4b2cb101$0$1112$4fafbaef@reader1.news.tin.it> Message-ID: <4b2ce8a1$1@dnews.tpgi.com.au> On 12/19/2009 11:48 PM, Chris Rebert wrote: > > Surprised you didn't think of the seemingly obvious approach: > > def permute_chars(one, two): > for left in set(one): > for right in set(two): > yield (left, right) > >>>> list(permute_chars('abc', 'wt')) > [('a', 'w'), ('a', 't'), ('b', 'w'), ('b', 't'), ('c', 'w'), ('c', 't')] > even less work: import itertools print set(itertools.product('abc', 'wt')) but neither of those two solves the OP's problem. And neither the OP's own solution solves his own problem (per my understanding from his description). what he wanted was something like: print set(tuple(sorted(x)) for x in itertools.product(s1, s2)) or, just for some functional fun, when written in point-free form: from itertools import product from functools import partial def compose(f, g): return lambda *a, **k: f(g(*a, **k)) sortedtuple = compose(tuple, sorted) setcomp = compose(set, map) unique_tuples = partial(setcomp, sortedtuple) permute_chars = compose(unique_tuples, product) print permute_chars(s1, s2) From malte.usenet at web.de Sat Dec 19 10:12:22 2009 From: malte.usenet at web.de (Malte Dik) Date: Sat, 19 Dec 2009 16:12:22 +0100 Subject: comparing dialects of csv-module References: <7p3q78F8o2U1@mid.dfncis.de> Message-ID: <7p48gqFntlU1@mid.dfncis.de> quote: > An implementation for the lazy > >>>> import csv >>>> d = csv.Sniffer().sniff("1,2,3") >>>> def eq(a, b, attributes=[name for name in dir(d) if not > name.startswith("_")]): > ... return all(getattr(a, n, None) == getattr(b, n, None) for n in > attributes) > ... Wow, this is awesome. I'd never come up with something like this. Will digg into it deeper as I implement it (code snippets like this need to melt in order to effuse all their flavor ;), but want to thank you very much in the first place! :) Have a nice day everyone, Malte From care02 at gmail.com Sat Dec 19 10:14:16 2009 From: care02 at gmail.com (Carl Johan Rehn) Date: Sat, 19 Dec 2009 07:14:16 -0800 (PST) Subject: numpy performance and random numbers References: <89e91529-3488-4162-a2ca-d18e3f0b891e@o28g2000yqh.googlegroups.com> Message-ID: <81c16ac3-110e-412d-8f69-e053303803ff@d10g2000yqh.googlegroups.com> On Dec 19, 2:49?pm, sturlamolden wrote: > On 19 Des, 11:05, Carl Johan Rehn wrote: > > > I plan to port a Monte Carlo engine from Matlab to Python. However, > > when I timed randn(N1, N2) in Python and compared it with Matlab's > > randn, Matlab came out as a clear winner with a speedup of 3-4 times. > > This was truly disappointing. I ran tthis test on a Win32 machine and > > without the Atlas library. > > This is due to the algorithm. Matlab is using Marsaglia's ziggurat > method. Is is the fastest there is for normal and gamma random > variates. NumPy uses the Mersenne Twister to produce uniform random > deviates, and then applies trancendental functions to transform to the > normal distribution. Marsaglia's C code for ziggurat is freely > available, so you can compile it yourself and call from ctypes, Cython > or f2py. > > The PRNG does not use BLAS/ATLAS. Thank you, this was very informative. I know about the Mersenne Twister, but had no idea about Marsaglia's ziggurat method. I will definitely try f2py or cython. Well, I guess I knew that random numbers were not handled by BLAS/ ATLAS, but wasn't 100% sure. Carl From care02 at gmail.com Sat Dec 19 10:20:10 2009 From: care02 at gmail.com (Carl Johan Rehn) Date: Sat, 19 Dec 2009 07:20:10 -0800 (PST) Subject: numpy performance and random numbers References: <00b63dbe$0$15654$c3e8da3@news.astraweb.com> Message-ID: On Dec 19, 3:16?pm, sturlamolden wrote: > On 19 Des, 14:06, Carl Johan Rehn wrote: > > > Matlab and numpy have (by chance?) the exact names for the same > > functionality, > > Common ancenstry, NumPy and Matlab borrowed the name from IDL. > > LabView, Octave and SciLab uses the name randn as well. > > > So the basioc question is, how can I speed up random number > > generation? > > The obvious thing would be to compile ziggurat yourself, and turn on > optimization flags for your hardware.http://www.jstatsoft.org/v05/i08/ > > P.S. Be careful if you consider using more than one processor. > Multithreading is a very difficult issue with PRNGs, becuase it is > difficult to guarrantee they are truely independent. But you can use a > producer-consumer pattern, though: one thread constantly producing > random numbers (writing into a buffer or pipe) and another thread(s) > consuming them. How about mulit-core or (perhaps more exciting) GPU and CUDA? I must admit that I am extremely interested in trying the CUDA-alternative. Obviously, cuBLAS is not an option here, so what is the safest route for a novice parallel-programmer? Carl Carl From steve at REMOVE-THIS-cybersource.com.au Sat Dec 19 10:22:45 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 19 Dec 2009 15:22:45 GMT Subject: numpy performance and random numbers References: <00b63dbe$0$15654$c3e8da3@news.astraweb.com> Message-ID: <00b67476$0$15654$c3e8da3@news.astraweb.com> On Sat, 19 Dec 2009 05:06:53 -0800, Carl Johan Rehn wrote: > so I was very happy with numpy's implementation until I timed it. How did you time it? -- Steven From python.list at tim.thechases.com Sat Dec 19 10:22:46 2009 From: python.list at tim.thechases.com (Tim Chase) Date: Sat, 19 Dec 2009 09:22:46 -0600 Subject: How Do I...? In-Reply-To: <4dc0cfea0912190210h3be56c85r34dbb93c672519cb@mail.gmail.com> References: <4dc0cfea0912181055o4da24927n4776b197efd5943@mail.gmail.com> <4B2BE024.4010307@tim.thechases.com> <4dc0cfea0912190210h3be56c85r34dbb93c672519cb@mail.gmail.com> Message-ID: <4B2CEFC6.8000801@tim.thechases.com> Victor Subervi wrote: > On Fri, Dec 18, 2009 at 3:03 PM, Tim Chase wrote: >> Well, you start by reading a book on how to program. You would then learn >> that what you want (in all likelihood) is a dictionary/map structure for >> dynamically created key/value pairs. Once you have progressed from your >> current apprenticeship and achieved the rank of third-degree journeyman >> programmer, the ways of dynamic variable creation will avail themselves. > > Why the arrogance? Why talk down to me? The aim was not arrogance, but expression of exasperation at your "using c.l.p to write my code and interpret my error messages" programming style that seems to indicate that you don't understand how to use tools like your editor, traceback messages, & google; or that you've not invested the time to learn programming concepts such as when to use dictionaries/maps, HTML, HTTP/server stuff, SMTP/email stuff, or research hosting provider information. Let's take a tour back through some of your previous posts to the list to see why the exasperation: Just in my readily-available offline archives, I count at least 4 off-topic (non-Python) posts, three of which you KNEW were OT because you put "OT" in the subject[1]. The 4th[2] is just a google-search away. Any basic HTML tutorial on using form elements would show you how to do this. And on the topic of googling for answers you had questions about good mailers[3], a quick search for "python send mail" turns up a multitude of built-in and code-copyable solutions. You don't seem to learn from previous answers[4] where the solution in the first response was "make sure you're not masking the built-in module with a same-named file in your project directory", only to have the same issue in the 2nd email. While it's somewhat forgivable as I too have accidentally masked my ability to send email by having an "email" module in the local directory, I learned to google the traceback's core message "ImportError: No module named base64MIME" which gave me the answer. You don't seem to read tracebacks[5]. When you do get tracebacks that you don't understand, many of your initial posts either post them in some funky line-numbered format[6] that makes them hard to read (though can be helpful, so this isn't as grievous)), or you simply omit the traceback completely[7]. Even if asked explicitly for them[8]. They contain valuable information. Your omission of them frustrates anybody trying to help. There's the omission of key information[9] or improperly hand-transcribing code instead of copy-and-pasting the actual code. And that doesn't even touch on the issues of repeated top-posting which is just annoying. Folks have been pretty lax, giving you subtle "changed to inline format to make it easier to follow", but you don't seem to pick up on the suggestion. I'll make it explicit: post replies inline for best results. You'll find that comp.lang.python is a generally friendly place, but HELP US HELP YOU. Try doing your own research first, reading error messages, giving us the tools we need to help you, and adhering to conventions like inline posting. I'm glad if my underlying suggestion of using a dict helped you reach a solution, but would be far more glad if you'd take this message to heart -- not as an enumeration transgressions, but as a way you can better ingratiate yourself with the list. -tkc [1] OT Virtual Server Host (OT) Recommend FTP Client (OT) Where Are Cookies Stored [2] Workaround to Add values to TextArea [3] A Good Mailer [4] Can't Find Module Python Will Not Send Email!! [5] Switching Databases [6] Problem w/ smtplib [7] Calendar Problem Calendar Stuff ...and others [8] Switching Databases [9] Nested Dicts Calendar Stuff From sturlamolden at yahoo.no Sat Dec 19 10:47:48 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Sat, 19 Dec 2009 07:47:48 -0800 (PST) Subject: numpy performance and random numbers References: <00b63dbe$0$15654$c3e8da3@news.astraweb.com> Message-ID: On 19 Des, 16:20, Carl Johan Rehn wrote: > How about mulit-core or (perhaps more exciting) GPU and CUDA? I must > admit that I am extremely interested in trying the CUDA-alternative. > > Obviously, cuBLAS is not an option here, so what is the safest route > for a novice parallel-programmer? The problem with PRNG is that they are iterative in nature, and maintain global states. They are therefore very hard to vectorize. A GPU will not help. The GPU has hundreds of computational cores that can run kernels, but you only get to utilize one. Parallel PRNGs are an unsolved problem in computer science. From davea at ieee.org Sat Dec 19 10:53:10 2009 From: davea at ieee.org (Dave Angel) Date: Sat, 19 Dec 2009 10:53:10 -0500 Subject: Seek support for new slice syntax PEP. In-Reply-To: References: <8e5054b1-8424-4633-a52e-1d9dcd1637b6@c34g2000yqn.googlegroups.com> <4B2B9676.4070206@gmail.com> Message-ID: <4B2CF6E6.6050700@ieee.org> Colin W. wrote: >
        On > 18-Dec-09 23:16 PM, Nobody wrote: >> On Fri, 18 Dec 2009 09:49:26 -0500, Colin W. wrote: >> >>> You don't say, but seem to imply that the slice components include >>> None. >> >> That's how missing components are implemented at the language level: >> >> > class foo: >> = def __getitem__(self, s): >> = return s >> = >> > x = foo() >> > x[::] >> slice(None, None, None) >> > x[1::2] >> slice(1, None, 2) >> >> The defaults of zero, sys.maxint and one apply to built-in types, but >> nothing forces user-defined types to behave this way. >> >> Or maybe I misunderstood your point. >> > No, it seems that the implementation is a little different from the doc. > > You are right: > *** Python 2.6.4 (r264:75708, Oct 26 2009, 08:23:19) [MSC v.1500 32 > bit (Intel)] on win32. *** > >>> a= range(10) > >>> a[2:8:2] > [2, 4, 6] > >>> a[2::2] > [2, 4, 6, 8] > >>> a[2:None:2] > [2, 4, 6, 8] > >>> > I had expected the last to be rejected, but it fits with the overall > philosophy. > > Colin W > >
        > None is perfectly valid as a parameter to a slice. To quote the 2.6.4 docs, in section 6.6: The slice of /s/ from /i/ to /j/ with step /k/ is defined as the sequence of items with index x = i + n*k such that 0 <= n < (j-i)/k. In other words, the indices are i, i+k, i+2*k, i+3*k and so on, stopping when /j/ is reached (but never including /j/). If /i/ or /j/ is greater than len(s), use len(s). If /i/ or /j/ are omitted or None, they become ?end? values (which end depends on the sign of /k/). Note, /k/ cannot be zero. If /k/ is None, it is treated like 1. DaveA From gervaz at gmail.com Sat Dec 19 11:07:52 2009 From: gervaz at gmail.com (mattia) Date: 19 Dec 2009 16:07:52 GMT Subject: py itertools? References: <4b2cb101$0$1112$4fafbaef@reader1.news.tin.it> Message-ID: <4b2cfa58$0$1101$4fafbaef@reader3.news.tin.it> Il Sat, 19 Dec 2009 10:54:58 +0000, mattia ha scritto: > Hi all, I need to create the permutation of two strings but without > repeat the values, e.g. 'ab' for me is equal to 'ba'. Here is my > solution, but maybe the python library provides something better: > >>>> def mcd(a, b): > ... if b == 0: > ... return a > ... else: > ... return mcd(b, a % b) > ... >>>> def mcm(a, b): > ... return int((a * b) / mcd(a, b)) ... >>>> s1 = 'abc' >>>> s2 = 'wt' >>>> m = mcm(len(s1), len(s2)) >>>> set(zip(s1*m, s2*m)) > {('a', 'w'), ('a', 't'), ('b', 'w'), ('c', 't'), ('b', 't'), ('c', 'w')} > > Any help? > > Thanks, Mattia Well, this is the code I'm using: import itertools def cheapest_travel(l): """Given a list of departure and return dates, return the cheapest solution""" s = set(itertools.permute(l[0], l[1])) return sorted(t, key = lambda s: s[0][2] + s[1][2]) # example using a dict d = { '2009/12/21' : [[('d', 1, 2), ('d', 3, 4), ('d', 2, 3)], [('r', 3, 5), ('r', 3, 8)]], '2009/12/19' : [[('d', 1, 2), ('d', 2, 3)], [('r', 1, 4), ('r', 6, 4), ('r', 3, 5), ('r', 3, 8)]], '2009/12/23' : [[('d', 2, 5), ('d', 2, 4)], [('r', 4, 5)]], '2009/12/26' : [[('d', 2, 5), ('d', 1, 4)], [('r', 3, 6)]], '2009/12/28' : [[('d', 2, 5)], [('r', 4, 4)]] } for k, v in d.items(): print(k) res = cheapest_travel(v) for x in res: print(x[0], "-->", x[1], "cost", x[0][2] + x[1][2], "EUR") From stef.mientki at gmail.com Sat Dec 19 11:50:25 2009 From: stef.mientki at gmail.com (Stef Mientki) Date: Sat, 19 Dec 2009 17:50:25 +0100 Subject: how do I set a Python installation as the default under windows ? Message-ID: <4B2D0451.9080000@gmail.com> hello, I just upgraded from Python 2.5 to 2.6. Most of the things work, but I'm struggling with one issue, when I start Python in a command window, it still uses Python 2.5. Is there a way to get Python 2.6 as my default Python environment ? thanks, Stef Mientki From victorsubervi at gmail.com Sat Dec 19 11:50:29 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Sat, 19 Dec 2009 11:50:29 -0500 Subject: How Do I...? In-Reply-To: <4B2CEFC6.8000801@tim.thechases.com> References: <4dc0cfea0912181055o4da24927n4776b197efd5943@mail.gmail.com> <4B2BE024.4010307@tim.thechases.com> <4dc0cfea0912190210h3be56c85r34dbb93c672519cb@mail.gmail.com> <4B2CEFC6.8000801@tim.thechases.com> Message-ID: <4dc0cfea0912190850kec7b3a2ice9cac3356cc221a@mail.gmail.com> On Sat, Dec 19, 2009 at 10:22 AM, Tim Chase wrote: > Victor Subervi wrote: > >> On Fri, Dec 18, 2009 at 3:03 PM, Tim Chase > >wrote: >> >> Well, you start by reading a book on how to program. You would then >>> learn >>> that what you want (in all likelihood) is a dictionary/map structure for >>> dynamically created key/value pairs. Once you have progressed from your >>> current apprenticeship and achieved the rank of third-degree journeyman >>> programmer, the ways of dynamic variable creation will avail themselves. >>> >> >> Why the arrogance? Why talk down to me? >> > > The aim was not arrogance, but expression of exasperation Exasperation is what triggers your arrogance. Learn to control it. "Walk a mile in my mocassins." You can't do it. I'm an artist. I think out of my right hemisphere, not my left like you. You couldn't possibly understand. Yes, sometimes I chide myself for the questions I ask when I see the answers come back. The problem is that I quite literally can't think like you. I have to force myself to do it every time. To you it's as natural as breathing, which is why you can't relate. Thank you for your help anyway. Thank you for your patience. Please try to understand. It starts by understanding you can't understand. You have my continued promise that I will do all I can to edit my questions as intelligently as you would before I post them. Trust me, I don't like looking foolish, and I know I do. You should recognize that that alone is chiding enough. It doesn't stop me, however, for continuing to program. The whole universe is a program. I program to understand it in a way you couldn't even begin to grasp. BTW, although I know full well about dictionaries, I didn't know one could use them like you indicated, nor would I have known how to google it. I did try googling, FYI. V -------------- next part -------------- An HTML attachment was scrubbed... URL: From care02 at gmail.com Sat Dec 19 12:02:38 2009 From: care02 at gmail.com (Carl Johan Rehn) Date: Sat, 19 Dec 2009 09:02:38 -0800 (PST) Subject: numpy performance and random numbers References: <00b63dbe$0$15654$c3e8da3@news.astraweb.com> Message-ID: <69df23c3-ee4e-4c8f-9d66-581e3e272fad@m38g2000yqd.googlegroups.com> On Dec 19, 4:47?pm, sturlamolden wrote: > On 19 Des, 16:20, Carl Johan Rehn wrote: > > > How about mulit-core or (perhaps more exciting) GPU and CUDA? I must > > admit that I am extremely interested in trying the CUDA-alternative. > > > Obviously, cuBLAS is not an option here, so what is the safest route > > for a novice parallel-programmer? > > The problem with PRNG is that they are iterative in nature, and > maintain global states. They are therefore very hard to vectorize. A > GPU will not help. The GPU has hundreds of computational cores that > can run kernels, but you only get to utilize one. > > Parallel PRNGs are an unsolved problem in computer science. >>>How did you time it? Well, in Matlab I used "tic; for i = 1:1000, randn(100, 10000), end; toc" and in IPython i used a similar construct but with "time" instead of tic/(toc. >>> Parallel PRNGs are an unsolved problem in computer science. Thanks again for sharing your knowledge. I had no idea. This means that if I want to speed up my application I have to go for the fastest random generator and focus on other parts of my code that can be vectorized. Carl From anh.hai.trinh at gmail.com Sat Dec 19 12:04:25 2009 From: anh.hai.trinh at gmail.com (Anh Hai Trinh) Date: Sat, 19 Dec 2009 09:04:25 -0800 (PST) Subject: iterators and views of lists References: <89604fb4-9dfa-45f1-a3df-f676cd4353ea@x5g2000prf.googlegroups.com> <87b87511-744c-450e-a024-976f8c57f032@15g2000prz.googlegroups.com> <7a50d745-34e7-4445-ba49-5d8d815ac2ba@l13g2000yqb.googlegroups.com> Message-ID: <8f588225-b78b-4380-b314-cdb2a8c70131@a10g2000pre.googlegroups.com> On Dec 19, 5:47?am, Bearophile wrote: > It seems you have missed my post, so here it is, more explicitly: > > http://www.boostcon.com/site-media/var/sphene/sphwiki/attachment/2009... Interestingly, my `listagent` can be used as a lazy iterator and thus using itertools we can compose them just like Andrei's `range`. the stage: x = range(0, 20, 2); x [0, 2, 4, 6, 8, 10, 12, 14, 16, 18] y = range(10, 20); y [10, 11, 12, 13, 14, 15, 16, 17, 18, 19] z = [996, 758, 670, 236, 898, 337, 442, 452, 490, 547] from listagent import listagent import itertools chain: sorted(itertools.chain(listagent(x)[::2], listagent(y)[-1:1:-2])) [0, 4, 8, 12, 13, 15, 16, 17, 19] zip: sorted(itertools.izip(listagent(z)[1::3], listagent(x)[2::3])) [(452, 16), (758, 4), (898, 10)] stride: slicing an agent returns another one, those lazy agents! python -m timeit -s'from listagent import listagent' 'list(listagent (range(1000000))[1:-1:5][::7][10000:-10000:42])' 10 loops, best of 3: 55.5 msec per loop python -m timeit 'range(1000000)[1:-1:5][::7][10000:-10000:42]' 10 loops, best of 3: 280 msec per loop radial: not implemented `listagent` is implemented in pure Python, of course. If implemented in C, there is surprisingly little difference between a slicing `agent` like this, or a listiterator, since both will have to keep a pointer to an memory index of in the original list: the listiterator advances this pointer when we call next(), whereas the agent keeps a pointer to the starting element of the slice and return basically (PyObject *) *(p+(i*step)) on __getitem__[i]. Mutability is a just matter of exposing this pointer to Python code in a nice way. ----aht From steve at holdenweb.com Sat Dec 19 13:00:27 2009 From: steve at holdenweb.com (Steve Holden) Date: Sat, 19 Dec 2009 13:00:27 -0500 Subject: Creating Classes In-Reply-To: <4B2C510D.80102@ieee.org> References: <26848375.post@talk.nabble.com> <4B2C510D.80102@ieee.org> Message-ID: Dave Angel wrote: > seafoid wrote: >> Hey Guys, >> >> I have started to read over classes as a brief respite from my parsing >> problem. >> >> When a class is defined, how does the class access the data upon which >> the >> class should act? >> >> Example: >> >> class Seq: >> def __init__(self, data, alphabet = Alphabet.generic_alphabet): >> self.data = data self.alphabet = alphabet >> >> def >> tostring(self): >> return self.data >> def tomutable(self): >> return MutableSeq(self.data, self.alphabet) >> def count(self, item): >> return len([x for x in self.data if x == item]) >> >> I know what it should do, but have no idea how to feed it the data. >> >> Methinks I need to invest in actual computing books as learning from >> biologists is hazy! >> >> Kind regards, >> Seafoid. >> > Steve's message was good, but I feel he kind of jumped in the middle. A > class is a description of a type of object, and the behaviors and data > that each instance of the object supports. > > You create the object by using the class name like a function call. The > arguments to that "call" are passed to the __init__ method. > > So obj = Seq("abcd") or obj = Seq("defg", "abcdefg") would each > create an object of the class. But generally, many objects will exist, > each with different data. > > The data in the object is accessed in what appears to be the "self" > namespace. The name self is just a convention, but it's the first > argument of each method of the class. So when somebody calls the > count() method, they pass 'item' a value, but self is used to refer to > that particular object's data. > > So how does 'self' get assigned? That's what Steve was describing. > When you use the syntax: > obj.count("value") > > you actually call the count method with self referring to "obj" and item > referring to "value". obj does double-duty here, both defining which > class' count() method will be called, and also supplying the first > parameter to the call, the "self" parameter. > > There are more complex things that can go on, like creating "bound" > function objects, but I think this should get you pretty far. > > One other point: you should always derive a class from some other > class, or 'object' by default. So you should being the class definition > by: > > class Seq(object): > > Why? It mainly has to do with super(). But in any case if you omit the > 'object' it's an "old style" class, and that's not even supported in > 3.x, so it's better to just get in the habit before it matters. > With respect, unless you have to expound on the differences between the old-style and the new-style classes (which aren't relevant here) you are just introducing a red herring by even mentioning it. The average Python user won't need to use super() in their first year as a Python programmer. And, since you brought up Python 3, it's not necessary to explicitly inherit from object to get new-style classes because, as you correctly point out, old-style classes don't exist in Python 3. I have no idea why you think "you should always derive a class from some other class". That's pretty unnecessary. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ UPCOMING EVENTS: http://holdenweb.eventbrite.com/ From jjposner at optimum.net Sat Dec 19 14:33:59 2009 From: jjposner at optimum.net (John Posner) Date: Sat, 19 Dec 2009 14:33:59 -0500 Subject: Programming intro book ch1 and ch2 (Windows/Python 3) - Request For Comments References: Message-ID: On Fri, 18 Dec 2009 13:00:48 -0500, Alf P. Steinbach wrote: > > Chapter 2 is about Basic Concepts (of programming). It's the usual: > variables, ... 1. Overall suggestion You have a tendency to include non-pertinent asides [1]. But then, rambling a bit endows a manuscript with the author's distinctive voice. Fortunately, we live in a hypertext-enabled world, where you can have your cake and eat it, too. I suggest that you go over your manuscript with a ruthless eye, and turn your rambles into hypertext-accessible "sidebars". See how much you can reduce the length of Chapter 2, which current runs 98 pages! 2. Comments on Section 2.6.7, "References & automatic garbage collection" There's a spell-check evader on page 2:49: "trough" s.b. "through". And your spell-checker should have caught "adressable" on page 2:48. I find your sequence-of-attribute-lookups approach to the topic of "variable assignment" interesting. The directed-graph illustration on page 2:49 even hints at the fact that in the world of Python, names ("turtle", "forward", etc.) and objects (various kinds of yellow boxes) are very different things. (I suggest getting rid of the callout "Very small fixed size variable". That way, only objects, not names, have the italicized callouts.) But using the term "references" and the directed-graph metaphor has its drawbacks. Avoiding the term "reference" will make it easier to navigate the turbulent waters of call-by-reference vs. call-by-value vs. call-by-name. (You don't even stick a toe in those waters in Section 2.7.5.) Combining memory addresses with the directed graph metaphor invites the reader to think at way too low a level, IMHO. Another metaphor just occurred to me: a scavenger hunt. It even fits in with your potentially-infinite-attribute-access approach to the topic. A sequence of attribute accesses: turtle.forward.__doc__ ... is like a sequence of scavenger-hunt instructions: 1. Get your next clue at the big oak tree 2. Get your next clue at the back door of the Valley Bank 3. Get your next clue under Dad's Oldsmobile It's clear that the scavenger hunt's clues (short characters strings -- like Python names) are different from the physical objects that you access as the hunt progresses (tree, bank building, automobile -- like Python objects). I haven't lived with this metaphor long enough to form an opinion as to where it might reside on the brain-dead <---> brilliant scale. As I've said in this forum (and the edu-sig forum) before, I think the best metaphor for understanding Python variable assignment is John Zelle's yellow-sticky-note metaphor. [2] I hope these comments help. -John -------------- [1] Examples: Section 2, page 2:1 It's almost impossible, but, as Robert A. Heinlein remarked, "A Paradox May Be Paradoctored". Section 2, page 2:3 (I believe the original text comes from the "Jargon file") about how arbitrary, undesirable and downright dangerous DWIM guessing can be: ... Section 2.5.1, page 2:14 a natural extension is to make that into a square spiral with far more windings; I recall it as a common theme in 1970?s pop-art and it can be quite impressive! Section 2.6.7, page 2:46 (some flat-Earthers once thought that the flat Earth rested on four turtles, which in turn stood on four larger turtles, and so on all the way down) [2] "Python Programming: An Introduction to Computer Science" by John Zelle (Franklin, Biddle & Associates, 2004) See Section 2.5.1, "Simple Assignment" From rami.chowdhury at gmail.com Sat Dec 19 15:06:48 2009 From: rami.chowdhury at gmail.com (Rami Chowdhury) Date: Sat, 19 Dec 2009 12:06:48 -0800 Subject: How Do I...? In-Reply-To: <4dc0cfea0912190850kec7b3a2ice9cac3356cc221a@mail.gmail.com> References: <4dc0cfea0912181055o4da24927n4776b197efd5943@mail.gmail.com> <4B2BE024.4010307@tim.thechases.com> <4dc0cfea0912190210h3be56c85r34dbb93c672519cb@mail.gmail.com> <4B2CEFC6.8000801@tim.thechases.com> <4dc0cfea0912190850kec7b3a2ice9cac3356cc221a@mail.gmail.com> Message-ID: <64348AFF-864A-4C30-AA07-15C326EAB801@gmail.com> On Dec 19, 2009, at 08:50 , Victor Subervi wrote: > On Sat, Dec 19, 2009 at 10:22 AM, Tim Chase wrote: > Victor Subervi wrote: > On Fri, Dec 18, 2009 at 3:03 PM, Tim Chase wrote: > > Well, you start by reading a book on how to program. You would then learn > that what you want (in all likelihood) is a dictionary/map structure for > dynamically created key/value pairs. Once you have progressed from your > current apprenticeship and achieved the rank of third-degree journeyman > programmer, the ways of dynamic variable creation will avail themselves. > > Why the arrogance? Why talk down to me? > > The aim was not arrogance, but expression of exasperation > You can't do it. [snip] You couldn't possibly understand. And you're accusing someone else of arrogance here ;-)? I don't think anyone is deliberately talking down to you -- would you contest the assertion that you are an 'apprentice' in the art of programming, and are posting on c.l.py to learn from those with more experience? > You have my continued promise that I will do all I can to edit my questions as intelligently as you would before I post them. > Trust me, I don't like looking foolish, and I know I do. Tim's given you a few suggestions, as have many others -- perhaps it would be worth making a note, somewhere, of checks to go through before you post, to ensure that you come across as well as you intend? HTH, Rami -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Sat Dec 19 15:13:54 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 19 Dec 2009 15:13:54 -0500 Subject: Tutorial: Accessing Desktop CouchDB with Python Message-ID: Above is a section heading in Code tutorial: make your application sync with Ubuntu One http://arstechnica.com/open-source/guides/2009/12/code-tutorial-make-your-application-sync-with-ubuntu-one.ars I just read part of it and thought others might find it interesting. tjr From lie.1296 at gmail.com Sat Dec 19 15:26:03 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Sun, 20 Dec 2009 07:26:03 +1100 Subject: numpy performance and random numbers In-Reply-To: <69df23c3-ee4e-4c8f-9d66-581e3e272fad@m38g2000yqd.googlegroups.com> References: <00b63dbe$0$15654$c3e8da3@news.astraweb.com> <69df23c3-ee4e-4c8f-9d66-581e3e272fad@m38g2000yqd.googlegroups.com> Message-ID: <4b2d36db$1@dnews.tpgi.com.au> On 12/20/2009 4:02 AM, Carl Johan Rehn wrote: >>>> How did you time it? > > Well, in Matlab I used "tic; for i = 1:1000, randn(100, 10000), end; > toc" and in IPython i used a similar construct but with "time" instead > of tic/(toc. Code? >>>> Parallel PRNGs are an unsolved problem in computer science. > > Thanks again for sharing your knowledge. I had no idea. This means > that if I want to speed up my application I have to go for the fastest > random generator and focus on other parts of my code that can be > vectorized. If you don't care about "repeatability" (which is already extremely difficult in parallel processing even without random number generators), you can just start two PRNG at two distinct states (and probably from two different algorithms) and they will each spews out two independent streams of random numbers. What was "unsolved" was the "pseudo-" part of the random number generation, which guarantee perfect replayability in all conditions. From victorsubervi at gmail.com Sat Dec 19 15:34:20 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Sat, 19 Dec 2009 15:34:20 -0500 Subject: How Do I...? In-Reply-To: <64348AFF-864A-4C30-AA07-15C326EAB801@gmail.com> References: <4dc0cfea0912181055o4da24927n4776b197efd5943@mail.gmail.com> <4B2BE024.4010307@tim.thechases.com> <4dc0cfea0912190210h3be56c85r34dbb93c672519cb@mail.gmail.com> <4B2CEFC6.8000801@tim.thechases.com> <4dc0cfea0912190850kec7b3a2ice9cac3356cc221a@mail.gmail.com> <64348AFF-864A-4C30-AA07-15C326EAB801@gmail.com> Message-ID: <4dc0cfea0912191234xcb9916fl6571754db0c2d0cf@mail.gmail.com> On Sat, Dec 19, 2009 at 3:06 PM, Rami Chowdhury wrote: > Tim's given you a few suggestions, as have many others -- perhaps it would > be worth making a note, somewhere, of checks to go through before you post, > to ensure that you come across as well as you intend? > I appreciate Tim's advice. I came across as I intended. V -------------- next part -------------- An HTML attachment was scrubbed... URL: From yarkot1 at gmail.com Sat Dec 19 15:48:07 2009 From: yarkot1 at gmail.com (Yarko) Date: Sat, 19 Dec 2009 12:48:07 -0800 (PST) Subject: Anybody use web2py? References: <6oidnWzFKdtK6LHWnZ2dnUVZ_opi4p2d@supernews.com> Message-ID: <320b6ef5-8508-4258-9e70-0d987d77e85f@u7g2000yqm.googlegroups.com> On Dec 19, 12:42?am, AppRe Godeck wrote: > Just curious if anybody prefers web2py over django, and visa versa. I > know it's been discussed on a flame war level a lot. I am looking for a > more intellectual reasoning behind using one or the other. Chevy or Ford? (or whatever pair you prefer) vi or emacs? ... These hold one aspect. Hammer or a saw? Hold (perhaps) another... us.pycon.org, for example, uses both (in reality a mix of the above argument sets, but at least evidence of the latter: different tools for different problems). >From a rapid prototyping perspective, web2py is heavily data-table efficient: that is, you can define a system, and all the app creation, form generation and validation have defaults out of the box, and you can have a "sense" of your data-centric structure in minutes. The same argument can go against ("how do I get it to do exactly what _I_ want it to, not what it wants to?") - that is, defaults hide things, and that has two edges... >From a layout/user interaction rapid prototyping perspective, web2py is just entering the waters... There is a steady growth of users, and (as you would expect for a young framework), a lot of changes going on (although backward compatiblity is a constant mantra when considering changes, that too is a double-edged thing). I find web2py useful, fast, and at times / in areas not as evolved / flexible as I'd like. BUT I could learn it quickly, and get to work quickly. I have taken an intro Django course (at a PyCon), have built a few things with it (not nearly as many as I have w/ web2py), and I _can_ do things in it - so I'll let someone else w/ django "miles" under their belt speak their mind. - Yarko From yarkot1 at gmail.com Sat Dec 19 15:51:30 2009 From: yarkot1 at gmail.com (Yarko) Date: Sat, 19 Dec 2009 12:51:30 -0800 (PST) Subject: Anybody use web2py? References: <6oidnWzFKdtK6LHWnZ2dnUVZ_opi4p2d@supernews.com> <320b6ef5-8508-4258-9e70-0d987d77e85f@u7g2000yqm.googlegroups.com> Message-ID: On Dec 19, 2:48?pm, Yarko wrote: > On Dec 19, 12:42?am, AppRe Godeck wrote: > > > Just curious if anybody prefers web2py over django, and visa versa. I > > know it's been discussed on a flame war level a lot. I am looking for a > > more intellectual reasoning behind using one or the other. > > Chevy or Ford? ?(or whatever pair you prefer) > vi or emacs? > ... > > These hold one aspect. > > Hammer or a saw? > > Hold (perhaps) another... > > us.pycon.org, for example, uses both (in reality a mix of the above > argument sets, but at least evidence of the latter: different tools > for different problems). > > From a rapid prototyping perspective, web2py is heavily data-table > efficient: that is, you can define a system, and all the app creation, > form generation and validation have defaults out of the box, and you > can have a "sense" of your data-centric structure in minutes. ? The > same argument can go against ("how do I get it to do exactly what _I_ > want it to, not what it wants to?") - that is, defaults hide things, > and ?that has two edges... > > From a layout/user interaction rapid prototyping perspective, web2py > is just entering the waters... > > There is a steady growth of users, and (as you would expect for a > young framework), a lot of changes going on (although backward > compatiblity is a constant mantra when considering changes, that too > is a double-edged thing). > > I find web2py useful, fast, and at times / in areas not as evolved / > flexible as I'd like. ?BUT I could learn it quickly, and get to work > quickly. Oh and one more thing: I find it dependable (not that snapshots don't have bugs, but that they are well defined, not "wild", and quickly fixed - and if you work around them, you can also depend on the system you've created). FYI, it does the money/registration part of PyCon (past 2 years). > > I have taken an intro Django course (at a PyCon), have built a few > things with it (not nearly as many as I have w/ web2py), and I _can_ > do things in it - so I'll let someone else w/ django "miles" under > their belt speak their mind. > > - Yarko From sturlamolden at yahoo.no Sat Dec 19 16:58:37 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Sat, 19 Dec 2009 13:58:37 -0800 (PST) Subject: numpy performance and random numbers References: <00b63dbe$0$15654$c3e8da3@news.astraweb.com> <69df23c3-ee4e-4c8f-9d66-581e3e272fad@m38g2000yqd.googlegroups.com> <4b2d36db$1@dnews.tpgi.com.au> Message-ID: <9a71ed3e-de34-4d39-b2d5-66e9ff1baa91@m3g2000yqf.googlegroups.com> On 19 Des, 21:26, Lie Ryan wrote: > you can just start two PRNG at two distinct states No. You have to know for certain that the outputs don't overlap. If you pick two random states (using any PRNG), you need error- checking that states are always unique, i.e. that each PRNG never reaches the starting state of the other(s). If I had to do this, I would e.g. hash the state to a 32 bit integer. You can deal with errors by jumping to a different state or simply aborting the simulation. The problem is that the book-keeping will be costly compared to the work involved in generating a single pseudorandom deviate. So while we can construct a parallel PRNG this way, it will likely run slower than one unique PRNG. It has been suggested to use short-period MTs with different characteristic polynomials. This is also available for the nVidia GPU using CUDA. This is probably the generator I would pick if I wanted to produce random numbers in parallel. However, here we should be aware that the math has not been thoroughly proven. http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/DC/dgene.pdf http://developer.download.nvidia.com/compute/cuda/2_2/sdk/website/projects/MersenneTwister/doc/MersenneTwister.pdf There is also a version of MT that use SIMD instructions internally, which gives a factor-of-two speedup. I would never use different algorithms. It will introduce a systematic difference in the simulation. From joshua at joshuakugler.com Sat Dec 19 17:04:27 2009 From: joshua at joshuakugler.com (Joshua Kugler) Date: Sat, 19 Dec 2009 13:04:27 -0900 Subject: ANNOUNCE: awstats_reader 0.5 Message-ID: ABOUT THE MODULE ================ AwstatsReader is a pythonic interface to AWStats data cache files. Using it, you can access year and month via dict-like subscripts, and and individual data points via both dict-like subscripts and attribute-like accessors. As of version 0.5, it includes a script for merging AWStats Cache files. Download: http://azariah.com/open_source.html ABOUT THE AUTHOR ================ Joshua Kugler (joshua at azariah.com) is a programmer and system administator with over 10 years of industory experience. He is currently looking for a job. Happen to have one you could offer him? :) Resume at: http://jjncj.com/papers/KuglerResume.pdf DISCLAIMER ========== This is an early-beta release. There are 43 tests which cover most, if not all of the functionality, but not much documentation. The interface should be considered stable, but not in concrete. The usage of this project in a "real world" situation (awstats_cache_merge.py) led to many improvements to the API. I wrote this via examples from an AWStats cache file, so I'm sure there are sections for which I do not have definitions. If you would send me those sections, I'll be sure to add them. Right now, this will parse and display cache files from AWStats 6.5. I've not tested other versions yet, as 6.5 is the only version I've had access to so far. REPOSITORY ========== No public repository yet. Just haven't set it up. LICENSE ======= Modified BSD EXAMPLE ======= import awstats_reader obj = awstats_reader.AwstatsReader('/path/to/awstats_logs', 'example.com') print obj[2007] print obj[2008][6] m = obj[2009][7] print m['general'] # Access like a dictionary... print m['general']['LastLine'] #...or like an object attribute print m['general'].LastLine print m.general.LastLine FEEDBACK ======== Please send questions/comments/suggestions to awstatsreader at azariah.com For now, you can find the latest version here: http://azariah.com/open_source.html From sturlamolden at yahoo.no Sat Dec 19 17:09:54 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Sat, 19 Dec 2009 14:09:54 -0800 (PST) Subject: numpy performance and random numbers References: <00b63dbe$0$15654$c3e8da3@news.astraweb.com> <69df23c3-ee4e-4c8f-9d66-581e3e272fad@m38g2000yqd.googlegroups.com> <4b2d36db$1@dnews.tpgi.com.au> <9a71ed3e-de34-4d39-b2d5-66e9ff1baa91@m3g2000yqf.googlegroups.com> Message-ID: On 19 Des, 22:58, sturlamolden wrote: > If you pick two random states (using any PRNG), you need error- > checking that states are always unique, i.e. that each PRNG never > reaches the starting state of the other(s). Another note on this: Ideally, we would e.g. know how to find (analytically) MT states that are very far apart. But to my knowledge no such equation has been derived. But often in Monte Carlo simulations, the PRNG is not the dominant computational bottleneck. So we can simply start N PRNGs from N consequtive states, and for each PRNG only use every N-th pseudorandom deviate. From eureka52 at yahoo.com Sat Dec 19 17:17:19 2009 From: eureka52 at yahoo.com (Rick) Date: Sat, 19 Dec 2009 22:17:19 -0000 Subject: using time.gov to get the current time Message-ID: Is there any way to get the current time from time.gov using urllib2 or something similar? Does anyone have any examples of doing this? Thanks! Rick King Southfield MI From rory at campbell-lange.net Sat Dec 19 17:43:31 2009 From: rory at campbell-lange.net (Rory Campbell-Lange) Date: Sat, 19 Dec 2009 22:43:31 +0000 Subject: Sort the values of a dict In-Reply-To: <4B2C1C03.8040108@mrabarnett.plus.com> References: <4b2c0386$0$1105$4fafbaef@reader4.news.tin.it> <20091219000054.GE22180@campbell-lange.net> <4B2C1C03.8040108@mrabarnett.plus.com> Message-ID: <20091219224331.GA15289@campbell-lange.net> > >>>>mylist = [z for z in zip(list(d), list(d.values()))] > The Pythonic way for the above line is: > >>> mylist = list(d.items()) Quite right. Thanks for pointing that out. I liked Chris Kaynor's solution: s = sorted(d.items(), key=lambda i: i[1][2]) I'm a bit rusty, and have just picked up the new "Learning Python" book but I'm finding that it isn't providing a useful refresher to the language or a particularly good introduction to version 3. Have you any suggestions. Regards Rory -- Rory Campbell-Lange rory at campbell-lange.net Campbell-Lange Workshop www.campbell-lange.net 0207 6311 555 3 Tottenham Street London W1T 2AF Registered in England No. 04551928 From care02 at gmail.com Sat Dec 19 17:57:15 2009 From: care02 at gmail.com (Carl Johan Rehn) Date: Sat, 19 Dec 2009 14:57:15 -0800 (PST) Subject: numpy performance and random numbers References: <00b63dbe$0$15654$c3e8da3@news.astraweb.com> <69df23c3-ee4e-4c8f-9d66-581e3e272fad@m38g2000yqd.googlegroups.com> <4b2d36db$1@dnews.tpgi.com.au> <9a71ed3e-de34-4d39-b2d5-66e9ff1baa91@m3g2000yqf.googlegroups.com> Message-ID: On 19 Dec, 23:09, sturlamolden wrote: > On 19 Des, 22:58, sturlamolden wrote: > > > If you pick two random states (using any PRNG), you need error- > > checking that states are always unique, i.e. that each PRNG never > > reaches the starting state of the other(s). > > Another note on this: > > Ideally, we would e.g. know how to find (analytically) MT states that > are very far apart. But to my knowledge no such equation has been > derived. > > But often in Monte Carlo simulations, the PRNG is not the dominant > computational bottleneck. So we can simply start N PRNGs from N > consequtive states, and for each PRNG only use every N-th pseudorandom > deviate. Thank you for pointing me to the short-period MT reference and especially the reference on the CUDA-version of parallel MT (even though I would have wished the author had included a benchmark comparison in the report). This is a very interesting topic. I agree that it may work to start PRNGs at distinct and different states, but that bookkeeping may slow down the algorithm so that it is not worth the effort. However, the CUDA-version sounds interesting and should be easy enough to use in a practical application. Carl From john at castleamber.com Sat Dec 19 18:09:01 2009 From: john at castleamber.com (John Bokma) Date: Sat, 19 Dec 2009 17:09:01 -0600 Subject: Sort the values of a dict References: <4b2c0386$0$1105$4fafbaef@reader4.news.tin.it> <20091219000054.GE22180@campbell-lange.net> <4B2C1C03.8040108@mrabarnett.plus.com> Message-ID: <87k4wik1de.fsf@castleamber.com> Rory Campbell-Lange writes: > I'm a bit rusty, and have just picked up the new "Learning Python" book > but I'm finding that it isn't providing a useful refresher to the > language or a particularly good introduction to version 3. Have you any > suggestions. While you aren't addressing me, I do have 2 suggestions: * Programming in Python 3 by Mark Summerfield (make sure you get the 2nd edition) * Dive into Python 3 by Mark Pilgrim I am halfway in the first book (but the 1st edition) and like it a lot. I know Dive into Python from an earlier version (2.x) and have no problem at all recommending the Python 3 edition. You can read/download it here: http://diveintopython3.org/ -- John Bokma Read my blog: http://johnbokma.com/ Hire me (Perl/Python): http://castleamber.com/ From sccolbert at gmail.com Sat Dec 19 18:25:31 2009 From: sccolbert at gmail.com (Chris Colbert) Date: Sun, 20 Dec 2009 00:25:31 +0100 Subject: a python downloader for the Amazon mp3 store Message-ID: <7f014ea60912191525v418a017ck9ec8daea39dfaf2e@mail.gmail.com> So, I wasn't happy with the Amazon mp3 downloader for linux (because it sucks). And clamz is written in C with a bunch of dependencies. Thus, I've created a python downloader for .amz files using the crypto keys figured out by Ben Moody (clamz author). Its just command line only right now, but I will add a pyqt front end in the future. The only external dependency is PyCrypto, which is in the ubuntu repos. I always appreciate feedback! GPL licensed http://code.google.com/p/pymazon/ Cheers! Chris -------------- next part -------------- An HTML attachment was scrubbed... URL: From massimodipierro71 at gmail.com Sat Dec 19 18:32:32 2009 From: massimodipierro71 at gmail.com (mdipierro) Date: Sat, 19 Dec 2009 15:32:32 -0800 (PST) Subject: Anybody use web2py? References: <6oidnWzFKdtK6LHWnZ2dnUVZ_opi4p2d@supernews.com> Message-ID: <39d22fcc-c721-4da3-952d-f2bc178a3122@l13g2000yqb.googlegroups.com> On Dec 19, 12:42?am, AppRe Godeck wrote: > Just curious if anybody prefers web2py over django, and visa versa. I > know it's been discussed on a flame war level a lot. I am looking for a > more intellectual reasoning behind using one or the other. Of course I am the most biased person in the world on this topic but perhaps you want to hear my bias. A little bit of history... I thought a Django course at DePaul University and built a CMS for the United Nations in Django. I loved it. Then I also learned RoR. I found RoR more intuitive and better for rapid prototyping. I found Django much faster and more solid. I decided to build a proof of concept system that was somewhat in between Django and Rails with focus on 3 features: 1) easy to start with (no installation, no configuration, web based IDE, web based testing, debugging, and database interface); 2) enforce good practice (MVC, postbacks); 3) secure (escape all output, talk to database via DAL to present injections, server-side cookies with uuid session keys, role based access control with pluggable login methods, regex validation for all input including URLs). Originally it was a proof of concept, mostly suitable for teaching. Then lots of people helped to make it better and turn it into a production system. Now he had more than 50 contributors and a more than 20 companies that provide support. There are some distinctive features of web2py vs Django. Some love them, some hate hate them (mostly people who did not try them): - We promise backward compatibility. I do not accept patches that break it. It has been backward compatible for three years and I will enforce the copyright, if necessary, in order to ensure it for the future. - In web2py models and controllers are not modules. They are not imported. They are executed. This means you do not need to import basic web2py symbols. They are already defined in the environment that executes the models and controllers (like in Rails). This also means you do not need to restart the web server when you edit your app. You can import additional modules and you can define modules if you like. - You have a web based IDE with editor, some conflict resolution, Mercurial integration, ticketing system, web-based testing and debugging. - The Database Abstraction Layer (DAL) is closed to SQL than Dango ORM is. This means it does less for you (in particular about many 2 many) but it is more flaxible when it comes to complex joins, aggregates and nested selects. - The DAL supports out of the box SQLite, MySQL, PostgreSQL, MSSQL, Oracle, FireBird, FireBase, DB2, Informix, Ingres, and the Google App Engine (except for joins and multi-entity transactions). We plan support for Sybase and MongoDB within one month. - The DAL supports transactions. It means it will create and/or ALTER tables for you as your model changes. This can be disabled. - The DAL has partial support for some legacy databases that do not have an 'id' auto increment primary key. - It has a plugin and a component systems (here is an old video: http://www.vimeo.com/7182692 the video says "experimental" but this is now stable in trunk, although not very well documented). - both systems have a web based database interface (Django calls it "admin", web2py calls it "appadmin, not to be confused with web2py "admin", the IDE). The Django one is more polished, customizable and designed to be exposed to users. The web2py one is raw and designed for the administrator. It is not customizable. Because it is designed for the administrator and requires administrator login it allows arbitrary DAL code to be executed. It can be disabled. Here is the last app I built with it: http://www.vimeo.com/7182692 running on GAE here: http://www.vimeo.com/7182692 Here http://www.vimeo.com/6507384 you can see a video in which I rewrite the Django polls tutorial in web2py. You will get an idea of some of the differences. Anyway, I think both system are great. Spend 15 minutes (no more) with each to make up your mind, and stick with it. Massimo From massimodipierro71 at gmail.com Sat Dec 19 18:35:44 2009 From: massimodipierro71 at gmail.com (mdipierro) Date: Sat, 19 Dec 2009 15:35:44 -0800 (PST) Subject: Anybody use web2py? References: <6oidnWzFKdtK6LHWnZ2dnUVZ_opi4p2d@supernews.com> <39d22fcc-c721-4da3-952d-f2bc178a3122@l13g2000yqb.googlegroups.com> Message-ID: <3e164613-a375-45a6-8965-8c90c2369125@r5g2000yqb.googlegroups.com> Errata. I said "The dal supports transactions" where I meant "the dal supports migrations". Of course it also supports "transactions" as well as "distributed transactions". On Dec 19, 5:32?pm, mdipierro wrote: > On Dec 19, 12:42?am, AppRe Godeck wrote: > > > Just curious if anybody prefers web2py over django, and visa versa. I > > know it's been discussed on a flame war level a lot. I am looking for a > > more intellectual reasoning behind using one or the other. > > Of course I am the most biased person in the world on this topic but > perhaps you want to hear my bias. > > A little bit of history... I thought a Django course at DePaul > University and built a CMS for the United Nations in Django. I loved > it. Then I also learned RoR. I found RoR more intuitive and better for > rapid prototyping. I found Django much faster and more solid. I > decided to build a proof of concept system that was somewhat in > between Django and Rails with focus on 3 features: 1) easy to start > with (no installation, no configuration, web based IDE, web based > testing, debugging, and database interface); 2) enforce good practice > (MVC, postbacks); 3) secure (escape all output, talk to database via > DAL to present injections, server-side cookies with uuid session keys, > role based access control with pluggable login methods, regex > validation for all input including URLs). > > Originally it was a proof of concept, mostly suitable for teaching. > Then lots of people helped to make it better and turn it into a > production system. Now he had more than 50 contributors and a more > than 20 companies that provide support. > > There are some distinctive features of web2py vs Django. Some love > them, some hate hate them (mostly people who did not try them): > > - We promise backward compatibility. I do not accept patches that > break it. It has been backward compatible for three years and I will > enforce the copyright, if necessary, in order to ensure it for the > future. > > - In web2py models and controllers are not modules. They are not > imported. They are executed. This means you do not need to import > basic web2py symbols. They are already defined in the environment that > executes the models and controllers (like in Rails). This also means > you do not need to restart the web server when you edit your app. You > can import additional modules and you can define modules if you like. > > - You have a web based IDE with editor, some conflict resolution, > Mercurial integration, ticketing system, web-based testing and > debugging. > > - The Database Abstraction Layer (DAL) is closed to SQL than Dango ORM > is. This means it does less for you (in particular about many 2 many) > but it is more flaxible when it comes to complex joins, aggregates and > nested selects. > > - The DAL supports out of the box SQLite, MySQL, PostgreSQL, MSSQL, > Oracle, FireBird, FireBase, DB2, Informix, Ingres, and the Google App > Engine (except for joins and multi-entity transactions). We plan > support for Sybase and MongoDB within one month. > > - The DAL supports transactions. It means it will create and/or ALTER > tables for you as your model changes. This can be disabled. > > - The DAL has partial support for some legacy databases that do not > have an 'id' auto increment primary key. > > - It has a plugin and a component systems (here is an old video:http://www.vimeo.com/7182692the video says "experimental" but this is > now stable in trunk, although not very well documented). > > - both systems have a web based database interface (Django calls it > "admin", web2py calls it "appadmin, not to be confused with web2py > "admin", the IDE). The Django one is more polished, customizable and > designed to be exposed to users. The web2py one is raw and designed > for the administrator. It is not customizable. Because it is designed > for the administrator and requires administrator login it allows > arbitrary DAL code to be executed. It can be disabled. > > Here is the last app I built with it:http://www.vimeo.com/7182692 > running on GAE here:http://www.vimeo.com/7182692 > > Herehttp://www.vimeo.com/6507384you can see a video in which I > rewrite the Django polls tutorial in web2py. You will get an idea of > some of the differences. > > Anyway, I think both system are great. Spend 15 minutes (no more) with > each to make up your mind, and stick with it. > > Massimo From j2geek at gmail.com Sat Dec 19 18:42:39 2009 From: j2geek at gmail.com (Jake) Date: Sat, 19 Dec 2009 15:42:39 -0800 (PST) Subject: Anybody use web2py? References: <6oidnWzFKdtK6LHWnZ2dnUVZ_opi4p2d@supernews.com> Message-ID: On Dec 19, 1:42?am, AppRe Godeck wrote: > Just curious if anybody prefers web2py over django, and visa versa. I > know it's been discussed on a flame war level a lot. I am looking for a > more intellectual reasoning behind using one or the other. Hi! I come from a mvc framework background in a few different languages (java, php, ruby). I'm only a couple weeks into web2py, I'm finding web2py a joy to work with. I won't waste your time with the features it provides, as you can find these on the website. There is also a copy of the lead developer's book on the site, and its very well written. If web2py intrigues you, I would recommend just trying it for a few days. It's pretty small (relatively few exposed classes and functions) and very comprehensible, so you won't really have to invest much if you decide to try it and don't like it. The mailing list is active and responsive, and the lead developer happens to have chimed in on every question i've asked. On the down side, the irc community is very small. Good Luck, Jake From greg.ewing at canterbury.ac.nz Sat Dec 19 19:04:10 2009 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Sun, 20 Dec 2009 13:04:10 +1300 Subject: numpy performance and random numbers In-Reply-To: <4b2d36db$1@dnews.tpgi.com.au> References: <00b63dbe$0$15654$c3e8da3@news.astraweb.com> <69df23c3-ee4e-4c8f-9d66-581e3e272fad@m38g2000yqd.googlegroups.com> <4b2d36db$1@dnews.tpgi.com.au> Message-ID: <7p57b7FuoqU1@mid.individual.net> Lie Ryan wrote: > If you don't care about "repeatability" (which is already extremely > difficult in parallel processing even without random number generators), > you can just start two PRNG at two distinct states (and probably from > two different algorithms) There's no need for different algorithms, and no problem with repeatability. There exist algorithms with a very long period (on the order of 2*100 or more) for which it's easy to calculate seeds for a set of guaranteed non- overlapping subsequences. http://or.journal.informs.org/cgi/content/abstract/44/5/816 http://or.journal.informs.org/cgi/content/abstract/47/1/159 In these kinds of generator, moving from one state to the next involves multiplying a state vector by a matrix using modulo arithmetic. So you can jump ahead N steps by raising the matrix to the power of N. -- Greg From rhodri at wildebst.demon.co.uk Sat Dec 19 19:07:02 2009 From: rhodri at wildebst.demon.co.uk (Rhodri James) Date: Sun, 20 Dec 2009 00:07:02 -0000 Subject: Raw string substitution problem References: <931375.44828.qm@web58902.mail.re1.yahoo.com> <2I-dnaKkY7MM_LfWnZ2dnUVZ_sGdnZ2d@rcn.net> Message-ID: On Fri, 18 Dec 2009 17:58:08 -0000, Alan G Isaac wrote: > On 12/17/2009 7:59 PM, Rhodri James wrote: >> "re.compile('a\\nc')" passes a sequence of four characters to >> re.compile: 'a', '\', 'n' and 'c'. re.compile() then does it's own >> interpretation: 'a' passes through as is, '\' flags an escape which >> combined with 'n' produces the newline character (0x0a), and 'c' passes >> through as is. > > > I got that from MRAB's posts. (Thanks.) > What I'm not getting is why the replacement string > gets this particular interpretation. What is the payoff? So that the substitution escapes \1, \2 and so on work. -- Rhodri James *-* Wildebeeste Herder to the Masses From massimodipierro71 at gmail.com Sat Dec 19 19:07:50 2009 From: massimodipierro71 at gmail.com (mdipierro) Date: Sat, 19 Dec 2009 16:07:50 -0800 (PST) Subject: Anybody use web2py? References: <6oidnWzFKdtK6LHWnZ2dnUVZ_opi4p2d@supernews.com> <39d22fcc-c721-4da3-952d-f2bc178a3122@l13g2000yqb.googlegroups.com> Message-ID: <23144c6a-2202-4550-8110-914a1ff226f4@g26g2000yqe.googlegroups.com> Errata 2. Before people jump on me. I said "copyright" but I meant "trademark". Of course web2py is GPL2 so everybody can copy and modify it. The license has an exception that basically treats the compiled web2py as freeware. The license does not extend to apps that require web2py. They can be distributed under any license you like, included closed source and bundled with the web2py binary. On Dec 19, 5:32?pm, mdipierro wrote: > On Dec 19, 12:42?am, AppRe Godeck wrote: > > > Just curious if anybody prefers web2py over django, and visa versa. I > > know it's been discussed on a flame war level a lot. I am looking for a > > more intellectual reasoning behind using one or the other. > > Of course I am the most biased person in the world on this topic but > perhaps you want to hear my bias. > > A little bit of history... I thought a Django course at DePaul > University and built a CMS for the United Nations in Django. I loved > it. Then I also learned RoR. I found RoR more intuitive and better for > rapid prototyping. I found Django much faster and more solid. I > decided to build a proof of concept system that was somewhat in > between Django and Rails with focus on 3 features: 1) easy to start > with (no installation, no configuration, web based IDE, web based > testing, debugging, and database interface); 2) enforce good practice > (MVC, postbacks); 3) secure (escape all output, talk to database via > DAL to present injections, server-side cookies with uuid session keys, > role based access control with pluggable login methods, regex > validation for all input including URLs). > > Originally it was a proof of concept, mostly suitable for teaching. > Then lots of people helped to make it better and turn it into a > production system. Now he had more than 50 contributors and a more > than 20 companies that provide support. > > There are some distinctive features of web2py vs Django. Some love > them, some hate hate them (mostly people who did not try them): > > - We promise backward compatibility. I do not accept patches that > break it. It has been backward compatible for three years and I will > enforce the copyright, if necessary, in order to ensure it for the > future. > > - In web2py models and controllers are not modules. They are not > imported. They are executed. This means you do not need to import > basic web2py symbols. They are already defined in the environment that > executes the models and controllers (like in Rails). This also means > you do not need to restart the web server when you edit your app. You > can import additional modules and you can define modules if you like. > > - You have a web based IDE with editor, some conflict resolution, > Mercurial integration, ticketing system, web-based testing and > debugging. > > - The Database Abstraction Layer (DAL) is closed to SQL than Dango ORM > is. This means it does less for you (in particular about many 2 many) > but it is more flaxible when it comes to complex joins, aggregates and > nested selects. > > - The DAL supports out of the box SQLite, MySQL, PostgreSQL, MSSQL, > Oracle, FireBird, FireBase, DB2, Informix, Ingres, and the Google App > Engine (except for joins and multi-entity transactions). We plan > support for Sybase and MongoDB within one month. > > - The DAL supports transactions. It means it will create and/or ALTER > tables for you as your model changes. This can be disabled. > > - The DAL has partial support for some legacy databases that do not > have an 'id' auto increment primary key. > > - It has a plugin and a component systems (here is an old video:http://www.vimeo.com/7182692the video says "experimental" but this is > now stable in trunk, although not very well documented). > > - both systems have a web based database interface (Django calls it > "admin", web2py calls it "appadmin, not to be confused with web2py > "admin", the IDE). The Django one is more polished, customizable and > designed to be exposed to users. The web2py one is raw and designed > for the administrator. It is not customizable. Because it is designed > for the administrator and requires administrator login it allows > arbitrary DAL code to be executed. It can be disabled. > > Here is the last app I built with it:http://www.vimeo.com/7182692 > running on GAE here:http://www.vimeo.com/7182692 > > Herehttp://www.vimeo.com/6507384you can see a video in which I > rewrite the Django polls tutorial in web2py. You will get an idea of > some of the differences. > > Anyway, I think both system are great. Spend 15 minutes (no more) with > each to make up your mind, and stick with it. > > Massimo From karlrixon at gmail.com Sat Dec 19 19:10:13 2009 From: karlrixon at gmail.com (KarlRixon) Date: Sat, 19 Dec 2009 16:10:13 -0800 (PST) Subject: Class variables static by default? Message-ID: Given the following script, I'd expect p1.items to just contain ["foo"] and p2.items to contain ["bar"] but they both contain ["foo", "bar"]. Why is this? Are object variables not specific to their instance? --------------------------- #!/usr/bin/env python class Parser: items = [] def add_item(self, item): self.items.append(item) p1 = Parser() p1.add_item("foo") p2 = Parser() p2.add_item("bar") print p1 print p2 print p1.items print p2.items ---------------------------- Output: <__main__.Parser instance at 0x7fd812ccc098> <__main__.Parser instance at 0x7fd812ccc0e0> ['foo', 'bar'] ['foo', 'bar'] From steve at holdenweb.com Sat Dec 19 19:20:29 2009 From: steve at holdenweb.com (Steve Holden) Date: Sat, 19 Dec 2009 19:20:29 -0500 Subject: how do I set a Python installation as the default under windows ? In-Reply-To: <4B2D0451.9080000@gmail.com> References: <4B2D0451.9080000@gmail.com> Message-ID: <4B2D6DCD.8080108@holdenweb.com> Stef Mientki wrote: > hello, > > I just upgraded from Python 2.5 to 2.6. > Most of the things work, > but I'm struggling with one issue, > when I start Python in a command window, > it still uses Python 2.5. > > Is there a way to get Python 2.6 as my default Python environment ? > > thanks, > Stef Mientki It's a matter of replacing C:\Python25 with C:\Python26 in your PATH environment variable, which is what the Windows command processor uses to fined executable programs. It's normal to add both the directory the interpreter lives in /and/ its Scripts subdirectory, so you may have two replacements to make. See http://www.python.org/doc/faq/windows/ for more. If anyone has any good updates to that document I'll be happy to make them (or give you permission to make them ...). It was written a long time ago, and I'm not sure it's had much love. In particular there'll not be anything relating to Windows 7. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 PyCon is coming! Atlanta, Feb 2010 http://us.pycon.org/ Holden Web LLC http://www.holdenweb.com/ UPCOMING EVENTS: http://holdenweb.eventbrite.com/ From steve at holdenweb.com Sat Dec 19 19:20:29 2009 From: steve at holdenweb.com (Steve Holden) Date: Sat, 19 Dec 2009 19:20:29 -0500 Subject: how do I set a Python installation as the default under windows ? In-Reply-To: <4B2D0451.9080000@gmail.com> References: <4B2D0451.9080000@gmail.com> Message-ID: <4B2D6DCD.8080108@holdenweb.com> Stef Mientki wrote: > hello, > > I just upgraded from Python 2.5 to 2.6. > Most of the things work, > but I'm struggling with one issue, > when I start Python in a command window, > it still uses Python 2.5. > > Is there a way to get Python 2.6 as my default Python environment ? > > thanks, > Stef Mientki It's a matter of replacing C:\Python25 with C:\Python26 in your PATH environment variable, which is what the Windows command processor uses to fined executable programs. It's normal to add both the directory the interpreter lives in /and/ its Scripts subdirectory, so you may have two replacements to make. See http://www.python.org/doc/faq/windows/ for more. If anyone has any good updates to that document I'll be happy to make them (or give you permission to make them ...). It was written a long time ago, and I'm not sure it's had much love. In particular there'll not be anything relating to Windows 7. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 PyCon is coming! Atlanta, Feb 2010 http://us.pycon.org/ Holden Web LLC http://www.holdenweb.com/ UPCOMING EVENTS: http://holdenweb.eventbrite.com/ From steve at REMOVE-THIS-cybersource.com.au Sat Dec 19 19:23:46 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 20 Dec 2009 00:23:46 GMT Subject: numpy performance and random numbers References: <00b63dbe$0$15654$c3e8da3@news.astraweb.com> <69df23c3-ee4e-4c8f-9d66-581e3e272fad@m38g2000yqd.googlegroups.com> Message-ID: <00b6f343$0$15654$c3e8da3@news.astraweb.com> On Sat, 19 Dec 2009 09:02:38 -0800, Carl Johan Rehn wrote: > Well, in Matlab I used "tic; for i = 1:1000, randn(100, 10000), end; > toc" and in IPython i used a similar construct but with "time" instead > of tic/(toc. I don't know if this will make any significant difference, but for the record that is not the optimal way to time a function in Python due to the overhead of creating the loop sequence. In Python, the typical for-loop construct is something like this: for i in range(1, 1000) but range isn't a funny way of writing "loop over these values", it actually creates a list of integers, which has a measurable cost. In Python 2.x you can reduce that cost by using xrange instead of range, but it's even better to pre-compute the list outside of the timing code. Even better still is to use a loop sequence like [None]*1000 (precomputed outside of the timing code naturally!) to minimize the cost of memory accesses. The best way to perform timings of small code snippets in Python is using the timeit module, which does all these things for you. Something like this: from timeit import Timer t = Timer('randn(100, 10000)', 'from numpy import randn') print min(t.repeat()) This will return the time taken by one million calls to randn. Because of the nature of modern operating systems, any one individual timing can be seriously impacted by other processes, so it does three independent timings and returns the lowest. And it will automatically pick the best timer to use according to your operating system (either clock, which is best on Windows, or time, which is better on Posix systems). -- Steven From jjposner at optimum.net Sat Dec 19 19:29:57 2009 From: jjposner at optimum.net (John Posner) Date: Sat, 19 Dec 2009 19:29:57 -0500 Subject: Class variables static by default? References: Message-ID: On Sat, 19 Dec 2009 19:10:13 -0500, KarlRixon wrote: > Given the following script, I'd expect p1.items to just contain > ["foo"] and p2.items to contain ["bar"] but they both contain ["foo", > "bar"]. > > Why is this? Are object variables not specific to their instance? > > --------------------------- > #!/usr/bin/env python > > class Parser: > items = [] > def add_item(self, item): > self.items.append(item) > You're using a *class attribute* instead of an *instance attribute*. Change the class definition to: class Parser: def __init__(self): self.items = [] def add_item(self, item): self.items.append(item) -John From mrholtsr at sbcglobal.net Sat Dec 19 19:30:34 2009 From: mrholtsr at sbcglobal.net (Ray Holt) Date: Sat, 19 Dec 2009 19:30:34 -0500 Subject: Question about dir function Message-ID: <3E8099AC2C044244A2154A7CF4D48A9A@ray> When I run a dir(_builtins_) I get the error message that the name _builtins_ is not defined. I haven't tried the dir function on other functions, but can someone tell me why I am getting this message? Thanks, Ray -------------- next part -------------- An HTML attachment was scrubbed... URL: From contact at xavierho.com Sat Dec 19 19:35:08 2009 From: contact at xavierho.com (Xavier Ho) Date: Sun, 20 Dec 2009 10:35:08 +1000 Subject: Class variables static by default? In-Reply-To: References: Message-ID: <2d56febf0912191635i7e0ccaefo490ba6a919666a3@mail.gmail.com> Yes, if you want instance variables that are unique to each instance of a class, do the following: class Parser: def __init__(self): self.items = [] And that should work fine. J:\_Programming Projects\Python>python test.py <__main__.Parser object at 0x0240E7B0> <__main__.Parser object at 0x02411930> ['foo'] ['bar'] Cheers, Xav On Sun, Dec 20, 2009 at 10:10 AM, KarlRixon wrote: > Given the following script, I'd expect p1.items to just contain > ["foo"] and p2.items to contain ["bar"] but they both contain ["foo", > "bar"]. > > Why is this? Are object variables not specific to their instance? > > --------------------------- > #!/usr/bin/env python > > class Parser: > items = [] > def add_item(self, item): > self.items.append(item) > > p1 = Parser() > p1.add_item("foo") > p2 = Parser() > p2.add_item("bar") > > print p1 > print p2 > print p1.items > print p2.items > ---------------------------- > > Output: > <__main__.Parser instance at 0x7fd812ccc098> > <__main__.Parser instance at 0x7fd812ccc0e0> > ['foo', 'bar'] > ['foo', 'bar'] > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From mnordhoff at mattnordhoff.com Sat Dec 19 19:39:21 2009 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Sun, 20 Dec 2009 00:39:21 +0000 Subject: Question about dir function In-Reply-To: <3E8099AC2C044244A2154A7CF4D48A9A@ray> References: <3E8099AC2C044244A2154A7CF4D48A9A@ray> Message-ID: <4B2D7239.9020409@mattnordhoff.com> Ray Holt wrote: > When I run a dir(_builtins_) I get the error message that the name > _builtins_ is not defined. I haven't tried the dir function on other > functions, but can someone tell me why I am getting this message? > Thanks, Ray You are getting that message because the name "_builtins_" is not defined, as it says. You were probably looking for "__builtins__", with 2 underscores on each end, not just 1. BTW, "__builtins__" is a CPython implementation detail. If you want to play with built-in objects, you should import the __builtin__ (no "s") module and use that. -- Matt Nordhoff From cs at zip.com.au Sat Dec 19 19:44:08 2009 From: cs at zip.com.au (Cameron Simpson) Date: Sun, 20 Dec 2009 11:44:08 +1100 Subject: Class variables static by default? In-Reply-To: References: Message-ID: <20091220004408.GA13778@cskk.homeip.net> On 19Dec2009 16:10, KarlRixon wrote: | Given the following script, I'd expect p1.items to just contain | ["foo"] and p2.items to contain ["bar"] but they both contain ["foo", | "bar"]. | | Why is this? Are object variables not specific to their instance? You haven't instatiated "items" in the object instance, so python finds it further out in the class. One class, one variable; it looks "static". Compare this (yours): class Parser: items = [] def add_item(self, item): self.items.append(item) with this: class Parser: def __init__(self): self.items = [] def add_item(self, item): self.items.append(item) The first makes an "items" in the class namespace. The second makes an "items" in each object as it is initialised. Run the rest of your code as is and compare. When you say "self.items" python looks first in the object and then in the class. Your code didn't put it in the object namespace, so it found the one in the class. Cheers, -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ I have always been a welly man myself. They are superb in wet grass, let alone lagoons of pig shit. - Julian Macassey From lie.1296 at gmail.com Sat Dec 19 19:44:11 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Sun, 20 Dec 2009 11:44:11 +1100 Subject: Class variables static by default? In-Reply-To: References: Message-ID: <4b2d735b$1@dnews.tpgi.com.au> On 12/20/2009 11:10 AM, KarlRixon wrote: > Given the following script, I'd expect p1.items to just contain > ["foo"] and p2.items to contain ["bar"] but they both contain ["foo", > "bar"]. > > Why is this? Are object variables not specific to their instance? First of all, dump all the preconception of what 'static' and 'class variable' means in any previous language you've learned. Those terms is not the same in python, and not even referring to a similar concept. In python, 'class variable' is a variable that belongs to a class; not to the instance and is shared by all instance that belong to the class. In contrast, 'instance variable' belongs to the instance, and each instance can make their instance variables refers to different objects than the other instances. Note that, in python, an object can be "owned" by multiple variables, or more precisely "an object can have multiple names". 'static' in python refers to 'staticmethod', these are called 'classmethod' in other languages (C/C++/Java). Python's 'classmethod' is an entirely different beast than 'classmethod' in other languages. 'staticmethod' in python is a method in a class that is not bound to the class nor the instance; the class is merely used as organizational tool. 'classmethod' in python is a method that is bound to the class instead of the instance; the first argument (self/cls) of a 'classmethod' is bound to the class instead of the instance. From chairman at python.org Sat Dec 19 19:44:55 2009 From: chairman at python.org (Steve Holden, Chairman, PSF) Date: Sat, 19 Dec 2009 19:44:55 -0500 Subject: Please Help Publicize PyCon Message-ID: <4B2D7387.202@python.org> Hi,everyone. This year I hope all readers of this list will assist me in crass commercial promotion of next year's PyCon. I will be speaking about "Building the Python Community", and we can't do that without advertising that the Python community exists (and hey, has pretty good conferences too). One particularly effective way for you prodigious email producers to assist is to something to your signature (as you will see I have done). This is especially important because it will bring PyCon to the attention of a wider audience - "preaching to the choir" is all very well, but doesn't build the community. regards Steve -- Steve Holden Chairman, Python Software Foundation The Python Community Conference http://python.org/psf/ PyCon 2010 Atlanta Feb 19-21 http://us.pycon.org/ Watch PyCon on video now! http://pycon.blip.tv/ From python.list at tim.thechases.com Sat Dec 19 19:45:33 2009 From: python.list at tim.thechases.com (Tim Chase) Date: Sat, 19 Dec 2009 18:45:33 -0600 Subject: Question about dir function In-Reply-To: <3E8099AC2C044244A2154A7CF4D48A9A@ray> References: <3E8099AC2C044244A2154A7CF4D48A9A@ray> Message-ID: <4B2D73AD.3020605@tim.thechases.com> Ray Holt wrote: > When I run a dir(_builtins_) I get the error message that the name > _builtins_ is not defined. I haven't tried the dir function on other > functions, but can someone tell me why I am getting this message? Thanks, > Ray > > So close, and yet thrown by requisite extra underscores: >>> dir(_builtins_) # one _ before and after Traceback (most recent call last): File "", line 1, in NameError: name '_builtins_' is not defined >>> dir(__builtins__) # two _'s before and after ['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False',...] -tkc From lie.1296 at gmail.com Sat Dec 19 19:46:37 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Sun, 20 Dec 2009 11:46:37 +1100 Subject: numpy performance and random numbers In-Reply-To: <9a71ed3e-de34-4d39-b2d5-66e9ff1baa91@m3g2000yqf.googlegroups.com> References: <00b63dbe$0$15654$c3e8da3@news.astraweb.com> <69df23c3-ee4e-4c8f-9d66-581e3e272fad@m38g2000yqd.googlegroups.com> <4b2d36db$1@dnews.tpgi.com.au> <9a71ed3e-de34-4d39-b2d5-66e9ff1baa91@m3g2000yqf.googlegroups.com> Message-ID: <4b2d73ec$1@dnews.tpgi.com.au> On 12/20/2009 8:58 AM, sturlamolden wrote: > On 19 Des, 21:26, Lie Ryan wrote: > >> you can just start two PRNG at two distinct states > > No. You have to know for certain that the outputs don't overlap. Not necessarily, you only need to be certain that the two streams don't overlap in any reasonable amount of time. For that purpose, you can use a PRNG that have extremely high period like Mersenne Twister and puts the generators to very distant states. > If you pick two random states (using any PRNG), you need error- > checking that states are always unique, i.e. that each PRNG never > reaches the starting state of the other(s). If I had to do this, I > would e.g. hash the state to a 32 bit integer. You can deal with > errors by jumping to a different state or simply aborting the > simulation. The problem is that the book-keeping will be costly > compared to the work involved in generating a single pseudorandom > deviate. So while we can construct a parallel PRNG this way, it will > likely run slower than one unique PRNG. You will need some logic to ensure that your generator's states are distant enough, but that won't incur any generation overhead. Of course this relies on the very large period of the PRNG algorithm. From chris at simplistix.co.uk Sat Dec 19 19:53:41 2009 From: chris at simplistix.co.uk (Chris Withers) Date: Sun, 20 Dec 2009 00:53:41 +0000 Subject: Checker 1.0 Released! Message-ID: <4B2D7595.8010403@simplistix.co.uk> I'm pleased to announce the first release of Checker. This is a cross-platform, pluggable tool for comparing the configuration of a machine with a known configuration stored in text files in a source control system all written in Python. For more information, please see: http://www.simplistix.co.uk/software/python/checker cheers, Chris -- Simplistix - Content Management, Zope & Python Consulting - http://www.simplistix.co.uk From steve at REMOVE-THIS-cybersource.com.au Sat Dec 19 19:55:48 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 20 Dec 2009 00:55:48 GMT Subject: numpy performance and random numbers References: <00b63dbe$0$15654$c3e8da3@news.astraweb.com> <69df23c3-ee4e-4c8f-9d66-581e3e272fad@m38g2000yqd.googlegroups.com> <4b2d36db$1@dnews.tpgi.com.au> <9a71ed3e-de34-4d39-b2d5-66e9ff1baa91@m3g2000yqf.googlegroups.com> Message-ID: <00b6fac4$0$15654$c3e8da3@news.astraweb.com> On Sat, 19 Dec 2009 13:58:37 -0800, sturlamolden wrote: > On 19 Des, 21:26, Lie Ryan wrote: > >> you can just start two PRNG at two distinct states > > No. You have to know for certain that the outputs don't overlap. "For certain"? Why? Presumably you never do a Monte Carlo simulation once, you always repeat the simulation. Does it matter if (say) one trial in fifty is lower- quality than the rest because the outputs happened to overlap? What if it's one trial in fifty thousand? So long as the probability of overlap is sufficiently small, you might not even care about doing repeated simulations. > If you pick two random states (using any PRNG), you need error- checking > that states are always unique, i.e. that each PRNG never reaches the > starting state of the other(s). If I had to do this, I would e.g. hash > the state to a 32 bit integer. You can deal with errors by jumping to a > different state or simply aborting the simulation. The problem is that > the book-keeping will be costly compared to the work involved in > generating a single pseudorandom deviate. So while we can construct a > parallel PRNG this way, it will likely run slower than one unique PRNG. Since truly random sequences sometimes produce repeating sequences, you should be able to tolerate short periods of overlap. I'd consider the following strategy: for each of your parallel PRNGs other than the first, periodically jump to another state unconditionally. The periods should be relatively prime to each other, e.g. the second PRNG jumps-ahead after (say) 51 calls, the third after 37 calls, etc. (the exact periods shouldn't be important). Use a second, cheap, PRNG to specify how far to jump ahead. The overhead should be quite small: a simple counter and test for each PRNG, plus a small number of calls to a cheap PRNG, and statistically you should expect no significant overlap. Is this workable? -- Steven From chairman at python.org Sat Dec 19 20:04:10 2009 From: chairman at python.org (Steve Holden, Chairman, PSF) Date: Sat, 19 Dec 2009 20:04:10 -0500 Subject: How Do I...? In-Reply-To: <4dc0cfea0912190850kec7b3a2ice9cac3356cc221a@mail.gmail.com> References: <4dc0cfea0912181055o4da24927n4776b197efd5943@mail.gmail.com> <4B2BE024.4010307@tim.thechases.com> <4dc0cfea0912190210h3be56c85r34dbb93c672519cb@mail.gmail.com> <4B2CEFC6.8000801@tim.thechases.com> <4dc0cfea0912190850kec7b3a2ice9cac3356cc221a@mail.gmail.com> Message-ID: <4B2D780A.8070801@python.org> Victor Subervi wrote: > On Sat, Dec 19, 2009 at 10:22 AM, Tim Chase > > > wrote: > > Victor Subervi wrote: > > On Fri, Dec 18, 2009 at 3:03 PM, Tim Chase > >wrote: > > Well, you start by reading a book on how to program. You > would then learn > that what you want (in all likelihood) is a dictionary/map > structure for > dynamically created key/value pairs. Once you have > progressed from your > current apprenticeship and achieved the rank of third-degree > journeyman > programmer, the ways of dynamic variable creation will avail > themselves. > > > Why the arrogance? Why talk down to me? > > > The aim was not arrogance, but expression of exasperation > > > Exasperation is what triggers your arrogance. Learn to control it. "Walk > a mile in my mocassins." You can't do it. I'm an artist. I think out of > my right hemisphere, not my left like you. You couldn't possibly > understand. Yes, sometimes I chide myself for the questions I ask when I > see the answers come back. The problem is that I quite literally can't > think like you. I have to force myself to do it every time. To you it's > as natural as breathing, which is why you can't relate. > It's perhaps not the most helpful approach to characterize as arrogance what is the actually the result of ignorance that only you could cure (since it requires some knowledge of your personal circumstances). It's not unusual to assume that everyone on this list has programming as a strong component of their skill set. I haven't been around the list much lately, so I don't know if your earlier posts were ever preceded by "please help a struggling right-brain artist", but on this group it certainly wouldn't have hurt. > Thank you for your help anyway. Thank you for your patience. Please try > to understand. It starts by understanding you can't understand. You have > my continued promise that I will do all I can to edit my questions as > intelligently as you would before I post them. Trust me, I don't like > looking foolish, and I know I do. You should recognize that that alone > is chiding enough. It doesn't stop me, however, for continuing to > program. The whole universe is a program. I program to understand it in > a way you couldn't even begin to grasp. > Well, if we were looking for arrogance we could easily interpret that last statement as such. Please remember that although we are mainly left-brain types on this list some of us do have artistic and musical skills. Some people will therefore probably be closer to your conception than you anticipate (though I confess I am unlikely to be one of them). > BTW, although I know full well about dictionaries, I didn't know one > could use them like you indicated, nor would I have known how to google > it. I did try googling, FYI. > V > The PSF has recently started to take diversity more seriously, and this should ideally include cultural diversity in all sorts of dimensions, so I hope you will stick around long enough to inject the artistic approach from time to time. Python has a *very* diverse user list, but not all are equally represented in the on-line communities. Tim is correct, the Python list is a pretty friendly place as far as netiquette standards go, and I am happy this thread didn't just turn into ugly name calling (which it could have with a less adult approach by the participants). regards Steve -- Steve Holden Chairman, Python Software Foundation The Python Community Conference http://python.org/psf/ PyCon 2010 Atlanta Feb 19-21 http://us.pycon.org/ Watch PyCon on video now! http://pycon.blip.tv/ From rhodri at wildebst.demon.co.uk Sat Dec 19 20:18:40 2009 From: rhodri at wildebst.demon.co.uk (Rhodri James) Date: Sun, 20 Dec 2009 01:18:40 -0000 Subject: Sort the values of a dict References: <4b2c0386$0$1105$4fafbaef@reader4.news.tin.it> Message-ID: On Fri, 18 Dec 2009 23:00:42 -0000, David Robinow wrote: > I won't engage in any arguments about pythonicity but it seems simpler > if you convert to a list of tuples right away. > > d = {1:('a', 1, 12), 5:('r',21,10), 2:('u',9,8)} > l = [(x, d[x]) for x in d.keys()] which is a long way of writing "l = d.items()", or "l = list(d.items())" if you're using Python 3. :-) > def third(q): > return q[1][2] > > s = sorted(l, key=third) > print s -- Rhodri James *-* Wildebeeste Herder to the Masses From mnordhoff at mattnordhoff.com Sat Dec 19 20:45:21 2009 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Sun, 20 Dec 2009 01:45:21 +0000 Subject: using time.gov to get the current time In-Reply-To: References: Message-ID: <4B2D81B1.3030805@mattnordhoff.com> Rick wrote: > Is there any way to get the current time from time.gov using urllib2 or something similar? > > Does anyone have any examples of doing this? > > Thanks! > Rick King > Southfield MI Why isn't your local system's clock accurate enough? -- Matt Nordhoff From steve at holdenweb.com Sat Dec 19 20:58:30 2009 From: steve at holdenweb.com (Steve Holden) Date: Sat, 19 Dec 2009 20:58:30 -0500 Subject: =?windows-1252?Q?Re=3A_I_look_for_proxy_cache_like_?= =?windows-1252?Q?apt-proxy_=28for_Debian_Package=29_but_for_?= =?windows-1252?Q?python_eggs_package=85?= In-Reply-To: <7hnag3F2ubptlU1@mid.uni-berlin.de> References: <7hnag3F2ubptlU1@mid.uni-berlin.de> Message-ID: <4B2D84C6.9070905@holdenweb.com> Diez B. Roggisch wrote: > Klein St?phane schrieb: >> Hi, >> >> I look for a tools to do proxy cache like apt-proxy (for Debian >> Package) but for python eggs package. >> >> Can a easy-install option perform this feature ? > > No. But you might install EggBasket, which is a PyPI-like server. > > http://www.chrisarndt.de/projects/eggbasket/ > > However, it is *not* a proxy, and to the best of my knowledge that's not > easily done anyway due to the way easy_install is working. It scrapes > the website it is pointed to, and when it finds something it likes, > follows that. > > Thus the server doesn't get an idea *what* easy_install is looking for, > and thus can't relay the request to the "real" PyPI, fetching the egg, > storing it locally, and then re-deliver it. > > Instead what we do with eggbasket is to copy all the eggs we obtained by > other means into a central repository that he serves. Thus we have them > backed-up & available even if PyPI or the actual package go away. > > Diez Time that software came out of beta! What needs fixing before a release? regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 PyCon is coming! Atlanta, Feb 2010 http://us.pycon.org/ Holden Web LLC http://www.holdenweb.com/ UPCOMING EVENTS: http://holdenweb.eventbrite.com/ From steve at holdenweb.com Sat Dec 19 20:58:30 2009 From: steve at holdenweb.com (Steve Holden) Date: Sat, 19 Dec 2009 20:58:30 -0500 Subject: =?windows-1252?Q?Re=3A_I_look_for_proxy_cache_like_?= =?windows-1252?Q?apt-proxy_=28for_Debian_Package=29_but_for_?= =?windows-1252?Q?python_eggs_package=85?= In-Reply-To: <7hnag3F2ubptlU1@mid.uni-berlin.de> References: <7hnag3F2ubptlU1@mid.uni-berlin.de> Message-ID: <4B2D84C6.9070905@holdenweb.com> Diez B. Roggisch wrote: > Klein St?phane schrieb: >> Hi, >> >> I look for a tools to do proxy cache like apt-proxy (for Debian >> Package) but for python eggs package. >> >> Can a easy-install option perform this feature ? > > No. But you might install EggBasket, which is a PyPI-like server. > > http://www.chrisarndt.de/projects/eggbasket/ > > However, it is *not* a proxy, and to the best of my knowledge that's not > easily done anyway due to the way easy_install is working. It scrapes > the website it is pointed to, and when it finds something it likes, > follows that. > > Thus the server doesn't get an idea *what* easy_install is looking for, > and thus can't relay the request to the "real" PyPI, fetching the egg, > storing it locally, and then re-deliver it. > > Instead what we do with eggbasket is to copy all the eggs we obtained by > other means into a central repository that he serves. Thus we have them > backed-up & available even if PyPI or the actual package go away. > > Diez Time that software came out of beta! What needs fixing before a release? regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 PyCon is coming! Atlanta, Feb 2010 http://us.pycon.org/ Holden Web LLC http://www.holdenweb.com/ UPCOMING EVENTS: http://holdenweb.eventbrite.com/ From rhodri at wildebst.demon.co.uk Sat Dec 19 21:01:22 2009 From: rhodri at wildebst.demon.co.uk (Rhodri James) Date: Sun, 20 Dec 2009 02:01:22 -0000 Subject: iterators and views of lists References: <89604fb4-9dfa-45f1-a3df-f676cd4353ea@x5g2000prf.googlegroups.com> <87b87511-744c-450e-a024-976f8c57f032@15g2000prz.googlegroups.com> <00b47124$0$15654$c3e8da3@news.astraweb.com> Message-ID: On Fri, 18 Dec 2009 21:10:28 -0000, Brendan Miller wrote: > When I said they are "weak" I meant it in sense that the algorithms > writeable against an InputerIterator interface (which is what python's > iterator protocol provides) is a proper subset of the algorithms that > can be written against a RandomAccessIterator interface. The class of > algorithms expressible against a python iterator is indeed limited to > those that can be expressed with a for each loop or map/reduce > operation. I think the most relevant thing that can be said to this is that you need to stop trying to write Python code as if it was C++. The languages constructs are intended for different purposes; iterators in C++ are part of the small arsenal of devices needed to provide type-independence to algorithms, something that comes a lot more easily to Python through dynamic typing and easy slicing. I'm barely literate in C++, but I can't see uses for a C++ random access iterator that aren't served in Python by simple indexing (possibly with additional bounds checking) or a Python iterator (possibly over a sliced sequence). The downside, of course, is that you don't have the security provided by static type checking. You pays your money, you takes your choice; preferably, however, you don't do like a friend of mine and try to write FORTRAN in whatever language you're using! -- Rhodri James *-* Wildebeeste Herder to the Masses From mnordhoff at mattnordhoff.com Sat Dec 19 21:18:48 2009 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Sun, 20 Dec 2009 02:18:48 +0000 Subject: using time.gov to get the current time In-Reply-To: <4B2D81B1.3030805@mattnordhoff.com> References: <4B2D81B1.3030805@mattnordhoff.com> Message-ID: <4B2D8988.7090601@mattnordhoff.com> Matt Nordhoff wrote: > Rick wrote: >> Is there any way to get the current time from time.gov using urllib2 or something similar? >> >> Does anyone have any examples of doing this? >> >> Thanks! >> Rick King >> Southfield MI > > Why isn't your local system's clock accurate enough? Bah, I'm better at IRC than e-mail... Anyway: The easiest way to get highly-accurate time is with an "apt-get install ntp" (or your OS's equivalent), and that solves it for all of your applications, not just this one. The time synchronization solutions that exist today are the result of decades of development by experts. If you try to write some solution yourself, it will not be as accurate (though that's okay if it still meets your accuracy requirements), and you're liable to make some mistake* and wind up with a bunch of angry NTP server operators chasing after you with torches and pitchforks. * Such as making excessively-frequent requests, or making more frequent requests if the server appears down, or ignoring NTP Kiss-o'-Death packets. Do not do these things! -- Matt Nordhoff From app at godeck.com Sat Dec 19 21:39:09 2009 From: app at godeck.com (AppRe Godeck) Date: Sat, 19 Dec 2009 20:39:09 -0600 Subject: Anybody use web2py? References: <6oidnWzFKdtK6LHWnZ2dnUVZ_opi4p2d@supernews.com> <320b6ef5-8508-4258-9e70-0d987d77e85f@u7g2000yqm.googlegroups.com> Message-ID: On Sat, 19 Dec 2009 12:48:07 -0800, Yarko wrote: > On Dec 19, 12:42?am, AppRe Godeck wrote: >> Just curious if anybody prefers web2py over django, and visa versa. I >> know it's been discussed on a flame war level a lot. I am looking for a >> more intellectual reasoning behind using one or the other. > > Chevy or Ford? (or whatever pair you prefer) vi or emacs? > ... > > These hold one aspect. > > Hammer or a saw? > > Hold (perhaps) another... > tis the nature of man kind to war. > us.pycon.org, for example, uses both (in reality a mix of the above > argument sets, but at least evidence of the latter: different tools for > different problems). > > From a rapid prototyping perspective, web2py is heavily data-table > efficient: that is, you can define a system, and all the app creation, > form generation and validation have defaults out of the box, and you can > have a "sense" of your data-centric structure in minutes. The same > argument can go against ("how do I get it to do exactly what _I_ want it > to, not what it wants to?") - that is, defaults hide things, and that > has two edges... > > From a layout/user interaction rapid prototyping perspective, web2py is > just entering the waters... > > There is a steady growth of users, and (as you would expect for a young > framework), a lot of changes going on (although backward compatiblity is > a constant mantra when considering changes, that too is a double-edged > thing). > > I find web2py useful, fast, and at times / in areas not as evolved / > flexible as I'd like. BUT I could learn it quickly, and get to work > quickly. > > I have taken an intro Django course (at a PyCon), have built a few > things with it (not nearly as many as I have w/ web2py), and I _can_ do > things in it - so I'll let someone else w/ django "miles" under their > belt speak their mind. > > - Yarko It seems that this is the biggest issue surrounding web2py, from my research, is the ability to customize the defaults (the easy). If all web2py offers is default views, then it may be good for proof of concept projects, however I can't see in my right mind, proofing an application, and then turning around to write it in django because more than the defaults is needed. Thanks for your replies, I was hoping to hear from some django people as well. Especially if you choose django over web2py, and why. If you have time to write, Give a situation where you would prefer to have django over web2py, and then another situation you would prefer web2py over django, and why. Why does web2py have classes that represent HTML? I can't see ever needing to write VIEW code in my controller, since thats what views are for. It seems that even though web2py is fast, supports lots of features, the fact that in the end it gets in the way of doing what you want is it's downfall. Django, even though requiring more "ground work", this ground work becomes a solid foundation on which to build your application on. From davea at ieee.org Sat Dec 19 21:43:30 2009 From: davea at ieee.org (Dave Angel) Date: Sat, 19 Dec 2009 21:43:30 -0500 Subject: Creating Classes In-Reply-To: References: <26848375.post@talk.nabble.com> <4B2C510D.80102@ieee.org> Message-ID: <4B2D8F52.20509@ieee.org> Steve Holden wrote: > Dave Angel wrote: > >> seafoid wrote: >> >>> Hey Guys, >>> >>> I have started to read over classes as a brief respite from my parsing >>> problem. >>> >>> When a class is defined, how does the class access the data upon which >>> the >>> class should act? >>> >>> Example: >>> >>> class Seq: >>> def __init__(self, data, alphabet = Alphabet.generic_alphabet): >>> self.data = data self.alphabet = alphabet >>> >>> def >>> tostring(self): >>> return self.data >>> def tomutable(self): >>> return MutableSeq(self.data, self.alphabet) >>> def count(self, item): >>> return len([x for x in self.data if x == item]) >>> >>> I know what it should do, but have no idea how to feed it the data. >>> >>> Methinks I need to invest in actual computing books as learning from >>> biologists is hazy! >>> >>> Kind regards, >>> Seafoid. >>> >>> >> Steve's message was good, but I feel he kind of jumped in the middle. A >> class is a description of a type of object, and the behaviors and data >> that each instance of the object supports. >> >> You create the object by using the class name like a function call. The >> arguments to that "call" are passed to the __init__ method. >> >> So obj = Seq("abcd") or obj = Seq("defg", "abcdefg") would each >> create an object of the class. But generally, many objects will exist, >> each with different data. >> >> The data in the object is accessed in what appears to be the "self" >> namespace. The name self is just a convention, but it's the first >> argument of each method of the class. So when somebody calls the >> count() method, they pass 'item' a value, but self is used to refer to >> that particular object's data. >> >> So how does 'self' get assigned? That's what Steve was describing. >> When you use the syntax: >> obj.count("value") >> >> you actually call the count method with self referring to "obj" and item >> referring to "value". obj does double-duty here, both defining which >> class' count() method will be called, and also supplying the first >> parameter to the call, the "self" parameter. >> >> There are more complex things that can go on, like creating "bound" >> function objects, but I think this should get you pretty far. >> >> One other point: you should always derive a class from some other >> class, or 'object' by default. So you should being the class definition >> by: >> >> class Seq(object): >> >> Why? It mainly has to do with super(). But in any case if you omit the >> 'object' it's an "old style" class, and that's not even supported in >> 3.x, so it's better to just get in the habit before it matters. >> >> > With respect, unless you have to expound on the differences between the > old-style and the new-style classes (which aren't relevant here) you are > just introducing a red herring by even mentioning it. The average Python > user won't need to use super() in their first year as a Python programmer. > > And, since you brought up Python 3, it's not necessary to explicitly > inherit from object to get new-style classes because, as you correctly > point out, old-style classes don't exist in Python 3. > > I have no idea why you think "you should always derive a class from some > other class". That's pretty unnecessary. > > regards > Steve > I'm not sure why, but since it changes behavior (more than just super()), and since the old behavior is deprecated, I think it's worthwhile to use new-style classes. And although you don't need to explicitly do it in Python 3.x, it does no harm. DaveA From massimodipierro71 at gmail.com Sat Dec 19 22:04:25 2009 From: massimodipierro71 at gmail.com (mdipierro) Date: Sat, 19 Dec 2009 19:04:25 -0800 (PST) Subject: Anybody use web2py? References: <6oidnWzFKdtK6LHWnZ2dnUVZ_opi4p2d@supernews.com> <320b6ef5-8508-4258-9e70-0d987d77e85f@u7g2000yqm.googlegroups.com> Message-ID: > Why does web2py have classes that represent HTML? I can't see ever > needing to write VIEW code in my controller, since thats what views are > for. You do not need to use but if, for example, you want to build a menu recursively, having a server-side presentation of the DOM allows to do it without string manipulation. It is safer and less error prone. Anyway, it is not something you must use. Lots of the features are optional. Like the web based IDE. If you do not like it, you can use the shell like you use Django. > It seems that even though web2py is fast, supports lots of features, the > fact that in the end it gets in the way of doing what you want is it's > downfall. Django, even though requiring more "ground work", this ground > work becomes a solid foundation on which to build your application on. What do you mean by "gets in the way"? Could you provide an example? From sturlamolden at yahoo.no Sat Dec 19 22:53:28 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Sat, 19 Dec 2009 19:53:28 -0800 (PST) Subject: numpy performance and random numbers References: <00b63dbe$0$15654$c3e8da3@news.astraweb.com> <69df23c3-ee4e-4c8f-9d66-581e3e272fad@m38g2000yqd.googlegroups.com> <4b2d36db$1@dnews.tpgi.com.au> <9a71ed3e-de34-4d39-b2d5-66e9ff1baa91@m3g2000yqf.googlegroups.com> <4b2d73ec$1@dnews.tpgi.com.au> Message-ID: <125c6868-6200-42ce-aee0-9c313b006966@b2g2000yqi.googlegroups.com> On 20 Des, 01:46, Lie Ryan wrote: > Not necessarily, you only need to be certain that the two streams don't > overlap in any reasonable amount of time. For that purpose, you can use > a PRNG that have extremely high period like Mersenne Twister and puts > the generators to very distant states. Except there is no way to find two very distant states and prove they are distant enough. From massimodipierro71 at gmail.com Sat Dec 19 23:08:00 2009 From: massimodipierro71 at gmail.com (mdipierro) Date: Sat, 19 Dec 2009 20:08:00 -0800 (PST) Subject: Moving from PHP to Python. Is it Possible References: Message-ID: <7ed0aeef-3756-44c6-857f-82d873df8fc4@d21g2000yqn.googlegroups.com> About you point 3). You may want to look into: http://www.web2py.com/php It translates a PHP page into a web2py template. It is crude and primitive and fails in some cases. Moreover a literal translation is not what you really want since you want to follow a more MVC design. Moreover it will not always maps PHP functions into valid Python/ web2py ones. Yet it may be a useful as a learning tool. I made it to convert Drupal templates into web2py layouts. Massimo On Dec 11, 4:26?am, Sancar Saran wrote: > Greetings. > > I'm 35 yrs old self learner ?and who do daily PHP coding for food more than a > decade. > > After ten years of PHP coding I'm getting bored and give try for learning new > things. > > After 3 days of crawling google, diving in python and cursing, now ?I can show > something on my linux/apache/mod_wsgi setup. > > And i'm struck on something. > > I had CMS design. It works with PHP very well. And I want to transfer my > design in Python. > > My design depends on a Global Array. A huge array which store everything about > requested Web page for a final rendering. > > In PHP accessing globals is easy. You may do direct access or use class > something like ZEND Registry. > > I'm looking for similar facility in python world. > > Also I have couple of questions. > > 1-) Can I create Global (read/write access anywhere from my code) Multi > dimensional, associative array (or hash) and store any kind of variable type. > > 2-) Is there any error trigger for mod_wsgi. When something go bad I god > Internal Server error. Looking for error log was't nice. Is there any way to > shows errors in the web page ? > > 3-) Any documents books sites about helping moving from php to python > > 4-) In php we had someting like > ob_start(); // start Output buffering > require('hede.php'); // include phtml similar to psp. mixed language and html > (to avoiding string replacement (or marker based) html templates) > $var = ob_get_clean(); // get rendered output and use anywhere > > can find a similar abilities in Python ? > > 5-) is there any Python documentation based on examples. When I give up about > to finding ?php's $_REQUEST or $_SERVER equivalents in python some demo code in > Twisted docs are much helpful than any other words. Me and my kind already > have ?problem with English language. Example code much more helpful than full > academic description. > > Thanks for support and patience for this old noob. > > Regards... From steve at REMOVE-THIS-cybersource.com.au Sat Dec 19 23:16:16 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 20 Dec 2009 04:16:16 GMT Subject: Class variables static by default? References: <4b2d735b$1@dnews.tpgi.com.au> Message-ID: <033d925d$0$1305$c3e8da3@news.astraweb.com> On Sun, 20 Dec 2009 11:44:11 +1100, Lie Ryan wrote: > In python, 'class variable' is a variable that belongs to a class; not > to the instance and is shared by all instance that belong to the class. Surely, since string variables are strings, and float variables are floats, and bool variables are bools, and module variables are modules, a class variable will be a class and an instance variable will be an instance? > In contrast, 'instance variable' belongs to the instance, and each > instance can make their instance variables refers to different objects > than the other instances. The usual term used in Python is "class attribute" and "instance attribute" for the named fields of a class or instance. -- Steven From thadeus.nathanial at gmail.com Sat Dec 19 23:21:40 2009 From: thadeus.nathanial at gmail.com (Thadeus Burgess) Date: Sat, 19 Dec 2009 20:21:40 -0800 (PST) Subject: Anybody use web2py? References: <6oidnWzFKdtK6LHWnZ2dnUVZ_opi4p2d@supernews.com> <320b6ef5-8508-4258-9e70-0d987d77e85f@u7g2000yqm.googlegroups.com> Message-ID: <1f7a5a2d-1681-4377-9560-a5d8502d96a1@v25g2000yqk.googlegroups.com> On Dec 19, 8:39?pm, AppRe Godeck wrote: > On Sat, 19 Dec 2009 12:48:07 -0800, Yarko wrote: > > On Dec 19, 12:42?am, AppRe Godeck wrote: > >> Just curious if anybody prefers web2py over django, and visa versa. I > >> know it's been discussed on a flame war level a lot. I am looking for a > >> more intellectual reasoning behind using one or the other. > > > Chevy or Ford? ?(or whatever pair you prefer) vi or emacs? > > ... > > > These hold one aspect. > > > Hammer or a saw? > > > Hold (perhaps) another... > > tis the nature of man kind to war. > > > > > > > us.pycon.org, for example, uses both (in reality a mix of the above > > argument sets, but at least evidence of the latter: different tools for > > different problems). > > > From a rapid prototyping perspective, web2py is heavily data-table > > efficient: that is, you can define a system, and all the app creation, > > form generation and validation have defaults out of the box, and you can > > have a "sense" of your data-centric structure in minutes. ? The same > > argument can go against ("how do I get it to do exactly what _I_ want it > > to, not what it wants to?") - that is, defaults hide things, and ?that > > has two edges... > > > From a layout/user interaction rapid prototyping perspective, web2py is > > just entering the waters... > > > There is a steady growth of users, and (as you would expect for a young > > framework), a lot of changes going on (although backward compatiblity is > > a constant mantra when considering changes, that too is a double-edged > > thing). > > > I find web2py useful, fast, and at times / in areas not as evolved / > > flexible as I'd like. ?BUT I could learn it quickly, and get to work > > quickly. > > > I have taken an intro Django course (at a PyCon), have built a few > > things with it (not nearly as many as I have w/ web2py), and I _can_ do > > things in it - so I'll let someone else w/ django "miles" under their > > belt speak their mind. > > > - Yarko > > It seems that this is the biggest issue surrounding web2py, from my > research, is the ability to customize the defaults (the easy). If all > web2py offers is default views, then it may be good for proof of concept > projects, however I can't see in my right mind, proofing an application, > and then turning around to write it in django because more than the > defaults is needed. > > Thanks for your replies, I was hoping to hear from some django people as > well. Especially if you choose django over web2py, and why. > > If you have time to write, > > Give a situation where you would prefer to have django over web2py, and > then another situation you would prefer web2py over django, and why. > > Why does web2py have classes that represent HTML? I can't see ever > needing to write VIEW code in my controller, since thats what views are > for. > > It seems that even though web2py is fast, supports lots of features, the > fact that in the end it gets in the way of doing what you want is it's > downfall. Django, even though requiring more "ground work", this ground > work becomes a solid foundation on which to build your application on. You need to realize that web2py is still a relatively young framework, issues to certain problems are currently being addressed in web2py. For example, the DAL is being re-written in a much more modular maner, allowing the addition of new database backends to be quite seemless. Other parts of web2py will follow as web2py grows I am sure. I wouldn't disqualify web2py based off what you read, you really need to try it for yourself, and if you run into a problem, I'm sure, some way there is a solution if you bring up the problem, and your problem might even help web2py to grow to be an even better framework. I dare you to try developing a web application with both. Spend one day working on a simple django application, polls, blog, image gallery, family pet tree, you name it. Then take the next day, and write the same application with web2py, and you decide. In the end, both are tools and you need to figure out what is best for YOU. From clp2 at rebertia.com Sat Dec 19 23:28:07 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Sat, 19 Dec 2009 20:28:07 -0800 Subject: Class variables static by default? In-Reply-To: <033d925d$0$1305$c3e8da3@news.astraweb.com> References: <4b2d735b$1@dnews.tpgi.com.au> <033d925d$0$1305$c3e8da3@news.astraweb.com> Message-ID: <50697b2c0912192028u27a09743x32666703d706fda0@mail.gmail.com> On Sat, Dec 19, 2009 at 8:16 PM, Steven D'Aprano wrote: > On Sun, 20 Dec 2009 11:44:11 +1100, Lie Ryan wrote: > >> In python, 'class variable' is a variable that belongs to a class; not >> to the instance and is shared by all instance that belong to the class. > > Surely, since string variables are strings, and float variables are > floats, and bool variables are bools, and module variables are modules, a > class variable will be a class and an instance variable will be an > instance? As they say, the exception proves the rule. :) Cheers, Chris -- http://blog.rebertia.com From anandvaidya.ml at gmail.com Sat Dec 19 23:30:22 2009 From: anandvaidya.ml at gmail.com (Anand Vaidya) Date: Sat, 19 Dec 2009 20:30:22 -0800 (PST) Subject: Anybody use web2py? References: <6oidnWzFKdtK6LHWnZ2dnUVZ_opi4p2d@supernews.com> Message-ID: <0b32658a-b067-4ee6-93ea-ea626384e3f0@z10g2000prh.googlegroups.com> On Dec 19, 2:42?pm, AppRe Godeck wrote: > Just curious if anybody prefers web2py over django, and visa versa. I > know it's been discussed on a flame war level a lot. I am looking for a > more intellectual reasoning behind using one or the other. Hi, I am not very familiar with Django, anyway, my reasons for selecting web2py are: - I believe Django naturally "fits in" to a publishing type of application. web2py seems to be more focussed on being a front-end to "applications" not so much for CMS type or newspaper type publishing. (There is a web2py based wiki/CMS app, though). Though, I agree either could fulfil any of these roles. - Django documentation is vastly superior, including third party books etc. After the v2 Web2py book, we do have solid documentation, but web2py evolves so quickly, there are always things that are documented only on the google groups, slices or wiki. - Many training courses are available pretty much everywhere for Django. Web2py needs to catch up - it will, probably. - Web2py lowers the barrier to entry into python web programming, since it is well thought out and intuitive. The support on the mailing list is fantastic, though I have no idea how good the support for Django is. w2py is easy to pick up for even a python newbie. - Massimo claims about the backward compatibility. I was surprised recently when I took an app I deployed several months (and several versions old) and retested it with the latest SVN code. And it worked fine! Which means, if my client asks for it, I could swap out old w2py with the latest code with no problems. My $0.02 From nsharish.mit at gmail.com Sun Dec 20 00:04:17 2009 From: nsharish.mit at gmail.com (harish anand) Date: Sun, 20 Dec 2009 10:34:17 +0530 Subject: tkinter import problem Message-ID: <6e1fb0a50912192104l20677d1eq9e815422f204d6f3@mail.gmail.com> Hi, I have Mandriva 2010.0 in my laptop. I installed python3.1 from the repository. But i am unable to import tkinter in python console. When I try to import tkinter I get the following error, `ImportError : No module named _tkinter` Am I doing something wrong? Thanks, -------------- next part -------------- An HTML attachment was scrubbed... URL: From anh.hai.trinh at gmail.com Sun Dec 20 01:18:43 2009 From: anh.hai.trinh at gmail.com (Anh Hai Trinh) Date: Sat, 19 Dec 2009 22:18:43 -0800 (PST) Subject: iterators and views of lists References: <89604fb4-9dfa-45f1-a3df-f676cd4353ea@x5g2000prf.googlegroups.com> <87b87511-744c-450e-a024-976f8c57f032@15g2000prz.googlegroups.com> <7a50d745-34e7-4445-ba49-5d8d815ac2ba@l13g2000yqb.googlegroups.com> <8f588225-b78b-4380-b314-cdb2a8c70131@a10g2000pre.googlegroups.com> Message-ID: <6ac93fc2-cd1f-4f7e-9dd1-17203d24b83e@o9g2000prg.googlegroups.com> On Dec 20, 12:04?am, Anh Hai Trinh wrote: > chain: > > ? sorted(itertools.chain(listagent(x)[::2], listagent(y)[-1:1:-2])) > ? [0, 4, 8, 12, 13, 15, 16, 17, 19] > > zip: > > ? sorted(itertools.izip(listagent(z)[1::3], listagent(x)[2::3])) > ? [(452, 16), (758, 4), (898, 10)] I think I mis-interpret Andrei's slides. I think what he meant to sort a chain of slices is such that to move the smaller elements into the first-given slices in-place, thus moving items around whatever lists underlying those slices. And for zip, I think he meant sort the first slice, but moving in- place the items referred by the others in lock-step. From alfps at start.no Sun Dec 20 02:29:43 2009 From: alfps at start.no (Alf P. Steinbach) Date: Sun, 20 Dec 2009 08:29:43 +0100 Subject: Programming intro book ch1 and ch2 (Windows/Python 3) - Request For Comments In-Reply-To: References: Message-ID: * John Posner: > On Fri, 18 Dec 2009 13:00:48 -0500, Alf P. Steinbach > wrote: > >> >> Chapter 2 is about Basic Concepts (of programming). It's the usual: >> variables, ... > > 1. Overall suggestion > > You have a tendency to include non-pertinent asides [1]. But then, > rambling a bit endows a manuscript with the author's distinctive voice. > Fortunately, we live in a hypertext-enabled world, where you can have > your cake and eat it, too. I suggest that you go over your manuscript > with a ruthless eye, and turn your rambles into hypertext-accessible > "sidebars". See how much you can reduce the length of Chapter 2, which > current runs 98 pages! He he. :-) You're right, although the examples you chose were not as I see it rambles, just short asides within sentences; useful concrete examples; and general background. I do have a tendency to apparently ramble, especially about technical details and consequences -- it's not arbitrary but an attempt to bring in important consequences and/or some more fundamental unifying view. I tried to discipline myself to not do that, to just let go, to let /the reader/ replace arbitrary rules with understanding, in time. Like, you don't really need to understand the physics to do hammering. Even though even a rough understanding of the physics can help you avoid looking like an effeminate Hollywood movie star acting out hammering, can help you avoid getting hurt, can get the job done much faster, and can help you in other situations! But I'll try even harder. :-) > 2. Comments on Section 2.6.7, "References & automatic garbage collection" > > There's a spell-check evader on page 2:49: "trough" s.b. "through". And > your spell-checker should have caught "adressable" on page 2:48. Sad to say, I'm not using a spell checker. The reason is that for me, in /most/ cases the speling erors marked by Word's spell checker are not speling erors. The beast is Just Wrong. And it's Wrong-Headed, insisting on "fixing" perfectly correct text. For example, replacing "southeast" with "southwest" (now, what the **** does Word's spell checker know about geography? Nothing!) Even worse, as soon as that beast just gets its little toe inside the door, it tends to invite in its friends the Grammar Checker and the Auto Formatter. Which feel free to not only report what they see as improvements, but to just change the text! So, thanks! Will be fixed. > I find your sequence-of-attribute-lookups approach to the topic of > "variable assignment" interesting. The directed-graph illustration on > page 2:49 even hints at the fact that in the world of Python, names > ("turtle", "forward", etc.) and objects (various kinds of yellow boxes) > are very different things. > > (I suggest getting rid of the callout "Very small fixed size variable". > That way, only objects, not names, have the italicized callouts.) > > But using the term "references" and the directed-graph metaphor has its > drawbacks. Avoiding the term "reference" will make it easier to navigate > the turbulent waters of call-by-reference vs. call-by-value vs. > call-by-name. (You don't even stick a toe in those waters in Section > 2.7.5.) Combining memory addresses with the directed graph metaphor > invites the reader to think at way too low a level, IMHO. Uhm, discussing call-by-name would really be rambling & anecdotal. AFAIK no real programming language has had that since Algol, where it was introduced by a too unclear spec implemented literally (i.e., lack of 2-way communication within the team introduced a "feature"!). Or am I misunderstanding what you mean? It's True, as you note, that people tend to get confused. I recently (just weeks ago) was astounded to see that a C++ "expert" thought that Java had pass by reference, apparently because in Java only references are passed around. But I think the cure for that is not to draw a veil over the things that can confuse, such as avoiding the word "reference", but rather to just discuss the reality. That is, I think argument passing & associated terminology is not more complicated than even my mom could understand, if she put her politician's mind to it. Certainly, anyone young enough won't have any problem. I believe... ;-) [snip] > I hope these comments help. Yes, thanks, - Alf From victorsubervi at gmail.com Sun Dec 20 03:56:46 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Sun, 20 Dec 2009 03:56:46 -0500 Subject: How Do I...? In-Reply-To: <4B2D780A.8070801@python.org> References: <4dc0cfea0912181055o4da24927n4776b197efd5943@mail.gmail.com> <4B2BE024.4010307@tim.thechases.com> <4dc0cfea0912190210h3be56c85r34dbb93c672519cb@mail.gmail.com> <4B2CEFC6.8000801@tim.thechases.com> <4dc0cfea0912190850kec7b3a2ice9cac3356cc221a@mail.gmail.com> <4B2D780A.8070801@python.org> Message-ID: <4dc0cfea0912200056l1b8d8e34p58d7f5d7b243c06e@mail.gmail.com> On Sat, Dec 19, 2009 at 8:04 PM, Steve Holden, Chairman, PSF < chairman at python.org> wrote: > Well, if we were looking for arrogance we could easily interpret that > last statement as such. Please remember that although we are mainly > left-brain types on this list some of us do have artistic and musical > skills. Some people will therefore probably be closer to your conception > than you anticipate (though I confess I am unlikely to be one of them). > Go here: http://logos.13gems.com/ if you really want to understand what I mean. It's not arrogance. It's the recognition that I simply haven't met anyone who can penetrate what I've discovered, even though I prove it factually, and it requires heavy right-brain functionality. Even that book is but a glimpse into what I've seen. Tim is correct, the Python list is a pretty friendly place as far as > netiquette standards go, and I am happy this thread didn't just turn > into ugly name calling (which it could have with a less adult approach > by the participants). > Good work, Steve! Two cheers! BTW, since I see I'm dealing with the chairman of this organization, many years ago I got booted off this list because (apparently) whoever was in charge of the list at that time decided to boot me off when the people running the Zope list booted me off, apparently because of my difficulties with programming. I didn't deserve to be booted off the Zope list, much less this one! Ever since then, I've been signing up under different pseudonames, the latest of which is "Victor Subervi". My legal name (changed to) is actually "beno". I would prefer to re-sign up under that. May I? If not, I'll put Victor out of his misery and create another fictitious character. Silly game I've had to play. Indeed, the whole concept of booting people off lists is absurd on its face. The approach I see in your post indicates a much more practical approach based in a profound level of maturity. Let me know. beno -------------- next part -------------- An HTML attachment was scrubbed... URL: From stef.mientki at gmail.com Sun Dec 20 04:35:08 2009 From: stef.mientki at gmail.com (Stef Mientki) Date: Sun, 20 Dec 2009 10:35:08 +0100 Subject: how do I set a Python installation as the default under windows ? In-Reply-To: <4B2D6DCD.8080108@holdenweb.com> References: <4B2D0451.9080000@gmail.com> <4B2D6DCD.8080108@holdenweb.com> Message-ID: <4B2DEFCC.4080607@gmail.com> Steve Holden wrote: > Stef Mientki wrote: > >> hello, >> >> I just upgraded from Python 2.5 to 2.6. >> Most of the things work, >> but I'm struggling with one issue, >> when I start Python in a command window, >> it still uses Python 2.5. >> >> Is there a way to get Python 2.6 as my default Python environment ? >> >> thanks, >> Stef Mientki >> > > It's a matter of replacing C:\Python25 with C:\Python26 in your PATH > environment variable, which is what the Windows command processor uses > to fined executable programs. Thanks Steve, that works exactly as you say. cheers, Stef > It's normal to add both the directory the > interpreter lives in /and/ its Scripts subdirectory, so you may have > two replacements to make. See > > http://www.python.org/doc/faq/windows/ > > for more. If anyone has any good updates to that document I'll be happy > to make them (or give you permission to make them ...). It was written a > long time ago, and I'm not sure it's had much love. In particular > there'll not be anything relating to Windows 7. > > regards > Steve > -------------- next part -------------- An HTML attachment was scrubbed... URL: From lie.1296 at gmail.com Sun Dec 20 04:47:39 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Sun, 20 Dec 2009 20:47:39 +1100 Subject: numpy performance and random numbers In-Reply-To: <125c6868-6200-42ce-aee0-9c313b006966@b2g2000yqi.googlegroups.com> References: <00b63dbe$0$15654$c3e8da3@news.astraweb.com> <69df23c3-ee4e-4c8f-9d66-581e3e272fad@m38g2000yqd.googlegroups.com> <4b2d36db$1@dnews.tpgi.com.au> <9a71ed3e-de34-4d39-b2d5-66e9ff1baa91@m3g2000yqf.googlegroups.com> <4b2d73ec$1@dnews.tpgi.com.au> <125c6868-6200-42ce-aee0-9c313b006966@b2g2000yqi.googlegroups.com> Message-ID: <4b2df2be$1@dnews.tpgi.com.au> On 12/20/2009 2:53 PM, sturlamolden wrote: > On 20 Des, 01:46, Lie Ryan wrote: > >> Not necessarily, you only need to be certain that the two streams don't >> overlap in any reasonable amount of time. For that purpose, you can use >> a PRNG that have extremely high period like Mersenne Twister and puts >> the generators to very distant states. > > Except there is no way to find two very distant states and prove they > are distant enough. > Except only theoretical scientist feel the need to prove it and perhaps perhaps for cryptographic-level security. Random number for games, random number for tmp files, and 99.99% random number users doesn't really need such proves. And don't forget the effect of the very long period of PRNG like Mersenne Twister (2**19937 ? 1, according to Wikipedia) makes it very unlikely to choose two different seeds and ended up in nearby entry point. Let's just assume we're using a 2**64-bit integer as the seeds and let's assume the entry point defined by these seeds are uniformly distributed you would to generate (on average) 2.34E+5982 numbers before you clashes with the nearest entry point. Such amount of numbers would require decades to generate. Your seed generator guard would only need to prevent seeding parallel generators with the same seed (which is disastrous), and that's it, the big period covers everything else. From steve at REMOVE-THIS-cybersource.com.au Sun Dec 20 04:58:02 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 20 Dec 2009 09:58:02 GMT Subject: Programming intro book ch1 and ch2 (Windows/Python 3) - Request For Comments References: Message-ID: <033de276$0$1289$c3e8da3@news.astraweb.com> On Sun, 20 Dec 2009 08:29:43 +0100, Alf P. Steinbach wrote: > I recently (just weeks > ago) was astounded to see that a C++ "expert" thought that Java had pass > by reference, apparently because in Java only references are passed > around. The Java community, for some bizarre reason, has a tendency to describe Java's argument passing model (which is identical to Python's) as "pass by reference" even though it is nothing like pass by reference in languages that actually have it (such as Pascal). There is nothing so simple that it can't be totally confused by sufficiently stupid terminology. -- Steven From victorsubervi at gmail.com Sun Dec 20 05:06:20 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Sun, 20 Dec 2009 05:06:20 -0500 Subject: Something Like os.environ['HTTP_REFERER'] Message-ID: <4dc0cfea0912200206s2fbbfb26pd015b7be7e88b570@mail.gmail.com> Hi; I'm looking for something like os.environ['HTTP_REFERER'] but for python scripts. That is, if I have a script that is imported by another script, how can I have the script that is being imported determine which script imported it? TIA, Victor -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVE-THIS-cybersource.com.au Sun Dec 20 05:15:41 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 20 Dec 2009 10:15:41 GMT Subject: Class variables static by default? References: <4b2d735b$1@dnews.tpgi.com.au> <033d925d$0$1305$c3e8da3@news.astraweb.com> Message-ID: <033de698$0$1289$c3e8da3@news.astraweb.com> On Sat, 19 Dec 2009 20:28:07 -0800, Chris Rebert wrote: >> Surely, since string variables are strings, and float variables are >> floats, and bool variables are bools, and module variables are modules, >> a class variable will be a class and an instance variable will be an >> instance? > > As they say, the exception proves the rule. :) http://www.worldwidewords.org/qa/qa-exc1.htm -- Steven From clp2 at rebertia.com Sun Dec 20 05:18:20 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 20 Dec 2009 02:18:20 -0800 Subject: Something Like os.environ['HTTP_REFERER'] In-Reply-To: <4dc0cfea0912200206s2fbbfb26pd015b7be7e88b570@mail.gmail.com> References: <4dc0cfea0912200206s2fbbfb26pd015b7be7e88b570@mail.gmail.com> Message-ID: <50697b2c0912200218j1966d811m42e4ccb04bdc1ba6@mail.gmail.com> On Sun, Dec 20, 2009 at 2:06 AM, Victor Subervi wrote: > Hi; > I'm looking for something like os.environ['HTTP_REFERER'] but for python > scripts. That is, if I have a script that is imported by another script, how > can I have the script that is being imported determine which script imported > it? Allow me to ask the meta-question of: Why do you want to do that? There is quite possibly a better means to accomplish whatever end you have. Cheers, Chris -- http://blog.rebertia.com From lord_eldritch at yahoo.co.uk Sun Dec 20 05:46:02 2009 From: lord_eldritch at yahoo.co.uk (Lord Eldritch) Date: Sun, 20 Dec 2009 11:46:02 +0100 Subject: Mails & encoding Message-ID: I have a CGI written in Python to process a form a read/write a text file (a minimal database). It runs in a Linux box with and it looks all the encoding is UTF8. Now I have two questions: - When I have: ttext='??????????' I get a warning sendinme to this page http://www.python.org/peps/pep-0263.html Should I understand that PEP has been already implemented and follow it? - Related to the former one: the CGI sends an email with stress marks and other characters. I can read it with out any problem in my Kmail client because it detects the encoding. But I saw that most of the users are gonna read it in a webmail service where the characters (UTF8) are not recognized. Can I force a encoding when I send an email? kind of: mail(adress,'My title', mytext.encode'iso9865') Thanks in advance. -- Lord Eldritch From clp2 at rebertia.com Sun Dec 20 05:54:08 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 20 Dec 2009 02:54:08 -0800 Subject: Mails & encoding In-Reply-To: References: Message-ID: <50697b2c0912200254p2ac68486vdb69c14155f6da63@mail.gmail.com> On Sun, Dec 20, 2009 at 2:46 AM, Lord Eldritch wrote: > - When I have: > > ttext='??????????' > > I get a warning sendinme to this page > > http://www.python.org/peps/pep-0263.html > > Should I understand that PEP has been already implemented and follow it? Yes. Cheers, Chris -- http://blog.rebertia.com From victorsubervi at gmail.com Sun Dec 20 06:05:55 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Sun, 20 Dec 2009 06:05:55 -0500 Subject: Something Like os.environ['HTTP_REFERER'] In-Reply-To: <50697b2c0912200218j1966d811m42e4ccb04bdc1ba6@mail.gmail.com> References: <4dc0cfea0912200206s2fbbfb26pd015b7be7e88b570@mail.gmail.com> <50697b2c0912200218j1966d811m42e4ccb04bdc1ba6@mail.gmail.com> Message-ID: <4dc0cfea0912200305m1f446bc5v13b309ca4d306c7e@mail.gmail.com> On Sun, Dec 20, 2009 at 5:18 AM, Chris Rebert wrote: > On Sun, Dec 20, 2009 at 2:06 AM, Victor Subervi > wrote: > > Hi; > > I'm looking for something like os.environ['HTTP_REFERER'] but for python > > scripts. That is, if I have a script that is imported by another script, > how > > can I have the script that is being imported determine which script > imported > > it? > > Allow me to ask the meta-question of: Why do you want to do that? > There is quite possibly a better means to accomplish whatever end you have. > I'm writing a shopping cart in which I'm automating as much as is possible. The problem is that certain kinds of shopping carts have certain peculiar needs that must be accommodated. For example, a shopping cart for pharmaceuticals requires authentication and identification of the visitor before serving the "products" available to the visitor and specific to the visitor (their prescriptions); the jewelry shopping cart I'm building will enable automatic pricing updates based on the spot prices of the various metals. I've realized that I can call specific programs from the pages where these special functionalities will need to be incorporated and then programmatically do the necessary. Of course, I can pass the page name as a parameter, but that's not elegant. TIA, V -------------- next part -------------- An HTML attachment was scrubbed... URL: From xenoszh at gmail.com Sun Dec 20 06:21:46 2009 From: xenoszh at gmail.com (Parker) Date: Sun, 20 Dec 2009 03:21:46 -0800 (PST) Subject: py itertools? References: <4b2cb101$0$1112$4fafbaef@reader1.news.tin.it> Message-ID: >>> a = 'qwerty' >>> b = '^%&$#' >>> c = [(x,y) for x in a for y in b] >>> c [('q', '^'), ('q', '%'), ('q', '&'), ('q', '$'), ('q', '#'), ('w', '^'), ('w', '%'), ('w', '&'), ('w', '$'), ('w', '#'), ('e', '^'), ('e', '%'), ('e', '&'), ('e', '$'), ('e', '#'), ('r', '^'), ('r', '%'), ('r', '&'), ('r', '$'), ('r', '#'), ('t', '^'), ('t', '%'), ('t', '&'), ('t', '$'), ('t', '#'), ('y', '^'), ('y', '%'), ('y', '&'), ('y', '$'), ('y', '#')] This one is better and simple. On Dec 19, 12:48?pm, Chris Rebert wrote: > On Sat, Dec 19, 2009 at 2:54 AM, mattia wrote: > > Hi all, I need to create the permutation of two strings but without > > repeat the values, e.g. 'ab' for me is equal to 'ba'. Here is my > > solution, but maybe the python library provides something better: > > >>>> def mcd(a, b): > > ... ? ? if b == 0: > > ... ? ? ? ? return a > > ... ? ? else: > > ... ? ? ? ? return mcd(b, a % b) > > ... > >>>> def mcm(a, b): > > ... ? ? return int((a * b) / mcd(a, b)) > > ... > >>>> s1 = 'abc' > >>>> s2 = 'wt' > >>>> m = mcm(len(s1), len(s2)) > >>>> set(zip(s1*m, s2*m)) > > {('a', 'w'), ('a', 't'), ('b', 'w'), ('c', 't'), ('b', 't'), ('c', 'w')} > > > Any help? > > Surprised you didn't think of the seemingly obvious approach: > > def permute_chars(one, two): > ? ? for left in set(one): > ? ? ? ? for right in set(two): > ? ? ? ? ? ? yield (left, right) > > >>> list(permute_chars('abc', 'wt')) > > [('a', 'w'), ('a', 't'), ('b', 'w'), ('b', 't'), ('c', 'w'), ('c', 't')] > > Cheers, > Chris > --http://blog.rebertia.com From victorsubervi at gmail.com Sun Dec 20 06:34:13 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Sun, 20 Dec 2009 06:34:13 -0500 Subject: Import Problem Message-ID: <4dc0cfea0912200334g4c190eaag3fb177ef352f3b24@mail.gmail.com> Hi; I have this import statement: from particulars import storePrimaryStandAlone, addStore, ourStores particulars.py has this code: def addStore(): return 'jewelry' def ourStores(): return ['products', 'prescriptions'] def storePrimaryStandAlone(): return 'prescriptions' But I get this error: /var/www/html/angrynates.com/cart/createTables2.py 263 264 ''' 265 266 createTables2() 267 createTables2 = /var/www/html/angrynates.com/cart/createTables2.py in createTables2() 105 these.append(basic) 106 i = 0 107 specialtyStore = addStore() 108 addStore = [] 109 addStore.append(specialtyStore) specialtyStore undefined, global addStore = UnboundLocalError: local variable 'addStore' referenced before assignment args = ("local variable 'addStore' referenced before assignment",) What's strange is that it imports ourStores just fine. but even if I copy ourStores to addStore the latter doesn't get imported! Why? Now, I've worked around this problem by just importing all of particulars, but why did my import fail? TIA, Victor -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Sun Dec 20 06:43:36 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 20 Dec 2009 03:43:36 -0800 Subject: Import Problem In-Reply-To: <4dc0cfea0912200334g4c190eaag3fb177ef352f3b24@mail.gmail.com> References: <4dc0cfea0912200334g4c190eaag3fb177ef352f3b24@mail.gmail.com> Message-ID: <50697b2c0912200343l430ba2d0u4c03bcce922ab83e@mail.gmail.com> On Sun, Dec 20, 2009 at 3:34 AM, Victor Subervi wrote: > But I get this error: > > /var/www/html/angrynates.com/cart/createTables2.py > ? 263 > ? 264 ''' > ? 265 > ? 266 createTables2() > ? 267 > createTables2 = > ?/var/www/html/angrynates.com/cart/createTables2.py in createTables2() > ? 105???? these.append(basic) > ? 106?? i = 0 > ? 107?? specialtyStore = addStore() > ? 108?? addStore = [] Rename this list so its name isn't the same as the addStore() function which you call. For more info, see: http://groups.google.com/group/comp.lang.python/browse_thread/thread/46b4c8af3196caaa?pli=1 > ? 109?? addStore.append(specialtyStore) > specialtyStore undefined, global addStore = > > UnboundLocalError: local variable 'addStore' referenced before assignment > ????? args = ("local variable 'addStore' referenced before assignment",) Cheers, Chris -- http://blog.rebertia.com From clp2 at rebertia.com Sun Dec 20 06:49:35 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 20 Dec 2009 03:49:35 -0800 Subject: py itertools? In-Reply-To: References: <4b2cb101$0$1112$4fafbaef@reader1.news.tin.it> Message-ID: <50697b2c0912200349v7186a0b0vaf5bd9dc8fc56c94@mail.gmail.com> > On Dec 19, 12:48?pm, Chris Rebert wrote: >> On Sat, Dec 19, 2009 at 2:54 AM, mattia wrote: >> > Hi all, I need to create the permutation of two strings but without >> > repeat the values, e.g. 'ab' for me is equal to 'ba'. Here is my >> > solution, but maybe the python library provides something better: >> >> >>>> def mcd(a, b): >> > ... ? ? if b == 0: >> > ... ? ? ? ? return a >> > ... ? ? else: >> > ... ? ? ? ? return mcd(b, a % b) >> > ... >> >>>> def mcm(a, b): >> > ... ? ? return int((a * b) / mcd(a, b)) >> > ... >> >>>> s1 = 'abc' >> >>>> s2 = 'wt' >> >>>> m = mcm(len(s1), len(s2)) >> >>>> set(zip(s1*m, s2*m)) >> > {('a', 'w'), ('a', 't'), ('b', 'w'), ('c', 't'), ('b', 't'), ('c', 'w')} >> >> > Any help? >> >> Surprised you didn't think of the seemingly obvious approach: >> >> def permute_chars(one, two): >> ? ? for left in set(one): >> ? ? ? ? for right in set(two): >> ? ? ? ? ? ? yield (left, right) >> >> >>> list(permute_chars('abc', 'wt')) >> >> [('a', 'w'), ('a', 't'), ('b', 'w'), ('b', 't'), ('c', 'w'), ('c', 't')] On Sun, Dec 20, 2009 at 3:21 AM, Parker wrote: >>>> a = 'qwerty' >>>> b = '^%&$#' >>>> c = [(x,y) for x in a for y in b] >>>> c > [('q', '^'), ('q', '%'), ('q', '&'), ('q', '$'), ('q', '#'), ('w', > '^'), ('w', '%'), ('w', '&'), ('w', '$'), ('w', '#'), ('e', '^'), > ('e', '%'), ('e', '&'), ('e', '$'), ('e', '#'), ('r', '^'), ('r', > '%'), ('r', '&'), ('r', '$'), ('r', '#'), ('t', '^'), ('t', '%'), > ('t', '&'), ('t', '$'), ('t', '#'), ('y', '^'), ('y', '%'), ('y', > '&'), ('y', '$'), ('y', '#')] > > > This one is better and simple. But fails if either of the input strings has repeated characters. (Although writing it as a comprehension is indeed much briefer.) Whether this matters, who knows, since the OP's spec for the function was rather vague... Cheers, Chris -- http://blog.rebertia.com From qq263020776 at gmail.com Sun Dec 20 07:24:57 2009 From: qq263020776 at gmail.com (yousay) Date: Sun, 20 Dec 2009 04:24:57 -0800 (PST) Subject: tarfiles usage on python 2.4.4 References: <205e4ce0-adda-4153-aa4f-d18eecefca40@z40g2000vba.googlegroups.com> Message-ID: <101268d0-325b-428a-9ca1-5ed41f1e8588@g1g2000pra.googlegroups.com> On Dec 19, 9:27?am, tekion wrote: > All, > I am using tarfile module and my python is version 2.4.4. ?When I call > method extractall, I am getting error method does not exist. Could > someone confirm if the method exist on python 2.4.4? Thanks dir(tarfile) check if is exist From gervaz at gmail.com Sun Dec 20 07:45:40 2009 From: gervaz at gmail.com (mattia) Date: 20 Dec 2009 12:45:40 GMT Subject: console command to get the path of a function Message-ID: <4b2e1c74$0$1113$4fafbaef@reader1.news.tin.it> Hi all, is there a way in the python shell to list the path of a library function (in order to look at the source code?). Thanks, Mattia From steve at holdenweb.com Sun Dec 20 07:46:17 2009 From: steve at holdenweb.com (Steve Holden) Date: Sun, 20 Dec 2009 07:46:17 -0500 Subject: How Do I...? In-Reply-To: <4dc0cfea0912200056l1b8d8e34p58d7f5d7b243c06e@mail.gmail.com> References: <4dc0cfea0912181055o4da24927n4776b197efd5943@mail.gmail.com> <4B2BE024.4010307@tim.thechases.com> <4dc0cfea0912190210h3be56c85r34dbb93c672519cb@mail.gmail.com> <4B2CEFC6.8000801@tim.thechases.com> <4dc0cfea0912190850kec7b3a2ice9cac3356cc221a@mail.gmail.com> <4B2D780A.8070801@python.org> <4dc0cfea0912200056l1b8d8e34p58d7f5d7b243c06e@mail.gmail.com> Message-ID: <4B2E1C99.3090804@holdenweb.com> Victor Subervi wrote: > On Sat, Dec 19, 2009 at 8:04 PM, Steve Holden, Chairman, PSF > > wrote: > > Well, if we were looking for arrogance we could easily interpret that > last statement as such. Please remember that although we are mainly > left-brain types on this list some of us do have artistic and musical > skills. Some people will therefore probably be closer to your conception > than you anticipate (though I confess I am unlikely to be one of them). > > > Go here: > http://logos.13gems.com/ > if you really want to understand what I mean. It's not arrogance. It's > the recognition that I simply haven't met anyone who can penetrate what > I've discovered, even though I prove it factually, and it requires heavy > right-brain functionality. Even that book is but a glimpse into what > I've seen. > > Tim is correct, the Python list is a pretty friendly place as far as > netiquette standards go, and I am happy this thread didn't just turn > into ugly name calling (which it could have with a less adult approach > by the participants). > > > Good work, Steve! Two cheers! BTW, since I see I'm dealing with the > chairman of this organization, many years ago I got booted off this list > because (apparently) whoever was in charge of the list at that time > decided to boot me off when the people running the Zope list booted me > off, apparently because of my difficulties with programming. I didn't > deserve to be booted off the Zope list, much less this one! Ever since > then, I've been signing up under different pseudonames, the latest of > which is "Victor Subervi". My legal name (changed to) is actually > "beno". I would prefer to re-sign up under that. May I? If not, I'll put > Victor out of his misery and create another fictitious character. Silly > game I've had to play. Indeed, the whole concept of booting people off > lists is absurd on its face. The approach I see in your post indicates a > much more practical approach based in a profound level of maturity. Let > me know. > beno I'm not aware that the python-list is subject to that kind of censorship. I don't see why you can't subscribe under any name you want, and I'm certainly not aware of any banning mechanism. However, you over-estimate the powers of the PSF chairman if you think I have anything to do with who gets to use the mailing list and who doesn't ... regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 PyCon is coming! Atlanta, Feb 2010 http://us.pycon.org/ Holden Web LLC http://www.holdenweb.com/ UPCOMING EVENTS: http://holdenweb.eventbrite.com/ From nobody at nowhere.org Sun Dec 20 07:50:31 2009 From: nobody at nowhere.org (Georg) Date: Sun, 20 Dec 2009 13:50:31 +0100 Subject: C Structure rebuild with ctypes Message-ID: <7p6ksnFkg1U1@mid.individual.net> Hi All, I need to use a library written in C. The routine "int func (int handle, int *numVars, char ***varNames, int **varTypes)" expects a complex object: " ... Variable names are structured as an array of *numVars pointers, each pointing to a char string containing a variable name, and *varNames is set to point to the first element of the array. Variable types are stored into a corresponding array of *numVars in elements, and *varTypes is set to point to the first element of the array." I tried using ctypes but nothing worked, e.g. "varNames = (c_char_p(c_char * 65) * NumberOfVariables)()" Can anyboby help? How do I have to state the structure "array of pointers to char string"? How is a pointer to the first element of such an array defined using ctypes? How do I allocate enough space for the char the array points to? Best regards Georg From irmen.NOSPAM at xs4all.nl Sun Dec 20 07:53:18 2009 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Sun, 20 Dec 2009 13:53:18 +0100 Subject: console command to get the path of a function In-Reply-To: <4b2e1c74$0$1113$4fafbaef@reader1.news.tin.it> References: <4b2e1c74$0$1113$4fafbaef@reader1.news.tin.it> Message-ID: <4b2e1e3d$0$22913$e4fe514c@news.xs4all.nl> On 12/20/2009 1:45 PM, mattia wrote: > Hi all, is there a way in the python shell to list the path of a library > function (in order to look at the source code?). > > Thanks, Mattia something like this? >>> import inspect >>> import os >>> inspect.getsourcefile(os.path.split) 'C:\\Python26\\lib\\ntpath.py' >>> print inspect.getsource(os.path.split) def split(p): """Split a pathname. ... ... --irmen From gervaz at gmail.com Sun Dec 20 08:03:29 2009 From: gervaz at gmail.com (mattia) Date: 20 Dec 2009 13:03:29 GMT Subject: py itertools? References: <4b2cb101$0$1112$4fafbaef@reader1.news.tin.it> Message-ID: <4b2e20a1$0$1104$4fafbaef@reader3.news.tin.it> Il Sun, 20 Dec 2009 03:49:35 -0800, Chris Rebert ha scritto: >> On Dec 19, 12:48?pm, Chris Rebert wrote: >>> On Sat, Dec 19, 2009 at 2:54 AM, mattia wrote: >>> > Hi all, I need to create the permutation of two strings but without >>> > repeat the values, e.g. 'ab' for me is equal to 'ba'. Here is my >>> > solution, but maybe the python library provides something better: >>> >>> >>>> def mcd(a, b): >>> > ... ? ? if b == 0: >>> > ... ? ? ? ? return a >>> > ... ? ? else: >>> > ... ? ? ? ? return mcd(b, a % b) >>> > ... >>> >>>> def mcm(a, b): >>> > ... ? ? return int((a * b) / mcd(a, b)) ... >>> >>>> s1 = 'abc' >>> >>>> s2 = 'wt' >>> >>>> m = mcm(len(s1), len(s2)) >>> >>>> set(zip(s1*m, s2*m)) >>> > {('a', 'w'), ('a', 't'), ('b', 'w'), ('c', 't'), ('b', 't'), ('c', >>> > 'w')} >>> >>> > Any help? >>> >>> Surprised you didn't think of the seemingly obvious approach: >>> >>> def permute_chars(one, two): >>> ? ? for left in set(one): >>> ? ? ? ? for right in set(two): >>> ? ? ? ? ? ? yield (left, right) >>> >>> >>> list(permute_chars('abc', 'wt')) >>> >>> [('a', 'w'), ('a', 't'), ('b', 'w'), ('b', 't'), ('c', 'w'), ('c', >>> 't')] > > On Sun, Dec 20, 2009 at 3:21 AM, Parker wrote: >>>>> a = 'qwerty' >>>>> b = '^%&$#' >>>>> c = [(x,y) for x in a for y in b] >>>>> c >> [('q', '^'), ('q', '%'), ('q', '&'), ('q', '$'), ('q', '#'), ('w', >> '^'), ('w', '%'), ('w', '&'), ('w', '$'), ('w', '#'), ('e', '^'), ('e', >> '%'), ('e', '&'), ('e', '$'), ('e', '#'), ('r', '^'), ('r', '%'), ('r', >> '&'), ('r', '$'), ('r', '#'), ('t', '^'), ('t', '%'), ('t', '&'), ('t', >> '$'), ('t', '#'), ('y', '^'), ('y', '%'), ('y', '&'), ('y', '$'), ('y', >> '#')] >> >> >> This one is better and simple. > > But fails if either of the input strings has repeated characters. > (Although writing it as a comprehension is indeed much briefer.) > > Whether this matters, who knows, since the OP's spec for the function > was rather vague... > > Cheers, > Chris Having non-repeating values metter. From gervaz at gmail.com Sun Dec 20 08:08:21 2009 From: gervaz at gmail.com (mattia) Date: 20 Dec 2009 13:08:21 GMT Subject: console command to get the path of a function References: <4b2e1c74$0$1113$4fafbaef@reader1.news.tin.it> <4b2e1e3d$0$22913$e4fe514c@news.xs4all.nl> Message-ID: <4b2e21c5$0$1104$4fafbaef@reader3.news.tin.it> Il Sun, 20 Dec 2009 13:53:18 +0100, Irmen de Jong ha scritto: > On 12/20/2009 1:45 PM, mattia wrote: >> Hi all, is there a way in the python shell to list the path of a >> library function (in order to look at the source code?). >> >> Thanks, Mattia > > something like this? > > >>> import inspect > >>> import os > >>> inspect.getsourcefile(os.path.split) > 'C:\\Python26\\lib\\ntpath.py' > >>> print inspect.getsource(os.path.split) > def split(p): > """Split a pathname. > ... > ... > > > --irmen Perfect, thank you. From gervaz at gmail.com Sun Dec 20 08:13:43 2009 From: gervaz at gmail.com (mattia) Date: 20 Dec 2009 13:13:43 GMT Subject: console command to get the path of a function References: <4b2e1c74$0$1113$4fafbaef@reader1.news.tin.it> <4b2e1e3d$0$22913$e4fe514c@news.xs4all.nl> Message-ID: <4b2e2306$0$1104$4fafbaef@reader3.news.tin.it> Il Sun, 20 Dec 2009 13:53:18 +0100, Irmen de Jong ha scritto: > On 12/20/2009 1:45 PM, mattia wrote: >> Hi all, is there a way in the python shell to list the path of a >> library function (in order to look at the source code?). >> >> Thanks, Mattia > > something like this? > > >>> import inspect > >>> import os > >>> inspect.getsourcefile(os.path.split) > 'C:\\Python26\\lib\\ntpath.py' > >>> print inspect.getsource(os.path.split) > def split(p): > """Split a pathname. > ... > ... > > > --irmen Ok, but how can I retrieve information about built-in functions (if any)? >>> inspect.getsourcefile(itertools.product) Traceback (most recent call last): File "", line 1, in File "C:\Python31\lib\inspect.py", line 439, in getsourcefile filename = getfile(object) File "C:\Python31\lib\inspect.py", line 406, in getfile raise TypeError('arg is a built-in class') TypeError: arg is a built-in class From __peter__ at web.de Sun Dec 20 08:30:21 2009 From: __peter__ at web.de (Peter Otten) Date: Sun, 20 Dec 2009 14:30:21 +0100 Subject: console command to get the path of a function References: <4b2e1c74$0$1113$4fafbaef@reader1.news.tin.it> <4b2e1e3d$0$22913$e4fe514c@news.xs4all.nl> <4b2e2306$0$1104$4fafbaef@reader3.news.tin.it> Message-ID: mattia wrote: > Il Sun, 20 Dec 2009 13:53:18 +0100, Irmen de Jong ha scritto: > >> On 12/20/2009 1:45 PM, mattia wrote: >>> Hi all, is there a way in the python shell to list the path of a >>> library function (in order to look at the source code?). >>> >>> Thanks, Mattia >> >> something like this? >> >> >>> import inspect >> >>> import os >> >>> inspect.getsourcefile(os.path.split) >> 'C:\\Python26\\lib\\ntpath.py' >> >>> print inspect.getsource(os.path.split) >> def split(p): >> """Split a pathname. >> ... >> ... >> >> >> --irmen > > Ok, but how can I retrieve information about built-in functions (if any)? > >>>> inspect.getsourcefile(itertools.product) > Traceback (most recent call last): > File "", line 1, in > File "C:\Python31\lib\inspect.py", line 439, in getsourcefile > filename = getfile(object) > File "C:\Python31\lib\inspect.py", line 406, in getfile > raise TypeError('arg is a built-in class') > TypeError: arg is a built-in class To get to the source of functions written in C you have to download the source distribution, or you can browse the subversion tree: http://svn.python.org/view/python/trunk/Modules/itertoolsmodule.c?view=markup Peter From mrholtsr at sbcglobal.net Sun Dec 20 08:40:05 2009 From: mrholtsr at sbcglobal.net (Ray Holt) Date: Sun, 20 Dec 2009 08:40:05 -0500 Subject: Invalid syntax error Message-ID: <4471724C2D974EC6AF241BCA4CD4A9B3@ray> Why am I getting an invalid syntax error on the following: os.chdir(c:\\Python_Modules). The error message says the colon after c is invalid syntax. Why is it saying this when I am trying to change directory to c:\Python_Modules. Thanks, Ray -------------- next part -------------- An HTML attachment was scrubbed... URL: From alfps at start.no Sun Dec 20 08:50:12 2009 From: alfps at start.no (Alf P. Steinbach) Date: Sun, 20 Dec 2009 14:50:12 +0100 Subject: Programming intro book ch1 and ch2 (Windows/Python 3) - Request For Comments In-Reply-To: References: Message-ID: Hi, 10 details I forgot in my first response... * John Posner: > [...] Chapter 2, which current runs 98 pages! The chapter 2 PDF I posted on was and is (it's not been updated) 101 pages, with an "-EOT-" at page 102. I suspect you may have read the previous version. However, I believe the only difference from the previous version is the added text, the last three pages, about dictionaries (associative arrays). Did your PDF have Lewis Carrol's Jabberwocky nonsense poem somewhere in the last three pages? I used that poem as an example text for word counting? [snip] > As I've said in this forum (and the edu-sig forum) before, I think the > best metaphor for understanding Python variable assignment is John > Zelle's yellow-sticky-note metaphor. [2] [snip] > > [2] "Python Programming: An Introduction to Computer Science" by John > Zelle (Franklin, Biddle & Associates, 2004) See Section 2.5.1, "Simple > Assignment" I'm unable to find anything about yellow sticky-notes there! However, I can guess what it was about :-), and I only looked in a PDF I downloaded, which probably was illegal and manually typed in by some kid. He he, they do a great service for us who don't have ready continuous access to a university library! Cheers, - Alf PS: Argh! Someone did it -- serious programming intro based on Python -- already! However, there's a difference between computer science and programming, as very clearly explained by Bjarne Stroustrup in his latest book; Zelle uses Python 2.x in Linux, while I use 3.x in Windows, more accessible to the average reader; Zelle's book seems to be at least partially assuming a school environment while what I'm writing is /meant/ to be sufficient for unassisted self study; and of course I think my progression is better, e.g. introducing loops and decisions very early. However, all those exercises... I wish Someone(TM) could cook up Really Interesting exercises for my manuscript! :-P From contact at xavierho.com Sun Dec 20 08:52:32 2009 From: contact at xavierho.com (Xavier Ho) Date: Sun, 20 Dec 2009 23:52:32 +1000 Subject: Invalid syntax error In-Reply-To: <4471724C2D974EC6AF241BCA4CD4A9B3@ray> References: <4471724C2D974EC6AF241BCA4CD4A9B3@ray> Message-ID: <2d56febf0912200552u4da0233coe1b252f42e3d5b89@mail.gmail.com> Putting quotemarks "" around the path would be a good start, I think. Cheers, Xav On Sun, Dec 20, 2009 at 11:40 PM, Ray Holt wrote: > Why am I getting an invalid syntax error on the following: > os.chdir(c:\\Python_Modules). The error message says the colon after c is > invalid syntax. Why is it saying this when I am trying to change directory > to c:\Python_Modules. Thanks, Ray > > -- > http://mail.python.org/mailman/listinfo/python-list > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From cournape at gmail.com Sun Dec 20 09:13:57 2009 From: cournape at gmail.com (David Cournapeau) Date: Sun, 20 Dec 2009 23:13:57 +0900 Subject: numpy performance and random numbers In-Reply-To: <4b2df2be$1@dnews.tpgi.com.au> References: <69df23c3-ee4e-4c8f-9d66-581e3e272fad@m38g2000yqd.googlegroups.com> <4b2d36db$1@dnews.tpgi.com.au> <9a71ed3e-de34-4d39-b2d5-66e9ff1baa91@m3g2000yqf.googlegroups.com> <4b2d73ec$1@dnews.tpgi.com.au> <125c6868-6200-42ce-aee0-9c313b006966@b2g2000yqi.googlegroups.com> <4b2df2be$1@dnews.tpgi.com.au> Message-ID: <5b8d13220912200613q5a65bf03n80b7e967b6543f1b@mail.gmail.com> On Sun, Dec 20, 2009 at 6:47 PM, Lie Ryan wrote: > On 12/20/2009 2:53 PM, sturlamolden wrote: >> >> On 20 Des, 01:46, Lie Ryan ?wrote: >> >>> Not necessarily, you only need to be certain that the two streams don't >>> overlap in any reasonable amount of time. For that purpose, you can use >>> a PRNG that have extremely high period like Mersenne Twister and puts >>> the generators to very distant states. >> >> Except there is no way to find two very distant states and prove they >> are distant enough. >> > Except only theoretical scientist feel the need to prove it and perhaps > perhaps for cryptographic-level security. Random number for games, random > number for tmp files, and 99.99% random number users doesn't really need > such proves. But the OP case mostly like falls in your estimated 0.01% case. PRNG quality is essential for reliable Monte Carlo procedures. I don't think long period is enough to guarantee those good properties for // random generators - at least it is not obvious to me. David From stef.mientki at gmail.com Sun Dec 20 09:26:54 2009 From: stef.mientki at gmail.com (Stef Mientki) Date: Sun, 20 Dec 2009 15:26:54 +0100 Subject: how to go back from 2.6.4 to 2.6.2 under windows ? Message-ID: <4B2E342E.4070808@gmail.com> hello, I've just upgraded my system from Python 2.5 to 2.6.4, and installed the latest packages of a lot of libraries. Now one essential package (VPython) only works with Python 2.6.2. I tried to install Python 2.6.2 over this 2.6.4 installation, and indeed the readme file says it's 2.6.2, but the python and pythonw are still 2.6.4. Why is that so ?? Now assume that a number of packages (because compiled with 2.6.4) will not work correctly with 2.6.2. Is that correct ? So the best way would be to reinstall everything ?? thanks, Stef Mientki From mlowicki at gmail.com Sun Dec 20 09:46:10 2009 From: mlowicki at gmail.com (mlowicki) Date: Sun, 20 Dec 2009 06:46:10 -0800 (PST) Subject: problem with cheetah Message-ID: <0fd84b05-cf12-485b-a14e-608e47679b32@s20g2000yqd.googlegroups.com> Hi!, i get such error when I try to install cheetah: sudo easy_install cheetah Searching for cheetah Reading http://pypi.python.org/simple/cheetah/ Reading http://www.CheetahTemplate.org/ Reading http://sourceforge.net/project/showfiles.php?group_id=28961 Reading http://www.cheetahtemplate.org/ Best match: Cheetah 2.4.1.linux-x86-64 Downloading http://pypi.python.org/packages/2.6/C/Cheetah/Cheetah-2.4.1.linux-x86_64.tar.gz#md5=98cda0e846db7988f43a6b2acf00a527 Processing Cheetah-2.4.1.linux-x86_64.tar.gz error: Couldn't find a setup script in /tmp/easy_install-uv6Ms_/ Cheetah-2.4.1.linux-x86_64.tar.gz From malte.usenet at web.de Sun Dec 20 10:22:36 2009 From: malte.usenet at web.de (Malte Dik) Date: Sun, 20 Dec 2009 16:22:36 +0100 Subject: comparing dialects of csv-module References: <7p3q78F8o2U1@mid.dfncis.de> Message-ID: <7p6tfuF5skU1@mid.dfncis.de> quote: >>>> d = csv.Sniffer().sniff("1,2,3") >>>> def eq(a, b, attributes=[name for name in dir(d) if not > name.startswith("_")]): > ... return all(getattr(a, n, None) == getattr(b, n, None) for n in > attributes) Only change I made is substituting "dir(csv.excel)" or "dir(csv.Dialect)" for "dir(d)", because I can't be always sure, that there'd be a nicely defined "d". Salute, Malte From davea at ieee.org Sun Dec 20 10:34:46 2009 From: davea at ieee.org (Dave Angel) Date: Sun, 20 Dec 2009 10:34:46 -0500 Subject: console command to get the path of a function In-Reply-To: <4b2e1c74$0$1113$4fafbaef@reader1.news.tin.it> References: <4b2e1c74$0$1113$4fafbaef@reader1.news.tin.it> Message-ID: <4B2E4416.9010303@ieee.org> mattia wrote: > Hi all, is there a way in the python shell to list the path of a library > function (in order to look at the source code?). > > Thanks, Mattia > > If you know what module it's in, you can use themodule.__file__ But realize that this will only work if the module has been imported, and might not if the module is implemented in C. DaveA From deets at nospam.web.de Sun Dec 20 10:54:04 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 20 Dec 2009 16:54:04 +0100 Subject: problem with cheetah In-Reply-To: <0fd84b05-cf12-485b-a14e-608e47679b32@s20g2000yqd.googlegroups.com> References: <0fd84b05-cf12-485b-a14e-608e47679b32@s20g2000yqd.googlegroups.com> Message-ID: <7p6vksF3qrp0gU1@mid.uni-berlin.de> mlowicki schrieb: > Hi!, i get such error when I try to install cheetah: > > sudo easy_install cheetah > Searching for cheetah > Reading http://pypi.python.org/simple/cheetah/ > Reading http://www.CheetahTemplate.org/ > Reading http://sourceforge.net/project/showfiles.php?group_id=28961 > Reading http://www.cheetahtemplate.org/ > Best match: Cheetah 2.4.1.linux-x86-64 > Downloading http://pypi.python.org/packages/2.6/C/Cheetah/Cheetah-2.4.1.linux-x86_64.tar.gz#md5=98cda0e846db7988f43a6b2acf00a527 > Processing Cheetah-2.4.1.linux-x86_64.tar.gz > error: Couldn't find a setup script in /tmp/easy_install-uv6Ms_/ > Cheetah-2.4.1.linux-x86_64.tar.gz > I don't know who created that package, but after downloading and listing it's contents it seems it is not a proper python egg or source distribution. Try to download cheetah yourself from here: http://pypi.python.org/packages/source/C/Cheetah/Cheetah-2.4.0.tar.gz#md5=873f5440676355512f176fc4ac01011e Extract & build it your own, with source-package $ sudo easy_install . Diez From darcy at druid.net Sun Dec 20 10:55:54 2009 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Sun, 20 Dec 2009 10:55:54 -0500 Subject: Invalid syntax error In-Reply-To: <4471724C2D974EC6AF241BCA4CD4A9B3@ray> References: <4471724C2D974EC6AF241BCA4CD4A9B3@ray> Message-ID: <20091220105554.bea77903.darcy@druid.net> On Sun, 20 Dec 2009 08:40:05 -0500 "Ray Holt" wrote: > Why am I getting an invalid syntax error on the following: > os.chdir(c:\\Python_Modules). The error message says the colon after c is You forgot the quotes around the string. I am not on Windows but I think the following will all work. os.chdir("c:\\Python_Modules") os.chdir(r"c:\Python_Modules") os.chdir("c:/Python_Modules") I won't swear to that last one but other languages handle it. Try them. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From dfnsonfsduifb at gmx.de Sun Dec 20 11:08:33 2009 From: dfnsonfsduifb at gmx.de (Johannes Bauer) Date: Sun, 20 Dec 2009 17:08:33 +0100 Subject: Python3.1: gzip encoding with UTF-8 fails Message-ID: <7p70hgFlt3U1@mid.dfncis.de> Hello group, with this following program: #!/usr/bin/python3 import gzip x = gzip.open("testdatei", "wb") x.write("?") x.close() I get a broken .gzip file when decompressing: $ cat testdatei |gunzip ? gzip: stdin: invalid compressed data--length error As it only happens with UTF-8 characters, I suppose the gzip module writes a length of 1 in the gzip file header (one character "?"), but then actually writes 2 characters (0xc3 0xa4). Is there a solution? Regards, Johannes -- "Aus starken Potentialen k?nnen starke Erdbeben resultieren; es k?nnen aber auch kleine entstehen - und "du" wirst es nicht f?r m?glich halten (!), doch sieh': Es k?nnen dabei auch gar keine Erdbeben resultieren." -- "R?diger Thomas" alias Thomas Schulz in dsa ?ber seine "Vorhersagen" <1a30da36-68a2-4977-9eed-154265b17d28 at q14g2000vbi.googlegroups.com> From steve at holdenweb.com Sun Dec 20 11:11:54 2009 From: steve at holdenweb.com (Steve Holden) Date: Sun, 20 Dec 2009 11:11:54 -0500 Subject: Creating Classes In-Reply-To: <4B2C5B4C.2000103@ieee.org> References: <26848375.post@talk.nabble.com> <4B2C5B4C.2000103@ieee.org> Message-ID: <4B2E4CCA.4020400@holdenweb.com> Dave Angel wrote: [...] > We were talking about 2.x And I explicitly mentioned 3.x because if > one develops code that depends on old-style classes, they'll be in > trouble with 3.x, which has no way to specify old-style classes. In > 3.x, all classes are new-style. And although it'll no longer matter > whether you specify (object), it doesn't do any harm. As I said, it's a > good habit for a beginner to get into when defining classes. > I maintain that this almost-cargo-cult belief over-complicates things for language beginners. How long do you have to be using Python before you make your first super() call? How many programs behave differently with old-style vs. new-style classes? regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 PyCon is coming! Atlanta, Feb 2010 http://us.pycon.org/ Holden Web LLC http://www.holdenweb.com/ UPCOMING EVENTS: http://holdenweb.eventbrite.com/ From steve at holdenweb.com Sun Dec 20 11:11:54 2009 From: steve at holdenweb.com (Steve Holden) Date: Sun, 20 Dec 2009 11:11:54 -0500 Subject: Creating Classes In-Reply-To: <4B2C5B4C.2000103@ieee.org> References: <26848375.post@talk.nabble.com> <4B2C5B4C.2000103@ieee.org> Message-ID: <4B2E4CCA.4020400@holdenweb.com> Dave Angel wrote: [...] > We were talking about 2.x And I explicitly mentioned 3.x because if > one develops code that depends on old-style classes, they'll be in > trouble with 3.x, which has no way to specify old-style classes. In > 3.x, all classes are new-style. And although it'll no longer matter > whether you specify (object), it doesn't do any harm. As I said, it's a > good habit for a beginner to get into when defining classes. > I maintain that this almost-cargo-cult belief over-complicates things for language beginners. How long do you have to be using Python before you make your first super() call? How many programs behave differently with old-style vs. new-style classes? regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 PyCon is coming! Atlanta, Feb 2010 http://us.pycon.org/ Holden Web LLC http://www.holdenweb.com/ UPCOMING EVENTS: http://holdenweb.eventbrite.com/ From andrearo at pvv.ntnu.no Sun Dec 20 11:36:07 2009 From: andrearo at pvv.ntnu.no (=?ISO-8859-15?Q?Andreas_R=F8sdal?=) Date: Sun, 20 Dec 2009 17:36:07 +0100 Subject: Multithreaded python program freezes Message-ID: Hello, I have some problems with a http proxy which is implemented in Python 2.6. A few times a day, the proxy begins using 100% CPU and doesn't work any more. I have created a thread dump when the problem occurs here: http://www.pvv.ntnu.no/~andrearo/thread-dump.html This is a thread dump during normal operation: http://www.pvv.ntnu.no/~andrearo/thread-dump-normal.html The source code can be found here: http://code.google.com/p/freeciv-forever/source/browse/trunk/freeciv-proxy/ The application is heavily multi-threaded, since its main function is being a proxy converting packets containing C struct data to JSON over HTTP. Any advice on why this Python program appears to freeze? Is there anything more I can do to find out why this problem occurs? Andreas R From benjamin.kaplan at case.edu Sun Dec 20 11:39:52 2009 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Sun, 20 Dec 2009 11:39:52 -0500 Subject: how to go back from 2.6.4 to 2.6.2 under windows ? In-Reply-To: <4B2E342E.4070808@gmail.com> References: <4B2E342E.4070808@gmail.com> Message-ID: On Sun, Dec 20, 2009 at 9:26 AM, Stef Mientki wrote: > hello, > > I've just upgraded my system from Python 2.5 to 2.6.4, > and installed the latest packages of a lot of libraries. > > Now one essential package (VPython) only works with Python 2.6.2. > I tried to install Python 2.6.2 over this 2.6.4 installation, > and indeed the readme file says it's 2.6.2, > but the python and pythonw are still 2.6.4. > Why is that so ?? > > Now assume that a number of packages (because compiled with 2.6.4) will not > work correctly with 2.6.2. > Is that correct ? > 2.6.4 is just a bugfix release- it's binary compatible with the other 2.6 releases. So any package that worked under 2.6.2 shouid also work under 2.6.4 unless a new bug was introduced or it relied on a bug that was fixed. And any package that works under 2.6.4 will also work under 2.6.2 without recompiling unless it hits one of the bugs that was fixed. > So the best way would be to reinstall everything ?? > > thanks, > Stef Mientki > > > -- > http://mail.python.org/mailman/listinfo/python-list > From tjacobs-sndr-4cf4f4 at codegnome.org Sun Dec 20 11:49:27 2009 From: tjacobs-sndr-4cf4f4 at codegnome.org (Todd A. Jacobs) Date: Sun, 20 Dec 2009 08:49:27 -0800 Subject: os.starfile() linux In-Reply-To: <880fa1d40911300935v8df6708xc3c5957d3db25cd9@mail.gmail.com> References: <880fa1d40911300935v8df6708xc3c5957d3db25cd9@mail.gmail.com> Message-ID: <20091220164927.GA22620@penguin.codegnome.org> On Mon, Nov 30, 2009 at 05:35:31PM +0000, joao abrantes wrote: > to open a new shell and to put the output of the new python program > there.. The subprocess module is probably what you want. -- "Oh, look: rocks!" -- Doctor Who, "Destiny of the Daleks" From deets at nospam.web.de Sun Dec 20 11:52:24 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 20 Dec 2009 17:52:24 +0100 Subject: Python3.1: gzip encoding with UTF-8 fails In-Reply-To: <7p70hgFlt3U1@mid.dfncis.de> References: <7p70hgFlt3U1@mid.dfncis.de> Message-ID: <7p7328F3r1r25U1@mid.uni-berlin.de> Johannes Bauer schrieb: > Hello group, > > with this following program: > > #!/usr/bin/python3 > import gzip > x = gzip.open("testdatei", "wb") > x.write("?") > x.close() > > I get a broken .gzip file when decompressing: > > $ cat testdatei |gunzip > ? > gzip: stdin: invalid compressed data--length error > > As it only happens with UTF-8 characters, I suppose the gzip module UTF-8 is not unicode. Even if the source-encoding above is UTF-8, I'm not sure what is used to encode the unicode-string when it's written. > writes a length of 1 in the gzip file header (one character "?"), but > then actually writes 2 characters (0xc3 0xa4). > > Is there a solution? What about writinga bytestring by explicitly decoding the string to utf-8 first? x.write("?".encode("utf-8")) Diez From tjacobs-sndr-4cf4f4 at codegnome.org Sun Dec 20 11:54:22 2009 From: tjacobs-sndr-4cf4f4 at codegnome.org (Todd A. Jacobs) Date: Sun, 20 Dec 2009 08:54:22 -0800 Subject: Invalid syntax error In-Reply-To: <4471724C2D974EC6AF241BCA4CD4A9B3@ray> References: <4471724C2D974EC6AF241BCA4CD4A9B3@ray> Message-ID: <20091220165422.GB22620@penguin.codegnome.org> On Sun, Dec 20, 2009 at 08:40:05AM -0500, Ray Holt wrote: > Why am I getting an invalid syntax error on the following: > os.chdir(c:\\Python_Modules). The error message says the colon after c You need to pass either a string literal or a variable. If you're passing a string, like you are trying to do, then you need to quote it. Also, you may want to use os.path.join() to make sure you're passing a portable pathname. -- "Oh, look: rocks!" -- Doctor Who, "Destiny of the Daleks" From aahz at pythoncraft.com Sun Dec 20 11:54:30 2009 From: aahz at pythoncraft.com (Aahz) Date: 20 Dec 2009 08:54:30 -0800 Subject: opening a connection to quickbooks References: Message-ID: In article , wrote: > >Has anyone ever attempted to work with quickbooks in a real time fashion? I >need some advise. I'm trying to work out a way to have real time >updates/inserts/and queries. I'd also like not to use all the user >licenses. But... > >I have discovered that opening a connection to quickbooks takes a long >time (as much as 11 seconds). Is there a way I can open/create the >connection in a thread (so the rest of the prog can continue) and then >use the connection in the rest of the program to make queries? Or does >someone have a suggestion as how to get around this problem. Are you trying to use the XML interface or the COM interface? Either way, probably using a thread would work. (Note that I actually know very little about QB -- I just had a research project a couple of months ago about trying to integrate with it.) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Looking back over the years, after I learned Python I realized that I never really had enjoyed programming before. From mlowicki at gmail.com Sun Dec 20 11:56:53 2009 From: mlowicki at gmail.com (mlowicki) Date: Sun, 20 Dec 2009 08:56:53 -0800 (PST) Subject: problem with cheetah References: <0fd84b05-cf12-485b-a14e-608e47679b32@s20g2000yqd.googlegroups.com> <7p6vksF3qrp0gU1@mid.uni-berlin.de> Message-ID: <8e8792d2-e5b3-4ee9-9785-237d0809c36d@y24g2000yqb.googlegroups.com> On Dec 20, 4:54?pm, "Diez B. Roggisch" wrote: > mlowicki schrieb: > > > Hi!, i get such error when I try to install cheetah: > > > sudo easy_install cheetah > > Searching for cheetah > > Readinghttp://pypi.python.org/simple/cheetah/ > > Readinghttp://www.CheetahTemplate.org/ > > Readinghttp://sourceforge.net/project/showfiles.php?group_id=28961 > > Readinghttp://www.cheetahtemplate.org/ > > Best match: Cheetah 2.4.1.linux-x86-64 > > Downloadinghttp://pypi.python.org/packages/2.6/C/Cheetah/Cheetah-2.4.1.linux-x86... > > Processing Cheetah-2.4.1.linux-x86_64.tar.gz > > error: Couldn't find a setup script in /tmp/easy_install-uv6Ms_/ > > Cheetah-2.4.1.linux-x86_64.tar.gz > > I don't know who created that package, but after downloading and listing > it's contents it seems it is not a proper python egg or source distribution. > > Try to download cheetah yourself from here: > > http://pypi.python.org/packages/source/C/Cheetah/Cheetah-2.4.0.tar.gz... > > Extract & build it your own, with > > source-package $ sudo easy_install . > > Diez Thanks Diez! when I run: sudo easy_install http://pypi.python.org/packages/source/C/Cheetah/Cheetah-2.4.0.tar.gz#md5=873f5440676355512f176fc4ac01011e it works. By I need also put Cheetah to install_requires in setup.py like this: setup( name="django-yuidoc", version="0.1", zip_safe=False, packages=find_packages(), install_requires=["setuptools", "Pygments", "SimpleJSON", "Cheetah", ], ) and install this package with buildout but I get "error: Couldn't find a setup script [...]" and workaround with pass the url doesn't work with here (An internal error occured due to a bug in either zc.buildout or in a recipe being used) From aahz at pythoncraft.com Sun Dec 20 11:59:13 2009 From: aahz at pythoncraft.com (Aahz) Date: 20 Dec 2009 08:59:13 -0800 Subject: When will Python 3 be fully deployed References: <4b20ac0a$0$1596$742ec2ed@news.sonic.net> Message-ID: In article , Ned Deily wrote: >In article <4b20ac0a$0$1596$742ec2ed at news.sonic.net>, > John Nagle wrote: >> >> I'd argue against using Python 2.6 for production work. Either use >> Python 2.5, which is stable, or 3.x, which is bleeding-edge. 2.6 >> has some of the features of Python 3.x, but not all of them, and is >> neither fish nor fowl as a result. 2.6 is really more of a sideline >> that was used for trying out new features, not something suitable for >> production. > >I disagree with that advice, strongly. 2.6 not only has new features >but it has many bug fixes that have not and will not be applied to 2.5. >It is hardly a sideline. Ditto -- we had some webserver crashes that were fixed by upgrading from 2.4 to 2.6 (we were already using 2.6 in the client and decided that skipping 2.5 on the server was best). -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Looking back over the years, after I learned Python I realized that I never really had enjoyed programming before. From mohamedmusthafa.safarulla at gmail.com Sun Dec 20 12:17:41 2009 From: mohamedmusthafa.safarulla at gmail.com (Mohamed Musthafa Safarulla) Date: Sun, 20 Dec 2009 11:17:41 -0600 Subject: IDLE issue Message-ID: I have python 2.5 ...but when i open it, i get the below error messages Socker Error: Connection refused and IDLE's subprocess didnt make connection. Either IDLE can't start subprocess or personal firewall software is blocking the connection. Have someone encountered this issue? Please help. -- Thanks, Musthafa -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at mrabarnett.plus.com Sun Dec 20 12:26:36 2009 From: python at mrabarnett.plus.com (MRAB) Date: Sun, 20 Dec 2009 17:26:36 +0000 Subject: Something Like os.environ['HTTP_REFERER'] In-Reply-To: <4dc0cfea0912200206s2fbbfb26pd015b7be7e88b570@mail.gmail.com> References: <4dc0cfea0912200206s2fbbfb26pd015b7be7e88b570@mail.gmail.com> Message-ID: <4B2E5E4C.7000809@mrabarnett.plus.com> Victor Subervi wrote: > Hi; I'm looking for something like os.environ['HTTP_REFERER'] but for > python scripts. That is, if I have a script that is imported by > another script, how can I have the script that is being imported > determine which script imported it? > I don't know whether that's possible (it probably is), but I do know that it's undesirable. A script shouldn't sometimes behave one way and sometimes another. Explicit is better than implicit. If you want to control its behaviour then you should do so explicitly. From aahz at pythoncraft.com Sun Dec 20 12:33:07 2009 From: aahz at pythoncraft.com (Aahz) Date: 20 Dec 2009 09:33:07 -0800 Subject: Where is my namespace? References: <00a7037c$0$15659$c3e8da3@news.astraweb.com> Message-ID: In article <00a7037c$0$15659$c3e8da3 at news.astraweb.com>, Steven D'Aprano wrote: >> 2009/12/7 vsoler : >>> >>> 3. Mark says: The from statement is really an assignment to names in >>> the importer's scope--a name-copy operation, not a name aliasing. ?? I >>> don't fully understand what he means. Could anybody explain? > >I'm not sure what Mark means by that either. It certainly isn't a copy >operation, it doesn't duplicate the object you imported. I don't know >what he means by aliasing, but if he means what I mean by aliasing, then >I'd say the from statement *is* an aliasing operation: it creates a new >name that refers to an existing object found by name. > >from module import name > >is roughly equivalent to: > >import module >name = module.name >del module The reason why Mark made his comment (although I think it needs some rephrasing): import module from module import name name = 'foo' print module.name is name (Of course this is all completely obvious to anyone who understands Python's name/binding semantics, but someone just learning about module imports is probably not in that category and needs some kind of warning about re-assigning names created by ``from ... import``.) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Looking back over the years, after I learned Python I realized that I never really had enjoyed programming before. From metolone+gmane at gmail.com Sun Dec 20 13:01:49 2009 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Sun, 20 Dec 2009 10:01:49 -0800 Subject: Python3.1: gzip encoding with UTF-8 fails References: <7p70hgFlt3U1@mid.dfncis.de> <7p7328F3r1r25U1@mid.uni-berlin.de> Message-ID: > "Diez B. Roggisch" wrote in message > news:7p7328F3r1r25U1 at mid.uni-berlin.de... > Johannes Bauer schrieb: > > Hello group, > > > > with this following program: > > > > #!/usr/bin/python3 > > import gzip > > x = gzip.open("testdatei", "wb") > > x.write("?") > > x.close() > > > > I get a broken .gzip file when decompressing: > > > > $ cat testdatei |gunzip > > ? > > gzip: stdin: invalid compressed data--length error > > > > As it only happens with UTF-8 characters, I suppose the gzip module > > UTF-8 is not unicode. Even if the source-encoding above is UTF-8, I'm not > sure what is used to encode the unicode-string when it's written. > > > writes a length of 1 in the gzip file header (one character "?"), but > > then actually writes 2 characters (0xc3 0xa4). > > > > Is there a solution? > > What about writinga bytestring by explicitly decoding the string to utf-8 > first? > > x.write("?".encode("utf-8")) While that works, it still seems like a bug in gzip. If gzip.open is replaced with a simple open: # coding: utf-8 import gzip x = open("testdatei", "wb") x.write("?") x.close() The result is: Traceback (most recent call last): File "C:\dev\python3\Lib\site-packages\Pythonwin\pywin\framework\scriptutils.py", line 427, in ImportFile exec(codeObj, __main__.__dict__) File "", line 1, in File "y.py", line 4, in x.write("?") TypeError: must be bytes or buffer, not str Opening a file in binary mode should require a bytes or buffer object. -Mark From apt.shansen at gmail.com Sun Dec 20 13:20:16 2009 From: apt.shansen at gmail.com (Stephen Hansen) Date: Sun, 20 Dec 2009 10:20:16 -0800 Subject: Something Like os.environ['HTTP_REFERER'] In-Reply-To: <4dc0cfea0912200305m1f446bc5v13b309ca4d306c7e@mail.gmail.com> References: <4dc0cfea0912200206s2fbbfb26pd015b7be7e88b570@mail.gmail.com> <50697b2c0912200218j1966d811m42e4ccb04bdc1ba6@mail.gmail.com> <4dc0cfea0912200305m1f446bc5v13b309ca4d306c7e@mail.gmail.com> Message-ID: <7a9c25c20912201020j73ee6b01wfd3c9bdb9fe564e5@mail.gmail.com> On Sun, Dec 20, 2009 at 3:05 AM, Victor Subervi wrote: > Of course, I can pass the page name as a parameter, but that's not elegant. > That is precisely what it is in fact-- elegant; it is non-elegant to have magical behavior where what 'imports' something somehow changes or determines how that something behaves. It may be possible to go into dark places to discover what code first imported a module, but its not possible to discover what code does subsequent imports-- and in either case, this is /not/ something that has any sort of elegance to it. Its deeply hackish. If you want a piece of code to have a variable number of differing behaviors, that's something you can handle in many elegant ways. That's something inheritance is good for, with a core default behavior represented in one class and more specialized behavior represented in sub-classes. But either way, you have to tell it which class to create at the moment, which entails passing in a parameter explicitly activating one or the other. This is a good thing. Don't try to get around it. --S -------------- next part -------------- An HTML attachment was scrubbed... URL: From victorsubervi at gmail.com Sun Dec 20 14:01:51 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Sun, 20 Dec 2009 14:01:51 -0500 Subject: Something Like os.environ['HTTP_REFERER'] In-Reply-To: <7a9c25c20912201020j73ee6b01wfd3c9bdb9fe564e5@mail.gmail.com> References: <4dc0cfea0912200206s2fbbfb26pd015b7be7e88b570@mail.gmail.com> <50697b2c0912200218j1966d811m42e4ccb04bdc1ba6@mail.gmail.com> <4dc0cfea0912200305m1f446bc5v13b309ca4d306c7e@mail.gmail.com> <7a9c25c20912201020j73ee6b01wfd3c9bdb9fe564e5@mail.gmail.com> Message-ID: <4dc0cfea0912201101r3e3c8e84rea9e513aeb5668ee@mail.gmail.com> On Sun, Dec 20, 2009 at 1:20 PM, Stephen Hansen wrote: > On Sun, Dec 20, 2009 at 3:05 AM, Victor Subervi wrote: > >> Of course, I can pass the page name as a parameter, but that's not >> elegant. >> > > That is precisely what it is in fact-- elegant; it is non-elegant to have > magical behavior where what 'imports' something somehow changes or > determines how that something behaves. > > It may be possible to go into dark places to discover what code first > imported a module, but its not possible to discover what code does > subsequent imports-- and in either case, this is /not/ something that has > any sort of elegance to it. Its deeply hackish. > > If you want a piece of code to have a variable number of differing > behaviors, that's something you can handle in many elegant ways. That's > something inheritance is good for, with a core default behavior represented > in one class and more specialized behavior represented in sub-classes. But > either way, you have to tell it which class to create at the moment, which > entails passing in a parameter explicitly activating one or the other. This > is a good thing. Don't try to get around it. > Inelegant. This will be elegant: ourFile = string.split(__file__, "/") p = ourFile[len(ourFile) - 1] p = p[: - 3] site = ourFile[4][:-10] if site != '': site = site[:-1] from this import that(site) Now it's automated. V -------------- next part -------------- An HTML attachment was scrubbed... URL: From lacrima.maxim at gmail.com Sun Dec 20 14:32:34 2009 From: lacrima.maxim at gmail.com (Lacrima) Date: Sun, 20 Dec 2009 11:32:34 -0800 (PST) Subject: Anybody use web2py? References: <6oidnWzFKdtK6LHWnZ2dnUVZ_opi4p2d@supernews.com> <39d22fcc-c721-4da3-952d-f2bc178a3122@l13g2000yqb.googlegroups.com> <3e164613-a375-45a6-8965-8c90c2369125@r5g2000yqb.googlegroups.com> Message-ID: On Dec 20, 1:35?am, mdipierro wrote: > Errata. I said "The dal supports transactions" where I meant "the dal > supports migrations". > Of course it also supports "transactions" as well as "distributed > transactions". Sorry, if this is not related to this topic. Does web2py support distributed transactions with Google App Engine Datastore? From stef.mientki at gmail.com Sun Dec 20 14:59:46 2009 From: stef.mientki at gmail.com (Stef Mientki) Date: Sun, 20 Dec 2009 20:59:46 +0100 Subject: how to go back from 2.6.4 to 2.6.2 under windows ? In-Reply-To: References: <4B2E342E.4070808@gmail.com> Message-ID: <4B2E8232.2090206@gmail.com> Benjamin Kaplan wrote: > On Sun, Dec 20, 2009 at 9:26 AM, Stef Mientki wrote: > >> hello, >> >> I've just upgraded my system from Python 2.5 to 2.6.4, >> and installed the latest packages of a lot of libraries. >> >> Now one essential package (VPython) only works with Python 2.6.2. >> I tried to install Python 2.6.2 over this 2.6.4 installation, >> and indeed the readme file says it's 2.6.2, >> but the python and pythonw are still 2.6.4. >> Why is that so ?? >> >> Now assume that a number of packages (because compiled with 2.6.4) will not >> work correctly with 2.6.2. >> Is that correct ? >> >> > > 2.6.4 is just a bugfix release- it's binary compatible with the other > 2.6 releases. So any package that worked under 2.6.2 shouid also work > under 2.6.4 unless a new bug was introduced or it relied on a bug that > was fixed. And any package that works under 2.6.4 will also work under > 2.6.2 without recompiling unless it hits one of the bugs that was > fixed. > thanks Benjamin, Then VPython must hit one of the bugs that were fixed. On a second machine, - I removed Python 2.6.4 (without removing all other libraries) - installed Python 2.6.2 (without re?nstalling all the libraries) and indeed the VPython library works as expected. So I guess this is a reasonable approach, and all libraries should work well, unless one of these libraries has a work around for one of the bugs fixed between 2.6.2 and 2.6.4. cheers, Stef > >> So the best way would be to reinstall everything ?? >> >> thanks, >> Stef Mientki >> >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> >> From tjreedy at udel.edu Sun Dec 20 15:02:12 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 20 Dec 2009 15:02:12 -0500 Subject: console command to get the path of a function In-Reply-To: <4b2e1c74$0$1113$4fafbaef@reader1.news.tin.it> References: <4b2e1c74$0$1113$4fafbaef@reader1.news.tin.it> Message-ID: On 12/20/2009 7:45 AM, mattia wrote: > Hi all, is there a way in the python shell to list the path of a library > function (in order to look at the source code?). On Windows and I believe other systems, for the stdlib, 'import x' imports .../Pythonx.y/Lib/x From tjreedy at udel.edu Sun Dec 20 15:07:49 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 20 Dec 2009 15:07:49 -0500 Subject: IDLE issue In-Reply-To: References: Message-ID: On 12/20/2009 12:17 PM, Mohamed Musthafa Safarulla wrote: > I have python 2.5 ...but when i open it, i get the below error messages > > Socker Error: Connection refused > > and > > IDLE's subprocess didnt make connection. Either IDLE can't start > subprocess or personal firewall software is blocking the connection. > > Have someone encountered this issue? Please help. Yes. go to bugs.python.org and search text: 'socket error', component: IDLE for previous reports and suggestions. It is possible that upgrade will help. tjr From massimodipierro71 at gmail.com Sun Dec 20 15:14:54 2009 From: massimodipierro71 at gmail.com (mdipierro) Date: Sun, 20 Dec 2009 12:14:54 -0800 (PST) Subject: Anybody use web2py? References: <6oidnWzFKdtK6LHWnZ2dnUVZ_opi4p2d@supernews.com> <39d22fcc-c721-4da3-952d-f2bc178a3122@l13g2000yqb.googlegroups.com> <3e164613-a375-45a6-8965-8c90c2369125@r5g2000yqb.googlegroups.com> Message-ID: <71758326-bdff-42f5-8064-06b50c069518@c3g2000yqd.googlegroups.com> The concept of distributed transaction does not make sense on GAE because there is only one datastore. It supports regular transactions on GAE to the extent that GAE supports them but you have to use the GAE run_in_transaction API explictely. It does support distributed transactions with multiple database connection to postgresq, mysql and/or firebird. I think this is related to the topic because it is a distinctive feature of web2py. Massimo On Dec 20, 1:32?pm, Lacrima wrote: > On Dec 20, 1:35?am, mdipierro wrote: > > > Errata. I said "The dal supports transactions" where I meant "the dal > > supports migrations". > > Of course it also supports "transactions" as well as "distributed > > transactions". > > Sorry, if this is not related to this topic. > Does web2py support distributed transactions with Google App Engine > Datastore? From tjreedy at udel.edu Sun Dec 20 15:23:03 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 20 Dec 2009 15:23:03 -0500 Subject: how to go back from 2.6.4 to 2.6.2 under windows ? In-Reply-To: <4B2E8232.2090206@gmail.com> References: <4B2E342E.4070808@gmail.com> <4B2E8232.2090206@gmail.com> Message-ID: On 12/20/2009 2:59 PM, Stef Mientki wrote: > Benjamin Kaplan wrote: >> On Sun, Dec 20, 2009 at 9:26 AM, Stef Mientki >> wrote: >>> hello, >>> >>> I've just upgraded my system from Python 2.5 to 2.6.4, >>> and installed the latest packages of a lot of libraries. >>> >>> Now one essential package (VPython) only works with Python 2.6.2. >>> I tried to install Python 2.6.2 over this 2.6.4 installation, >>> and indeed the readme file says it's 2.6.2, >>> but the python and pythonw are still 2.6.4. >>> Why is that so ?? >>> >>> Now assume that a number of packages (because compiled with 2.6.4) >>> will not >>> work correctly with 2.6.2. >>> Is that correct ? >>> >> >> 2.6.4 is just a bugfix release- it's binary compatible with the other >> 2.6 releases. So any package that worked under 2.6.2 shouid also work >> under 2.6.4 unless a new bug was introduced or it relied on a bug that >> was fixed. And any package that works under 2.6.4 will also work under >> 2.6.2 without recompiling unless it hits one of the bugs that was >> fixed. > thanks Benjamin, > > Then VPython must hit one of the bugs that were fixed. > On a second machine, > - I removed Python 2.6.4 (without removing all other libraries) > - installed Python 2.6.2 (without re?nstalling all the libraries) > and indeed the VPython library works as expected. > > So I guess this is a reasonable approach, > and all libraries should work well, > unless one of these libraries has a work around for one of the bugs > fixed between 2.6.2 and 2.6.4. Let VPython people know about this problem. People should be able to run it on the latest patched 2.6. From python.list at tim.thechases.com Sun Dec 20 15:26:49 2009 From: python.list at tim.thechases.com (Tim Chase) Date: Sun, 20 Dec 2009 14:26:49 -0600 Subject: Something Like os.environ['HTTP_REFERER'] In-Reply-To: <4dc0cfea0912201101r3e3c8e84rea9e513aeb5668ee@mail.gmail.com> References: <4dc0cfea0912200206s2fbbfb26pd015b7be7e88b570@mail.gmail.com> <50697b2c0912200218j1966d811m42e4ccb04bdc1ba6@mail.gmail.com> <4dc0cfea0912200305m1f446bc5v13b309ca4d306c7e@mail.gmail.com> <7a9c25c20912201020j73ee6b01wfd3c9bdb9fe564e5@mail.gmail.com> <4dc0cfea0912201101r3e3c8e84rea9e513aeb5668ee@mail.gmail.com> Message-ID: <4B2E8889.6080303@tim.thechases.com> Victor Subervi wrote: > On Sun, Dec 20, 2009 at 1:20 PM, Stephen Hansen wrote: >>> Of course, I can pass the page name as a parameter, but that's not >>> elegant. >>> >> That is precisely what it is in fact-- elegant; it is non-elegant to have >> magical behavior where what 'imports' something somehow changes or >> determines how that something behaves. >> >> It may be possible to go into dark places to discover what code first >> imported a module, but its not possible to discover what code does >> subsequent imports-- and in either case, this is /not/ something that has >> any sort of elegance to it. Its deeply hackish. > > Inelegant. This will be elegant: [snipped atrocious malformed code that won't compile, has undocumented magic constants, and is fragilely dependent on a certain directory/naming convention] For your claims to be a right-brained artistic type, your evidenced sense of aesthetic leans towards the baroquen. Trust the list's suggestions -- your proposed code is NOT elegant. This is reinforced on multiple fronts: Stephen and MRAB have already commented this is an inelegant idea (and Chris hinted that it's undesirable) and I share their opinion; additionally, the fact that Python doesn't make this easy suggests that it's not the preferred way to do things. Yes, one can sniff stacks, check the system module cache before and after an import, or do other crazy black magic, but for your described use-case, proper architecture can be both elegant and simple as Stephen suggests. -tkc From apt.shansen at gmail.com Sun Dec 20 15:26:56 2009 From: apt.shansen at gmail.com (Stephen Hansen) Date: Sun, 20 Dec 2009 12:26:56 -0800 Subject: Something Like os.environ['HTTP_REFERER'] In-Reply-To: <4dc0cfea0912201101r3e3c8e84rea9e513aeb5668ee@mail.gmail.com> References: <4dc0cfea0912200206s2fbbfb26pd015b7be7e88b570@mail.gmail.com> <50697b2c0912200218j1966d811m42e4ccb04bdc1ba6@mail.gmail.com> <4dc0cfea0912200305m1f446bc5v13b309ca4d306c7e@mail.gmail.com> <7a9c25c20912201020j73ee6b01wfd3c9bdb9fe564e5@mail.gmail.com> <4dc0cfea0912201101r3e3c8e84rea9e513aeb5668ee@mail.gmail.com> Message-ID: <7a9c25c20912201226w1b43aef1u112609d567ca0071@mail.gmail.com> On Sun, Dec 20, 2009 at 11:01 AM, Victor Subervi wrote: > If you want a piece of code to have a variable number of differing >> behaviors, that's something you can handle in many elegant ways. That's >> something inheritance is good for, with a core default behavior represented >> in one class and more specialized behavior represented in sub-classes. But >> either way, you have to tell it which class to create at the moment, which >> entails passing in a parameter explicitly activating one or the other. This >> is a good thing. Don't try to get around it. >> > > Inelegant. This will be elegant: > > ourFile = string.split(__file__, "/") > p = ourFile[len(ourFile) - 1] > p = p[: - 3] > site = ourFile[4][:-10] > if site != '': > site = site[:-1] > > from this import that(site) > > Now it's automated. > Since when is "automation" a synonym of "elegance"? Granted, elegance is something that will always be in the eye of the beholder-- but looking at that chunk of code, I can't even figure out what you're trying to do with it (or what that last 'from ...' line is even supposed to mean). To me, elegance in code is the hard-to-define and oft-saught-after unity of clarity, maintainability and functionality. For code to be elegant, you must be able to look at it in isolation and with relative ease(provided one understands the language and its idiomatic usage, of course) fully understand what it does. Its clear. You shouldn't have to look into another part of code, or worse another file, to understand it. Being clear, its purpose should be well-defined such that you can make changes to it with ease and have no worry about breaking or altering the behavior of other parts of code. Its maintainable. Being maintainable, it achieves its desired function in the best way that it can without sacrificing previous principles -- its relatively efficient without being dirtied by premature optimization, it takes advantages of the strengths of the language instead of pressing into the weaknesses. Not all code can be elegant; most can't for purely practical reasons, and that's fine. But describing spooky-action-at-a-distance behavior into modules such that which imports the code somehow changes that codes behavior as elegant? I dunno, we're operating on very different definitions at that point :) If elegance and automation are linked, then you'll find a lot of stuff in Python is inelegant, as the fundamental design of the language itself prizes explicitness as elegance, and not vice-versa. --S -------------- next part -------------- An HTML attachment was scrubbed... URL: From stef.mientki at gmail.com Sun Dec 20 15:38:33 2009 From: stef.mientki at gmail.com (Stef Mientki) Date: Sun, 20 Dec 2009 21:38:33 +0100 Subject: how to go back from 2.6.4 to 2.6.2 under windows ? In-Reply-To: References: <4B2E342E.4070808@gmail.com> <4B2E8232.2090206@gmail.com> Message-ID: <4B2E8B49.8070104@gmail.com> >> >> So I guess this is a reasonable approach, >> and all libraries should work well, >> unless one of these libraries has a work around for one of the bugs >> fixed between 2.6.2 and 2.6.4. > > Let VPython people know about this problem. People should be able to > run it on the latest patched 2.6. > > Well this is the first line on the VPython download page ;-) "To use Visual 5.13 with Python 2.6, use Python 2.6.2, NOT later versions such as Python 2.6.3 or Python 2.6.4 or Python 3.x:" cheers, Stef From wangpurui at yahoo.com.cn Sun Dec 20 15:40:42 2009 From: wangpurui at yahoo.com.cn (pograph) Date: Sun, 20 Dec 2009 12:40:42 -0800 (PST) Subject: console command to get the path of a function References: <4b2e1c74$0$1113$4fafbaef@reader1.news.tin.it> Message-ID: <44abfa9a-1354-4e26-8db6-479f408002fe@15g2000prz.googlegroups.com> On Dec 20, 12:02?pm, Terry Reedy wrote: > On 12/20/2009 7:45 AM, mattia wrote: > > > Hi all, is there a way in the python shell to list the path of a library > > function (in order to look at the source code?). > > On Windows and I believe other systems, for the stdlib, 'import x' > imports .../Pythonx.y/Lib/x Not always. For example, os.path is actually in one of ntpath.py, posixpath.py, or macpath.py. From adityashukla1983 at gmail.com Sun Dec 20 16:05:05 2009 From: adityashukla1983 at gmail.com (aditya shukla) Date: Sun, 20 Dec 2009 15:05:05 -0600 Subject: Live Video Capture using Python Message-ID: <73045cca0912201305kea3811dr70a7a65c5556c219@mail.gmail.com> Hello Guys, I am trying to capture images from a live broadcast of a "cricket match" or say any video using python. I can see the video in the browser.My aim is to capture the video at any moment and create an images.Searching on google turns up http://videocapture.sourceforge.net/ .I am not sure if this would be help here.I would appreciate if someone points me in the right direction. Thanks Aditya -------------- next part -------------- An HTML attachment was scrubbed... URL: From richardbp at gmail.com Sun Dec 20 16:09:56 2009 From: richardbp at gmail.com (Baron) Date: Sun, 20 Dec 2009 13:09:56 -0800 (PST) Subject: Anybody use web2py? References: <6oidnWzFKdtK6LHWnZ2dnUVZ_opi4p2d@supernews.com> <320b6ef5-8508-4258-9e70-0d987d77e85f@u7g2000yqm.googlegroups.com> Message-ID: <257054b4-8dcc-46ea-bd2a-333db22c0f28@y32g2000prd.googlegroups.com> > If all > web2py offers is default views, then it may be good for proof of concept > projects, however I can't see in my right mind, proofing an application, > and then turning around to write it in django because more than the > defaults is needed. You *can* customize web2py views ... > Why does web2py have classes that represent HTML? I can't see ever > needing to write VIEW code in my controller, since thats what views are > for. I use these in my views when a HTML tag has multiple dynamic properties because it looks more neat. I came to web2py a year back after writing applications in many other frameworks (Turbogears / Symonfy / Rails / Django) and find myself more productive with web2py. So as others have said - try both. Write a small application in both to see which suits you. Richard From python.list at tim.thechases.com Sun Dec 20 16:19:57 2009 From: python.list at tim.thechases.com (Tim Chase) Date: Sun, 20 Dec 2009 15:19:57 -0600 Subject: How Do I...? In-Reply-To: <4dc0cfea0912190850kec7b3a2ice9cac3356cc221a@mail.gmail.com> References: <4dc0cfea0912181055o4da24927n4776b197efd5943@mail.gmail.com> <4B2BE024.4010307@tim.thechases.com> <4dc0cfea0912190210h3be56c85r34dbb93c672519cb@mail.gmail.com> <4B2CEFC6.8000801@tim.thechases.com> <4dc0cfea0912190850kec7b3a2ice9cac3356cc221a@mail.gmail.com> Message-ID: <4B2E94FD.4040707@tim.thechases.com> Victor Subervi wrote: >> The aim was not arrogance, but expression of exasperation > > "Walk a mile in my mocassins." You can't do it. I'm an artist. > I think out of my right hemisphere, not my left like you. You > couldn't possibly understand. [snip] > Thank you for your help anyway. Thank you for your patience. > Please try to understand. It starts by understanding you can't > understand. [snip] > The whole universe is a program. I program to understand it in > a way you couldn't even begin to grasp. I'm not sure how I become the one accused of arrogance. Or where my right-brain ceases to be as magnificent as yours and my capacity to understand you falls so short -- whether it's speaking Spanish or being conversational in ASL; authoring and illustrating a children's book; striving for beautiful code (Stephen's recent post well summarizes elegance in code); submitting my work status reports in [limerick, sonnet, rap, comic, pop-music spoof, crossword puzzle, etc]; cooking; sewing/crafting/needlework; painting; wood-working; guitar-playing; the philosophy minor; creating balloon art, etc. It would seem I use both sides of the brain, like many others on the list here. For just a single example reference, check out Adrian Holovaty (one of the Django founders) jamming some beautiful guitar-work on YouTube. > The problem is that I quite literally can't think like you. I > have to force myself to do it every time. To you it's as > natural as breathing, which is why you can't relate. In time and with repeated exercise, it's possible to develop both sides of the brain. One side may dominate (and I'll forthrightly declare that my left brain dominates), but it doesn't excuse failure to strengthen the weaker side. > You have my continued promise that I will do all > I can to edit my questions as intelligently as you would > before I post them. Trust me, I don't like looking foolish, > and I know I do. You should recognize that that alone is > chiding enough. It doesn't stop me, however, for continuing to > program. I appreciate your efforts to edit -- I've provided a bit of a check-list that you can use to make sure you've googled for the obvious; taken the time understand the problem in both a local context and stepping away to see the big-picture view of the problem; taken a survey of your available tools; read the tracebacks to try and understand what they're telling you; and when you post (with replies inline), provide the code exactly as it's erroring for you (stripped down examples are nice, as long as they reproduce the problem) instead of transcribing something like your code; if you get exceptions post the full traceback not just your interpretation of them; and if you're running in a non-conventional environment such as a web-server instead of a standalone application, it's helpful to note it up front. The perennial "Smart Questions" article by ESR might also be a useful read in ingratiating yourself. By demonstrating that you've exerted the effort to help the list help you, it encourages us to provide the best answers. On the whole, the list does enjoy being helpful. And when you do get a helpful answer, saying thanks is always appreciated... > I appreciate Tim's advice something I've noted you've improved on lately...thanks in return. > I came across as I intended. Your intent was to come across condescendingly as a right-brained artist struggling to be understood yet obdurately plunging ahead without striving to facilitate others in helping you? -tkc From victorsubervi at gmail.com Sun Dec 20 16:21:23 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Sun, 20 Dec 2009 16:21:23 -0500 Subject: Something Like os.environ['HTTP_REFERER'] In-Reply-To: <7a9c25c20912201226w1b43aef1u112609d567ca0071@mail.gmail.com> References: <4dc0cfea0912200206s2fbbfb26pd015b7be7e88b570@mail.gmail.com> <50697b2c0912200218j1966d811m42e4ccb04bdc1ba6@mail.gmail.com> <4dc0cfea0912200305m1f446bc5v13b309ca4d306c7e@mail.gmail.com> <7a9c25c20912201020j73ee6b01wfd3c9bdb9fe564e5@mail.gmail.com> <4dc0cfea0912201101r3e3c8e84rea9e513aeb5668ee@mail.gmail.com> <7a9c25c20912201226w1b43aef1u112609d567ca0071@mail.gmail.com> Message-ID: <4dc0cfea0912201321p24879e43u21b036922198acb8@mail.gmail.com> On Sun, Dec 20, 2009 at 3:26 PM, Stephen Hansen wrote: > On Sun, Dec 20, 2009 at 11:01 AM, Victor Subervi wrote: > >> If you want a piece of code to have a variable number of differing >>> behaviors, that's something you can handle in many elegant ways. That's >>> something inheritance is good for, with a core default behavior represented >>> in one class and more specialized behavior represented in sub-classes. But >>> either way, you have to tell it which class to create at the moment, which >>> entails passing in a parameter explicitly activating one or the other. This >>> is a good thing. Don't try to get around it. >>> >> >> Inelegant. This will be elegant: >> >> ourFile = string.split(__file__, "/") >> p = ourFile[len(ourFile) - 1] >> p = p[: - 3] >> site = ourFile[4][:-10] >> if site != '': >> site = site[:-1] >> >> from this import that(site) >> >> Now it's automated. >> > > Since when is "automation" a synonym of "elegance"? > > Granted, elegance is something that will always be in the eye of the > beholder-- but looking at that chunk of code, I can't even figure out what > you're trying to do with it (or what that last 'from ...' line is even > supposed to mean). > It's something to plug into any page anywhere and not have to worry about tweaking it for a given page. Not reading further responses to this post. V -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Sun Dec 20 16:22:02 2009 From: davea at ieee.org (Dave Angel) Date: Sun, 20 Dec 2009 16:22:02 -0500 Subject: Something Like os.environ['HTTP_REFERER'] In-Reply-To: <4dc0cfea0912201101r3e3c8e84rea9e513aeb5668ee@mail.gmail.com> References: <4dc0cfea0912200206s2fbbfb26pd015b7be7e88b570@mail.gmail.com> <50697b2c0912200218j1966d811m42e4ccb04bdc1ba6@mail.gmail.com> <4dc0cfea0912200305m1f446bc5v13b309ca4d306c7e@mail.gmail.com> <7a9c25c20912201020j73ee6b01wfd3c9bdb9fe564e5@mail.gmail.com> <4dc0cfea0912201101r3e3c8e84rea9e513aeb5668ee@mail.gmail.com> Message-ID: <4B2E957A.30007@ieee.org> Victor Subervi wrote: > Inelegant. This will be elegant: > > ourFile = string.split(__file__, "/") > p = ourFile[len(ourFile) - 1] > p = p[: - 3] > site = ourFile[4][:-10] > if site != '': > site = site[:-1] > > from this import that(site) > > Now it's automated. > V > > Amazing. When trying to split a path string, consider using os.path.split(). When trying to get rid of the file extension, consider using os.path.splitext(). When trying to get the last item of a list, consider using subscript of -1. And when you want all but the last 10 characters of a string, use [:-11] instead of a two-step. Since you've hardcoded the directory structure (also a bad idea), this may not be quite right. But something like: site = os.path.splitext(os.path.split(__file__)[1])[0][:-8] will extract the beginning of the basename, whether it's a URL, or Linux, or Windows. But all of this has nothing to do with your original question, which said: >>>>If I have a script that is imported by another script, how can I have >>>>the script that is being imported determine which script imported it? We were all willing to overlook the misuse of the word script -- a python source file that's imported isn't a script, it's a module -- but somehow we assumed you were asking a serious question. Nothing about the code you now post has anything to do with the script that imported it. DaveA From zabin.farishta at gmail.com Sun Dec 20 16:59:11 2009 From: zabin.farishta at gmail.com (Zabin) Date: Sun, 20 Dec 2009 13:59:11 -0800 (PST) Subject: PyQt Signals and multiple sources Message-ID: <64001010-9d5f-41cf-a7a9-a507f52d8e79@g22g2000prf.googlegroups.com> I am beginner in programming in pyqt. I have been trying to call the same function from multiple events- but each event results in a different instance of the function. I am just unable to figure out how to retrieve the source which calls the function: My source signal declarations are as below: QtCore.QObject.connect(self.ui.Button_Process, QtCore.SIGNAL("clicked ()"), self.activate_tab) QtCore.QObject.connect(self.ui.Button_Material, QtCore.SIGNAL("clicked ()"), self.activate_tab) QtCore.QObject.connect(self.ui.Button_Geometry, QtCore.SIGNAL("clicked ()"), self.activate_tab) for each of the above source i want to activate a different instance of the activate_tab function. Any help would be greatly appreciated! From jjposner at optimum.net Sun Dec 20 17:15:30 2009 From: jjposner at optimum.net (John Posner) Date: Sun, 20 Dec 2009 17:15:30 -0500 Subject: PyQt Signals and multiple sources References: <64001010-9d5f-41cf-a7a9-a507f52d8e79@g22g2000prf.googlegroups.com> Message-ID: On Sun, 20 Dec 2009 16:59:11 -0500, Zabin wrote: > I am beginner in programming in pyqt. I have been trying to call the > same function from multiple events- but each event results in a > different instance of the function. I am just unable to figure out how > to retrieve the source which calls the function: > > My source signal declarations are as below: > QtCore.QObject.connect(self.ui.Button_Process, QtCore.SIGNAL("clicked > ()"), self.activate_tab) > QtCore.QObject.connect(self.ui.Button_Material, QtCore.SIGNAL("clicked > ()"), self.activate_tab) > QtCore.QObject.connect(self.ui.Button_Geometry, QtCore.SIGNAL("clicked > ()"), self.activate_tab) > > for each of the above source i want to activate a different instance > of the activate_tab function. Any help would be greatly appreciated! In the self.activate_tab() method, use self.sender() to determine which object sent the signal. -John From zabin.farishta at gmail.com Sun Dec 20 17:33:39 2009 From: zabin.farishta at gmail.com (Zabin) Date: Sun, 20 Dec 2009 14:33:39 -0800 (PST) Subject: PyQt Signals and multiple sources References: <64001010-9d5f-41cf-a7a9-a507f52d8e79@g22g2000prf.googlegroups.com> Message-ID: <76902fec-ce88-43b6-a3ff-8ff72ce0e487@m33g2000pri.googlegroups.com> On Dec 21, 11:15?am, "John Posner" wrote: > On Sun, 20 Dec 2009 16:59:11 -0500, Zabin wrote: > > I am beginner in programming in pyqt. I have been trying to call the > > same function from multiple events- but each event results in a > > different instance of the function. I am just unable to figure out how > > to retrieve the source which calls the function: > > > My source signal declarations are as below: > > QtCore.QObject.connect(self.ui.Button_Process, QtCore.SIGNAL("clicked > > ()"), self.activate_tab) > > QtCore.QObject.connect(self.ui.Button_Material, QtCore.SIGNAL("clicked > > ()"), self.activate_tab) > > QtCore.QObject.connect(self.ui.Button_Geometry, QtCore.SIGNAL("clicked > > ()"), self.activate_tab) > > > for each of the above source i want to activate a different instance > > of the activate_tab function. Any help would be greatly appreciated! > > In the self.activate_tab() method, use self.sender() to determine which ? > object sent the signal. > > -John- Hide quoted text - > > - Show quoted text - Awesum. That works! To get the object name you just need to use self.sender().objectName() Cheers! From roy at panix.com Sun Dec 20 17:34:15 2009 From: roy at panix.com (Roy Smith) Date: Sun, 20 Dec 2009 17:34:15 -0500 Subject: When will Python 3 be fully deployed References: <4b20ac0a$0$1596$742ec2ed@news.sonic.net> Message-ID: In article , aahz at pythoncraft.com (Aahz) wrote: > Looking back over the years, after I learned Python I realized that I > never really had enjoyed programming before. That's a sad commentary. Python is fun to use, but surely there are other ways you can enjoy programming? The first thing I learned how to program was an HP-9810 (http://www.hpmuseum.org/hp9810.htm). I had LOADS of fun with that. Then I learned BASIC (using my high school's ASR-33 hookup to a HP-3000 a couple of towns away). Lots of fun there too. Then came Fortran. I guess I had fun with that, at least in the beginning. I did a bunch of assembler. Some of it was fun (pdp-11, 6800), some of it was not (pdp-10, IBM-1130). Lisp was fun for a while, but I never really got into it. C was fun at the beginning, but quickly became a drag. C++ was was evil and horrible at the beginning. As opposed to now, when I'm somewhat of an expert in it, and it's still evil and horrible. Learning PostScript was blast! One of the true epiphanies of my programming career was hooking a video terminal up to the RS-232 port on an Apple LaserWriter, typing a few lines of PostScript at it, and watching a page come out with a square drawn on it. Everybody should learn PostScript. People think of it as just some document printing thing, but it's a real (Turing-complete) programming language. Not just that, but it's a fun language to learn, and lets you explore some corners of the language design space which most people never see. Go forth and learn PostScript! Learning Java was about as much fun as kissing your sister. I'm sure I've left a few out, but the point is there are plenty of ways to have fun programming besides Python. From massimodipierro71 at gmail.com Sun Dec 20 17:57:39 2009 From: massimodipierro71 at gmail.com (mdipierro) Date: Sun, 20 Dec 2009 14:57:39 -0800 (PST) Subject: Anybody use web2py? References: <6oidnWzFKdtK6LHWnZ2dnUVZ_opi4p2d@supernews.com> <320b6ef5-8508-4258-9e70-0d987d77e85f@u7g2000yqm.googlegroups.com> <257054b4-8dcc-46ea-bd2a-333db22c0f28@y32g2000prd.googlegroups.com> Message-ID: People seem to think that because web2py has a default for almost everything (part of its design) than you must use the default. - There is a web based IDE but you *can* use the shell instead (like you do in Django) - There are migrations but you *can* disable then (and it works like Django that does not do migrations) - There are default views for every action but you *can* make your own - There is a default route to every action but you *can* create your own routes.py, equivalent to Django urls.py - There is a default for form layout but you *can* customize them in multiple ways - There is a default widget for every field but you *can* change it or define your own - There is a default validator for every field but you *can* change it or create your own - It comes with a default layout.html but you can user any other html/ css layout or make your own - It comes with jQuery but you *can* use any other javascript library - It default to email/password login but you *can* use other authentication methods (gmail, twitter, openid, rpx, cas, ldap). - etc. The only things that web2py does not let you customize are things that have security implications (like how sessions and uploads are handled). On Dec 20, 3:09?pm, Baron wrote: > > If all > > web2py offers is default views, then it may be good for proof of concept > > projects, however I can't see in my right mind, proofing an application, > > and then turning around to write it in django because more than the > > defaults is needed. > > You *can* customize web2py views ... > > > Why does web2py have classes that represent HTML? I can't see ever > > needing to write VIEW code in my controller, since thats what views are > > for. > > I use these in my views when a HTML tag has multiple dynamic > properties because it looks more neat. > > I came to web2py a year back after writing applications in many other > frameworks (Turbogears / Symonfy / Rails / Django) and find myself > more productive with web2py. > So as others have said - try both. Write a small application in both > to see which suits you. > > Richard From bearophileHUGS at lycos.com Sun Dec 20 18:27:50 2009 From: bearophileHUGS at lycos.com (Bearophile) Date: Sun, 20 Dec 2009 15:27:50 -0800 (PST) Subject: Vectorized laziness 2 Message-ID: Do you remember my post about Vectorized laziness that was fully ignored by everyone here? http://groups.google.com/group/comp.lang.python/browse_thread/thread/2637aafa1274629d/ The latest Clojure v.1.1 has implemented the same idea, they are named "Chunked Sequences": http://www.infoq.com/news/2009/12/clojure-11-rc1-transients See: http://clojure.googlegroups.com/web/chunks.pdf (I know they can have some problematic corner cases.) Bye and be well, bearophile From metolone+gmane at gmail.com Sun Dec 20 18:54:57 2009 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Sun, 20 Dec 2009 15:54:57 -0800 Subject: C Structure rebuild with ctypes References: <7p6ksnFkg1U1@mid.individual.net> Message-ID: "Georg" wrote in message news:7p6ksnFkg1U1 at mid.individual.net... > Hi All, > > I need to use a library written in C. The routine "int func (int handle, > int *numVars, char ***varNames, int **varTypes)" > > expects a complex object: > > " ... Variable names are structured as an array of *numVars pointers, each > pointing to a char string containing a variable name, and *varNames is set > to point to the first element of the array. Variable types are stored into > a corresponding array of *numVars in elements, and *varTypes is set to > point to the first element of the array." > > I tried using ctypes but nothing worked, e.g. "varNames = (c_char_p(c_char > * 65) * NumberOfVariables)()" > > Can anyboby help? How do I have to state the structure "array of pointers > to char string"? How is a pointer to the first element of such an array > defined using ctypes? How do I allocate enough space for the char the > array points to? Are you passing in these values, or are they being returned? To me the depth of the pointer references implies numVars, varNames, and varTypes are out parameters. I'll assume that for now. If they are in/out parameters let me know. I mocked up a DLL to test returning values of these types. I used VS2008 and compiled with "cl /LD func.c": --- func.c ------------------------------- #include #define FUNCDLL #include "func.h" static char* g_data[] = {"one","two","three"}; static int g_types[] = {1,2,3}; FUNCAPI int func (int handle, int *numVars, char ***varNames, int **varTypes) { *numVars = _countof(g_data); *varNames = g_data; *varTypes = g_types; return handle + 1; } --- func.h ------------------------------- #ifdef FUNCDLL # define FUNCAPI __declspec(dllexport) #else # define FUNCAPI __declspec(dllimport) #endif FUNCAPI int func (int handle, int *numVars, char ***varNames, int **varTypes); --- func.py ------------------------------- import ctypes as c # shortcuts for useful types INT = c.c_int PINT = c.POINTER(INT) PPINT = c.POINTER(PINT) PCHAR = c.c_char_p PPCHAR = c.POINTER(PCHAR) PPPCHAR = c.POINTER(PPCHAR) # int func (int handle, int *numVars, char ***varNames, int **varTypes) func = c.CDLL('func').func func.restype = INT func.argtypes = [INT,PINT,PPPCHAR,PPINT] # allocate storage for the out parameters numVars = INT() varNames = PPCHAR() varTypes = PINT() print func(5,c.byref(numVars),c.byref(varNames),c.byref(varTypes)) # numVars contains size of returned arrays. Recast to access. varNamesArray = c.cast(varNames,c.POINTER(PCHAR * numVars.value)) varTypesArray = c.cast(varTypes,c.POINTER(INT * numVars.value)) for value in varNamesArray.contents: print value for value in varTypesArray.contents: print value --- output ------------------------------- 6 one two three 1 2 3 Hope this helps, -Mark From lie.1296 at gmail.com Sun Dec 20 19:18:38 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Mon, 21 Dec 2009 11:18:38 +1100 Subject: numpy performance and random numbers In-Reply-To: References: <69df23c3-ee4e-4c8f-9d66-581e3e272fad@m38g2000yqd.googlegroups.com> <4b2d36db$1@dnews.tpgi.com.au> <9a71ed3e-de34-4d39-b2d5-66e9ff1baa91@m3g2000yqf.googlegroups.com> <4b2d73ec$1@dnews.tpgi.com.au> <125c6868-6200-42ce-aee0-9c313b006966@b2g2000yqi.googlegroups.com> <4b2df2be$1@dnews.tpgi.com.au> Message-ID: <4b2ebee0$1@dnews.tpgi.com.au> On 12/21/2009 1:13 AM, David Cournapeau wrote: > But the OP case mostly like falls in your estimated 0.01% case. PRNG > quality is essential for reliable Monte Carlo procedures. I don't > think long period is enough to guarantee those good properties for // > random generators - at least it is not obvious to me. Now it's not, long periods are not indicator of quality. I was responding to the chance of unexpected repetition of sequence because of collision of entry points. Long periods is an indicator that the chance of entry point collision should be low enough. Long periods (alone) doesn't mean anything to the quality of the randomness itself. From timr at probo.com Sun Dec 20 19:24:00 2009 From: timr at probo.com (Tim Roberts) Date: Sun, 20 Dec 2009 16:24:00 -0800 Subject: strptime not strict enough References: <4ssgi55t36uocn9uqh27ouevnd0chfuiov@4ax.com> Message-ID: Chris Rebert wrote: >On Tue, Dec 15, 2009 at 9:47 PM, Tim Roberts wrote: >> Tobias Weber wrote: >>> >>>despite the directives for leading zero stime.strptime('09121', >>>'%y%m%d') returns the first of December. Shouldn't it raise ValueError? >> >> Python merely calls the strptime function in your C run-time library. ?If >> it sucks, so will time.strptime. > >Er, no, wrong: http://svn.python.org/view/python/trunk/Lib/_strptime.py?view=markup Chris is right, I'm wrong. time.strptime is a C function that loads and runs the version in the _strptime.py module. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From ppearson at nowhere.invalid Sun Dec 20 20:41:17 2009 From: ppearson at nowhere.invalid (Peter Pearson) Date: 21 Dec 2009 01:41:17 GMT Subject: numpy performance and random numbers References: <00b63dbe$0$15654$c3e8da3@news.astraweb.com> <69df23c3-ee4e-4c8f-9d66-581e3e272fad@m38g2000yqd.googlegroups.com> <4b2d36db$1@dnews.tpgi.com.au> Message-ID: <7p821tFgauU1@mid.individual.net> On Sun, 20 Dec 2009 07:26:03 +1100, Lie Ryan wrote: > On 12/20/2009 4:02 AM, Carl Johan Rehn wrote: > >>>>> Parallel PRNGs are an unsolved problem in computer science. >> >> Thanks again for sharing your knowledge. I had no idea. This means >> that if I want to speed up my application I have to go for the fastest >> random generator and focus on other parts of my code that can be >> vectorized. > > If you don't care about "repeatability" (which is already extremely > difficult in parallel processing even without random number generators), > you can just start two PRNG at two distinct states (and probably from > two different algorithms) and they will each spews out two independent > streams of random numbers. What was "unsolved" was the "pseudo-" part of > the random number generation, which guarantee perfect replayability in > all conditions. Why not use a good cipher, such as AES, to generate a pseudorandom bit stream by encrypting successive integers? If you use a different key for each instance, you'll have exactly the independence you want. And if you can detect any statistical anomaly in the output, you automatically have the most exciting paper to be published in the next issue of the Journal of Cryptology. Minor caveats: 1. This might be slower than another approach, but maybe not: AES is much faster than the ciphers of the old days. 2. Since AES(key,i) != AES(key,j) if i != j, there will be a dearth of duplicates, which will become statistically detectable around the time i has been incremented 2**64 times. There are many reasons why this might not bother you (one: you don't plan to use so many values; two: you might use the 128-bit AES output in pieces, rather than as a single value, in which case duplicates will appear among the pieces at the right rate), but if it *does* bother you, it can be fixed by using i^AES(key,i) instead of just AES(key,i). -- To email me, substitute nowhere->spamcop, invalid->net. From wolftracks at invalid.com Sun Dec 20 21:16:52 2009 From: wolftracks at invalid.com (W. eWatson) Date: Sun, 20 Dec 2009 18:16:52 -0800 Subject: Windows, IDLE, __doc_, other Message-ID: When I use numpy.__doc__ in IDLE under Win XP, I get a heap of words without reasonable line breaks. "\nNumPy\n=====\n\nProvides\n 1. An array object of arbitrary homogeneous items\n 2. Fast mathematical operations over arrays\n 3. Linear Algebra, Fourier Transforms, Random Number ... Is there a way to get this formated properly. If I use dir(numpy), I get yet a very long list that starts as: ['ALLOW_THREADS', 'BUFSIZE', 'CLIP', 'DataSource', 'ERR_CALL', 'ERR_DEFAULT', 'ERR_DEFAULT2', 'ERR_IGNORE', 'ERR_LOG', 'ERR_PRINT', 'ERR_RAISE', 'ERR_WARN', 'FLOATING_POINT_SUPPORT', 'FPE_DIVIDEBYZERO', 'FPE_INVALID', 'FPE_OVERFLOW', 'FPE_UNDERFLOW', 'False_', 'Inf', 'Infinity', 'MAXDIMS', 'MachAr', 'NAN', 'NINF', 'NZERO', 'NaN', 'PINF', 'PZERO', 'PackageLoader', 'RAISE', 'RankWarning', 'SHIFT_DIVIDEBYZERO', 'SHIFT_INVALID', 'SHIFT_OVERFLOW', 'SHIFT_UNDERFLOW', 'ScalarType', 'Tester', 'True_', 'UFUNC_BUFSIZE_DEFAULT' ... I see this might be a dictionary. What can I do to make it more readable or useful, or is that it? Is there a more abc as in Linux? It the IDLE shell, it's not possible to retrieve lines entered earlier without copying them. Is there an edit facility? From wolftracks at invalid.com Sun Dec 20 21:19:32 2009 From: wolftracks at invalid.com (W. eWatson) Date: Sun, 20 Dec 2009 18:19:32 -0800 Subject: Windows, IDLE, __doc_, other In-Reply-To: References: Message-ID: Add to this. Isn't there a way to see the arguments and descriptions of functions? From tekion at gmail.com Sun Dec 20 21:23:39 2009 From: tekion at gmail.com (tekion) Date: Sun, 20 Dec 2009 18:23:39 -0800 (PST) Subject: converting string to a date format Message-ID: <0b17f6a7-658b-4249-8697-2b7218de2e25@g26g2000yqe.googlegroups.com> All, I know there is a datetime module for converting and manipulate date format. I have this string date format: 24/Nov/2009:10:39:03 -0500 and would like to convert it to a date format of "2009-11-24 10:39:03". At the moment I am reading datetime module trying to find out if I could do it with datetime module. Does any one know of a way besides slashing my way through it using string split function? Thanks. From lie.1296 at gmail.com Sun Dec 20 21:43:17 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Mon, 21 Dec 2009 13:43:17 +1100 Subject: Windows, IDLE, __doc_, other In-Reply-To: References: Message-ID: <4b2ee0c7$1@dnews.tpgi.com.au> On 12/21/2009 1:19 PM, W. eWatson wrote: > When I use numpy.__doc__ in IDLE under Win XP, I get a heap of words without reasonable line breaks. > > "\nNumPy\n=====\n\nProvides\n 1. An array object of arbitrary homogeneous items\n 2. Fast mathematical operations over arrays\n 3. Linear Algebra, Fourier Transforms, Random Number > .... > > Is there a way to get this formated properly. help(object) > If I use dir(numpy), I get yet a very long list that starts as: > ['ALLOW_THREADS', 'BUFSIZE', 'CLIP', 'DataSource', 'ERR_CALL', 'ERR_DEFAULT', 'ERR_DEFAULT2', 'ERR_IGNORE', 'ERR_LOG', 'ERR_PRINT', 'ERR_RAISE', 'ERR_WARN', 'FLOATING_POINT_SUPPORT', 'FPE_DIVIDEBYZERO', 'FPE_INVALID', 'FPE_OVERFLOW', 'FPE_UNDERFLOW', 'False_', 'Inf', 'Infinity', 'MAXDIMS', 'MachAr', 'NAN', 'NINF', 'NZERO', 'NaN', 'PINF', 'PZERO', 'PackageLoader', 'RAISE', 'RankWarning', 'SHIFT_DIVIDEBYZERO', 'SHIFT_INVALID', 'SHIFT_OVERFLOW', 'SHIFT_UNDERFLOW', 'ScalarType', 'Tester', 'True_', 'UFUNC_BUFSIZE_DEFAULT' > .... > I see this might be a dictionary. What can I do to make it more readable or useful, or is that it? Is there a more abc as in Linux? You can use pprint module: import pprint pprint.pprint(dir(object)) though help() is usually better > It the IDLE shell, it's not possible to retrieve lines entered earlier without copying them. Is there an edit facility? Press Alt+P (Previous) and Alt+N (Next). Or you can click/select on the line you want to copy and press Enter. >> Add to this. Isn't there a way to see the arguments and descriptions of >> functions? Use help(). Or if you're doing this without human intervention, use `inspect` module. From python at mrabarnett.plus.com Sun Dec 20 21:46:55 2009 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 21 Dec 2009 02:46:55 +0000 Subject: converting string to a date format In-Reply-To: <0b17f6a7-658b-4249-8697-2b7218de2e25@g26g2000yqe.googlegroups.com> References: <0b17f6a7-658b-4249-8697-2b7218de2e25@g26g2000yqe.googlegroups.com> Message-ID: <4B2EE19F.7060605@mrabarnett.plus.com> tekion wrote: > All, > I know there is a datetime module for converting and manipulate date > format. I have this string date format: 24/Nov/2009:10:39:03 -0500 > and would like to convert it to a date format of "2009-11-24 > 10:39:03". At the moment I am reading datetime module trying to find > out if I could do it with datetime module. Does any one know of a way > besides slashing my way through it using string split function? Use datetime.datetime.strptime() to parse the string; you'll need to remove the timezone from the string first. The format you need to provide is the same one you'd use if you were creating the string from a datetime. Then call the .strftime() method of the resulting datetime object, providing the appropriate format to create the new string. From benjamin.kaplan at case.edu Sun Dec 20 21:51:10 2009 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Sun, 20 Dec 2009 21:51:10 -0500 Subject: Windows, IDLE, __doc_, other In-Reply-To: References: Message-ID: On Sun, Dec 20, 2009 at 9:16 PM, W. eWatson wrote: > When I use numpy.__doc__ in IDLE under Win XP, I get a heap of words without > reasonable line breaks. > > "\nNumPy\n=====\n\nProvides\n ?1. An array object of arbitrary homogeneous > items\n ?2. Fast mathematical operations over arrays\n ?3. Linear Algebra, > Fourier Transforms, Random Number > ... > > Is there a way to get this formated properly. > when you just do >> numpy.__doc__ you get the repr of the string, which uses the escaped characters. You'd get the same thing in the interactive interpreter. Try using print if you want to see it correctly. > If I use dir(numpy), I get yet a very long list that starts as: > ['ALLOW_THREADS', 'BUFSIZE', 'CLIP', 'DataSource', 'ERR_CALL', > 'ERR_DEFAULT', 'ERR_DEFAULT2', 'ERR_IGNORE', 'ERR_LOG', 'ERR_PRINT', > 'ERR_RAISE', 'ERR_WARN', 'FLOATING_POINT_SUPPORT', 'FPE_DIVIDEBYZERO', > 'FPE_INVALID', 'FPE_OVERFLOW', 'FPE_UNDERFLOW', 'False_', 'Inf', 'Infinity', > 'MAXDIMS', 'MachAr', 'NAN', 'NINF', 'NZERO', 'NaN', 'PINF', 'PZERO', > 'PackageLoader', 'RAISE', 'RankWarning', 'SHIFT_DIVIDEBYZERO', > 'SHIFT_INVALID', 'SHIFT_OVERFLOW', 'SHIFT_UNDERFLOW', 'ScalarType', > 'Tester', 'True_', 'UFUNC_BUFSIZE_DEFAULT' > ... > I see this might be a dictionary. What can I do to make it more readable or > useful, or is that it? Is there a more abc as in Linux? > It's a list, not a dictionary. pprint.pprint will print 1 item per line. > It the IDLE shell, it's not possible to retrieve lines entered earlier > without copying them. Is there an edit facility? > -- > http://mail.python.org/mailman/listinfo/python-list > From ben+python at benfinney.id.au Sun Dec 20 21:54:53 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Mon, 21 Dec 2009 13:54:53 +1100 Subject: converting string to a date format References: <0b17f6a7-658b-4249-8697-2b7218de2e25@g26g2000yqe.googlegroups.com> Message-ID: <87bphtyr2a.fsf@benfinney.id.au> tekion writes: > I have this string date format: 24/Nov/2009:10:39:03 -0500 and would > like to convert it to a date format of "2009-11-24 10:39:03". This should, ideally, consist of two separate operations: * parse the string, using a specific format, to create a ?datetime? object * create a string representation of the datetime using your preferred string format > At the moment I am reading datetime module trying to find out if I > could do it with datetime module. Unfortunately, the manipulation of time data has historically been a bit messy in the Python standard library; the functionality for round-trip conversion of strings and datetime values involves both the ?datetime? and ?time? modules. If you have Python 2.6 or greater, you can perform the above steps using to parse the string to a ?datetime? object, and get a string from the method of that object. If you have an earlier Python, you don't have ?datetime.strptime?. So you'll need to follow the hack suggested in the documentation above for that method, ?datetime(*(time.strptime(date_string, format)[0:6]))?. -- \ ?Because of the impropriety of entertaining guests of the | `\ opposite sex in the bedroom, it is suggested that the lobby be | _o__) used for this purpose.? ?hotel, Zurich | Ben Finney From cs at zip.com.au Sun Dec 20 23:59:31 2009 From: cs at zip.com.au (Cameron Simpson) Date: Mon, 21 Dec 2009 15:59:31 +1100 Subject: Multithreaded python program freezes In-Reply-To: References: Message-ID: <20091221045931.GA15398@cskk.homeip.net> On 20Dec2009 17:36, Andreas R?sdal wrote: | I have some problems with a http proxy which is implemented | in Python 2.6. A few times a day, the proxy begins using 100% CPU | and doesn't work any more. | | I have created a thread dump when the problem occurs here: | http://www.pvv.ntnu.no/~andrearo/thread-dump.html | | This is a thread dump during normal operation: | http://www.pvv.ntnu.no/~andrearo/thread-dump-normal.html These two URLs don't work for me. [...] | Any advice on why this Python program appears to freeze? Is there anything | more I can do to find out why this problem occurs? Sounds like a livelock: http://en.wikipedia.org/wiki/Deadlock#Livelock or busy lock. Can you find out which bits of your program are busy? Are there places in your code that loop, polling for data, instead of using blocking I/O. With a network proxy, a typical place that might happen is a loop testing select() (or its poll-like friends) with a short or zero timeout on inactive file handles. Cheers, -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ No electrons were harmed in the production of this message. - Dr. P. Gensheimer From rami.chowdhury at gmail.com Mon Dec 21 00:02:02 2009 From: rami.chowdhury at gmail.com (Rami Chowdhury) Date: Sun, 20 Dec 2009 21:02:02 -0800 Subject: numpy performance and random numbers In-Reply-To: <7p821tFgauU1@mid.individual.net> References: <00b63dbe$0$15654$c3e8da3@news.astraweb.com> <69df23c3-ee4e-4c8f-9d66-581e3e272fad@m38g2000yqd.googlegroups.com> <4b2d36db$1@dnews.tpgi.com.au> <7p821tFgauU1@mid.individual.net> Message-ID: On Dec 20, 2009, at 17:41 , Peter Pearson wrote: > On Sun, 20 Dec 2009 07:26:03 +1100, Lie Ryan wrote: >> On 12/20/2009 4:02 AM, Carl Johan Rehn wrote: >> >>>>>> Parallel PRNGs are an unsolved problem in computer science. >>> >>> Thanks again for sharing your knowledge. I had no idea. This means >>> that if I want to speed up my application I have to go for the fastest >>> random generator and focus on other parts of my code that can be >>> vectorized. >> >> If you don't care about "repeatability" (which is already extremely >> difficult in parallel processing even without random number generators), >> you can just start two PRNG at two distinct states (and probably from >> two different algorithms) and they will each spews out two independent >> streams of random numbers. What was "unsolved" was the "pseudo-" part of >> the random number generation, which guarantee perfect replayability in >> all conditions. > > Why not use a good cipher, such as AES, to generate a pseudorandom > bit stream by encrypting successive integers? Isn't the Fortuna PRNG based around that approximate concept? ------------- Rami Chowdhury "Never assume malice when stupidity will suffice." -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) From aahz at pythoncraft.com Mon Dec 21 00:04:28 2009 From: aahz at pythoncraft.com (Aahz) Date: 20 Dec 2009 21:04:28 -0800 Subject: The fun of Python (was Re: When will Python 3 be fully deployed) References: Message-ID: In article , Roy Smith wrote: >In article , aahz at pythoncraft.com (Aahz) >wrote: >> >> -- >> Looking back over the years, after I learned Python I realized that I >> never really had enjoyed programming before. > >That's a sad commentary. Python is fun to use, but surely there are other >ways you can enjoy programming? Not really. I've been programming more than thirty years, and the closest I came previously to enjoying programming was Turbo Pascal, and even that has too much tedium and lack of brain-fit. Before Turbo Pascal, there was BASIC on an HP-1000. Afterward came HP-41, Ada, FORTRAN, Paradox PAL, C, Perl, and there must be some others I'm forgetting. Thankfully, I didn't learn Java until after I'd been programming in Python for a while. (And arguably I still haven't learned Java despite writing a PGP encryption wrapper around BouncyCastle.) Programming is difficult to begin with, and everything other than Python just gets in my way. To be fair, my quote isn't entirely honest: I never called myself a programmer before I learned Python because I didn't really like it. It took Python to make me realize that programming *could* be fun, or at least not annoying enough to keep me from making a career of programming. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Looking back over the years, after I learned Python I realized that I never really had enjoyed programming before. From ben+python at benfinney.id.au Mon Dec 21 00:18:59 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Mon, 21 Dec 2009 16:18:59 +1100 Subject: The fun of Python References: Message-ID: <877hsgzyyk.fsf@benfinney.id.au> aahz at pythoncraft.com (Aahz) writes: > I never called myself a programmer before I learned Python because I > didn't really like it. It took Python to make me realize that > programming *could* be fun, or at least not annoying enough to keep me > from making a career of programming. +1 QOTW -- \ ?Two hands working can do more than a thousand clasped in | `\ prayer.? ?Anonymous | _o__) | Ben Finney From david.lyon at preisshare.net Mon Dec 21 00:42:59 2009 From: david.lyon at preisshare.net (David Lyon) Date: Mon, 21 Dec 2009 00:42:59 -0500 Subject: Live Video Capture using Python In-Reply-To: <3de8e1f70912202145s54a20dc9qc8c1a2cf32041f7a@mail.gmail.com> References: <73045cca0912201305kea3811dr70a7a65c5556c219@mail.gmail.com> <3de8e1f70912202145s54a20dc9qc8c1a2cf32041f7a@mail.gmail.com> Message-ID: <8380120472fc5f5db6e900161df40aad@preisshare.net> Also try.. http://www.unixuser.org/~euske/python/vnc2flv/index.html On Mon, 21 Dec 2009 11:15:32 +0530, Banibrata Dutta wrote: > Have you searched the archives of this list ? I remember seeing a related > discussion 5-6 months back. > > On Mon, Dec 21, 2009 at 2:35 AM, aditya shukla > wrote: > >> Hello Guys, >> >> I am trying to capture images from a live broadcast of a "cricket match" >> or >> say any video using python. I can see the video in the browser.My aim is >> to >> capture the video at any moment and create an images.Searching on google >> turns up http://videocapture.sourceforge.net/ .I am not sure if this >> would be help here.I would appreciate if someone points me in the right >> direction. >> >> >> Thanks >> >> Aditya >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> >> From banibrata.dutta at gmail.com Mon Dec 21 00:45:32 2009 From: banibrata.dutta at gmail.com (Banibrata Dutta) Date: Mon, 21 Dec 2009 11:15:32 +0530 Subject: Live Video Capture using Python In-Reply-To: <73045cca0912201305kea3811dr70a7a65c5556c219@mail.gmail.com> References: <73045cca0912201305kea3811dr70a7a65c5556c219@mail.gmail.com> Message-ID: <3de8e1f70912202145s54a20dc9qc8c1a2cf32041f7a@mail.gmail.com> Have you searched the archives of this list ? I remember seeing a related discussion 5-6 months back. On Mon, Dec 21, 2009 at 2:35 AM, aditya shukla wrote: > Hello Guys, > > I am trying to capture images from a live broadcast of a "cricket match" or > say any video using python. I can see the video in the browser.My aim is to > capture the video at any moment and create an images.Searching on google > turns up http://videocapture.sourceforge.net/ .I am not sure if this > would be help here.I would appreciate if someone points me in the right > direction. > > > Thanks > > Aditya > > -- > http://mail.python.org/mailman/listinfo/python-list > > -- regards, Banibrata http://www.linkedin.com/in/bdutta -------------- next part -------------- An HTML attachment was scrubbed... URL: From sridharr at activestate.com Mon Dec 21 01:38:28 2009 From: sridharr at activestate.com (Sridhar Ratnakumar) Date: Sun, 20 Dec 2009 22:38:28 -0800 Subject: how do I set a Python installation as the default under windows ? In-Reply-To: <4B2DEFCC.4080607@gmail.com> References: <4B2D0451.9080000@gmail.com> <4B2D6DCD.8080108@holdenweb.com> <4B2DEFCC.4080607@gmail.com> Message-ID: <4B2F17E4.7010302@activestate.com> On 12/20/2009 1:35 AM, Stef Mientki wrote: > Steve Holden wrote: >> Stef Mientki wrote: >> >>> hello, >>> >>> I just upgraded from Python 2.5 to 2.6. >>> Most of the things work, >>> but I'm struggling with one issue, >>> when I start Python in a command window, >>> it still uses Python 2.5. >>> >>> Is there a way to get Python 2.6 as my default Python environment ? >>> >>> thanks, >>> Stef Mientki >>> >> >> It's a matter of replacing C:\Python25 with C:\Python26 in your PATH >> environment variable, which is what the Windows command processor uses >> to fined executable programs. > Thanks Steve, > that works exactly as you say. Additionally if you're using ActivePython, you do not even have to fiddle with PATH because: 1) C:\PythonXY (and %APPDATA%\Python\Scripts) is automatically added to %PATH%. 2) "python.exe" is also available as "python26.exe", so you can simply type "python26" in the console to get Python 2.6 (if another version of ActivePython/Python is already installed). -srid From gagsl-py2 at yahoo.com.ar Mon Dec 21 02:33:53 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 21 Dec 2009 04:33:53 -0300 Subject: Class variables static by default? References: <4b2d735b$1@dnews.tpgi.com.au> <033d925d$0$1305$c3e8da3@news.astraweb.com> Message-ID: En Sun, 20 Dec 2009 01:16:16 -0300, Steven D'Aprano escribi?: > On Sun, 20 Dec 2009 11:44:11 +1100, Lie Ryan wrote: > >> In python, 'class variable' is a variable that belongs to a class; not >> to the instance and is shared by all instance that belong to the class. > > Surely, since string variables are strings, and float variables are > floats, and bool variables are bools, and module variables are modules, a > class variable will be a class and an instance variable will be an > instance? > >> In contrast, 'instance variable' belongs to the instance, and each >> instance can make their instance variables refers to different objects >> than the other instances. > > The usual term used in Python is "class attribute" and "instance > attribute" for the named fields of a class or instance. I agree with your interpretation of "class variable", but you'll have to rewrite parts of the official Python documentation so it becomes consistent with it. The phrase "class variable" appears about 30 times, always meaning "class attribute"; four of them in the Language Reference, section "Class definitions", where the OP's issue is discussed: "Programmer?s note: Variables defined in the class definition are class variables; they are shared by all instances. To create instance variables, they can be set in a method with self.name = value. Both class and instance variables are accessible through the notation ?self.name?, and an instance variable hides a class variable with the same name when accessed in this way. Class variables can be used as defaults for instance variables, but using mutable values there can lead to unexpected results. For new-style classes, descriptors can be used to create instance variables with different implementation details." http://docs.python.org/reference/compound_stmts.html#class-definitions -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Mon Dec 21 02:35:14 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 21 Dec 2009 04:35:14 -0300 Subject: How can I get the target platform info of a dll with Python 3.1.1? References: <01772f90-856c-4723-9f72-366a5d088ed5@k4g2000yqb.googlegroups.com> Message-ID: En Mon, 14 Dec 2009 07:25:45 -0300, W00D00 escribi?: > On dec. 12, 03:18, "Gabriel Genellina" wrote: >> En Fri, 11 Dec 2009 16:39:37 -0300, Isti >> escribi?: >> >> > I have manydllfiles and I would like to select them into two >> > different folders (PC and PPC). For this I need to know the target >> > platform of thedllfile or any other details about its platform. >> >> Look at sys.platform and the platform module. > > The platform module gives you information about the platform where you > are running on with your script and not about the not loaded dll(s). Sorry, I misunderstood you. (completely unrelated to your problem: see PEP8 at http://www.python.org/dev/peps/pep-0008/ ) -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Mon Dec 21 02:35:23 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 21 Dec 2009 04:35:23 -0300 Subject: Mails & encoding References: Message-ID: En Sun, 20 Dec 2009 07:46:02 -0300, Lord Eldritch escribi?: > I have a CGI written in Python to process a form a read/write a text > file (a > minimal database). It runs in a Linux box with and it looks all the > encoding is UTF8. [...] > - Related to the former one: the CGI sends an email with stress marks and > other characters. I can read it with out any problem in my Kmail client > because it detects the encoding. But I saw that most of the users are > gonna > read it in a webmail service where the characters (UTF8) are not > recognized. > Can I force a encoding when I send an email? kind of: > > mail(adress,'My title', mytext.encode'iso9865') Yes, you can, and you should. Make sure the Content-Type (and probably Content-Transfer-Encoding too) header fields are correct. How to set them, depends on how you build the email to be sent (and the Python version in use). -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Mon Dec 21 02:35:36 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 21 Dec 2009 04:35:36 -0300 Subject: PyArg_ParseTupleAndKeywords in Python3.1 References: <0a0b822c-8d57-4816-8563-5fd8ff39f7f1@p8g2000yqb.googlegroups.com> <83f08b89-6b61-4005-9fbd-c9a01da36654@d9g2000prh.googlegroups.com> <408e4acd-3182-4d08-bcb4-d4ff1632d9c2@l13g2000yqb.googlegroups.com> <2a0f6103-3615-4d6a-bd6c-e0bfcbf37eb6@26g2000yqo.googlegroups.com> <89c38c820912190236k3cbf2a69kb556e614c921dfb@mail.gmail.com> Message-ID: En Sat, 19 Dec 2009 07:36:59 -0300, Emeka escribi?: > Okay if that is the case, why do we need it? By having int a = 65, b = > 66 , > why should we also have *kwlist[]? > > > > static PyObject* foo(PyObject *self, PyObject *args, PyObject *kwrds) > { > int a=65, b=66; > char *kwlist[] = {"a", "b", NULL}; > if (!PyArg_ParseTupleAndKeywords(args, kwrds, "|CC", kwlist, &a, > &b)) > return NULL; > return Py_BuildValue("(CC)", a, b); > } It's not related to default values. foo(x=30) should raise an error; the allowed parameter names are only 'a' and 'b', not 'x'. -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Mon Dec 21 02:35:54 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 21 Dec 2009 04:35:54 -0300 Subject: AttributeError: logging module bug ? References: <4dc0cfea0912151005g7cf389ddx2e3d9d5a62338344@mail.gmail.com> <4B27D721.2010707@mrabarnett.plus.com> <4dc0cfea0912151112n235fa28vd509a36ddfc4ade9@mail.gmail.com> <4B2C4602.2070401@mycircuit.org> Message-ID: En Sat, 19 Dec 2009 00:18:26 -0300, Peter escribi?: > This was somehow unexpected for me, since in a module using logger.py, I > could use either import: > > from mylogger import logger # without package name > > or > > from of.mylogger import logger # with package name > > but this does not seem to work for the class specification in the config > file (only the former works). Then you have a big problem with the Python search path (sys.path): you should *not* have two different (absolute) ways to refer to the same module, ever. If "of" is a package, it should not be listed in sys.path -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Mon Dec 21 02:42:34 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 21 Dec 2009 04:42:34 -0300 Subject: tkinter import problem References: <6e1fb0a50912192104l20677d1eq9e815422f204d6f3@mail.gmail.com> Message-ID: En Sun, 20 Dec 2009 02:04:17 -0300, harish anand escribi?: > I have Mandriva 2010.0 in my laptop. > I installed python3.1 from the repository. > But i am unable to import tkinter in python console. > When I try to import tkinter I get the following error, > `ImportError : No module named _tkinter` > > Am I doing something wrong? I don't know Mandriva, but probably tkinter comes from a separate package (like tkinter, python-tkinter, python-tk, or something like that) -- Gabriel Genellina From alfps at start.no Mon Dec 21 02:53:21 2009 From: alfps at start.no (Alf P. Steinbach) Date: Mon, 21 Dec 2009 08:53:21 +0100 Subject: Windows, IDLE, __doc_, other In-Reply-To: References: Message-ID: * W. eWatson: > When I use numpy.__doc__ in IDLE under Win XP, I get a heap of words > without reasonable line breaks. > > "\nNumPy\n=====\n\nProvides\n 1. An array object of arbitrary > homogeneous items\n 2. Fast mathematical operations over arrays\n 3. > Linear Algebra, Fourier Transforms, Random Number > ... > > Is there a way to get this formated properly. print( numpy.__doc__ ) (For Python 2.x you can and best should leave out the parenthesis) > If I use dir(numpy), I get yet a very long list that starts as: > ['ALLOW_THREADS', 'BUFSIZE', 'CLIP', 'DataSource', 'ERR_CALL', > 'ERR_DEFAULT', 'ERR_DEFAULT2', 'ERR_IGNORE', 'ERR_LOG', 'ERR_PRINT', > 'ERR_RAISE', 'ERR_WARN', 'FLOATING_POINT_SUPPORT', 'FPE_DIVIDEBYZERO', > 'FPE_INVALID', 'FPE_OVERFLOW', 'FPE_UNDERFLOW', 'False_', 'Inf', > 'Infinity', 'MAXDIMS', 'MachAr', 'NAN', 'NINF', 'NZERO', 'NaN', 'PINF', > 'PZERO', 'PackageLoader', 'RAISE', 'RankWarning', 'SHIFT_DIVIDEBYZERO', > 'SHIFT_INVALID', 'SHIFT_OVERFLOW', 'SHIFT_UNDERFLOW', 'ScalarType', > 'Tester', 'True_', 'UFUNC_BUFSIZE_DEFAULT' > ... > I see this might be a dictionary. What can I do to make it more readable > or useful, or is that it? Is there a more abc as in Linux? Something like (off the cuff, fix if eroRs!) for name in dir[numpy]: if name.startswith( "_" ): pass else: doc_lines = getattr( numpy, name ).__doc__.split() print( format( "{0:25} {1}".format( name, doc_lines[0] ) ) Should ideally work whether you use Python 2.x or 3.x. But as mentioned I just typed that in so there may be eroRs. > It the IDLE shell, it's not possible to retrieve lines entered earlier > without copying them. Is there an edit facility? I suggest you download a programmers' editor (like Notepad++ or PsPad) for programming work and use the basic Python interpreter for interactive work. The basic interpreter lives in a standard Window console window where you can use up and down arrow keys, F8 completion, F7 for list of earlier commands, etc (as documented by the doskey command in the Windows command interpreter). Just forget IDLE in windows: while Windows console windows are something from the middle ages, IDLE seems to stem from a period before that! Cheers & hth., - Alf PS: Shameless plug: take a look at , it's for Windows. From steven at REMOVE.THIS.cybersource.com.au Mon Dec 21 02:53:51 2009 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 21 Dec 2009 07:53:51 GMT Subject: Creating Classes References: <26848375.post@talk.nabble.com> <4B2C5B4C.2000103@ieee.org> Message-ID: On Sun, 20 Dec 2009 11:11:54 -0500, Steve Holden wrote: > Dave Angel wrote: > [...] >> We were talking about 2.x And I explicitly mentioned 3.x because if >> one develops code that depends on old-style classes, they'll be in >> trouble with 3.x, which has no way to specify old-style classes. In >> 3.x, all classes are new-style. And although it'll no longer matter >> whether you specify (object), it doesn't do any harm. As I said, it's >> a good habit for a beginner to get into when defining classes. >> > I maintain that this almost-cargo-cult belief over-complicates things > for language beginners. How long do you have to be using Python before > you make your first super() call? That depends on who you are and what you're doing. Are you a n00b who has never programmed before? An old Fortran or Pascal dinosaur who doesn't like that new fangled object stuff? A former Java OO guru whose class hierarchies are 85 classes deep on average? Someone who just discovered multiple inheritance and now everything looks like a nail? > How many programs behave differently > with old-style vs. new-style classes? Any program that uses properties will behave differently. __getattribute__ and __slots__ will not work at all in old-style classes. There will be subtle differences, e.g. isinstance(type, MyClass) will return False if MyClass is old-style. The default repr and str of instances will look different (which may or may not count as different behaviour). Speed and efficiency will be different. So I guess the correct answer to your question is "All of them". The interesting question is, what's the magnitude of the differences? The advice I used to give was, unless you care about the difference, always inherit from object because new-style classes are the way of the future. Unfortunately, it is no longer obvious whether something in isolation is a new-style or old-style class, as you have to know the target Python version. -- Steven From alfps at start.no Mon Dec 21 02:56:26 2009 From: alfps at start.no (Alf P. Steinbach) Date: Mon, 21 Dec 2009 08:56:26 +0100 Subject: Windows, IDLE, __doc_, other In-Reply-To: References: Message-ID: * Alf P. Steinbach: > * W. eWatson: >> When I use numpy.__doc__ in IDLE under Win XP, I get a heap of words >> without reasonable line breaks. >> >> "\nNumPy\n=====\n\nProvides\n 1. An array object of arbitrary >> homogeneous items\n 2. Fast mathematical operations over arrays\n 3. >> Linear Algebra, Fourier Transforms, Random Number >> ... >> >> Is there a way to get this formated properly. > > print( numpy.__doc__ ) > > (For Python 2.x you can and best should leave out the parenthesis) > > >> If I use dir(numpy), I get yet a very long list that starts as: >> ['ALLOW_THREADS', 'BUFSIZE', 'CLIP', 'DataSource', 'ERR_CALL', >> 'ERR_DEFAULT', 'ERR_DEFAULT2', 'ERR_IGNORE', 'ERR_LOG', 'ERR_PRINT', >> 'ERR_RAISE', 'ERR_WARN', 'FLOATING_POINT_SUPPORT', 'FPE_DIVIDEBYZERO', >> 'FPE_INVALID', 'FPE_OVERFLOW', 'FPE_UNDERFLOW', 'False_', 'Inf', >> 'Infinity', 'MAXDIMS', 'MachAr', 'NAN', 'NINF', 'NZERO', 'NaN', >> 'PINF', 'PZERO', 'PackageLoader', 'RAISE', 'RankWarning', >> 'SHIFT_DIVIDEBYZERO', 'SHIFT_INVALID', 'SHIFT_OVERFLOW', >> 'SHIFT_UNDERFLOW', 'ScalarType', 'Tester', 'True_', >> 'UFUNC_BUFSIZE_DEFAULT' >> ... >> I see this might be a dictionary. What can I do to make it more >> readable or useful, or is that it? Is there a more abc as in Linux? > > Something like (off the cuff, fix if eroRs!) > > for name in dir[numpy]: > if name.startswith( "_" ): > pass > else: > doc_lines = getattr( numpy, name ).__doc__.split() Uh oh, 'splitlines' not 'split' ! > print( format( "{0:25} {1}".format( name, doc_lines[0] ) ) > > Should ideally work whether you use Python 2.x or 3.x. > > But as mentioned I just typed that in so there may be eroRs. > > >> It the IDLE shell, it's not possible to retrieve lines entered earlier >> without copying them. Is there an edit facility? > > I suggest you download a programmers' editor (like Notepad++ or PsPad) > for programming work and use the basic Python interpreter for > interactive work. The basic interpreter lives in a standard Window > console window where you can use up and down arrow keys, F8 completion, > F7 for list of earlier commands, etc (as documented by the doskey > command in the Windows command interpreter). Just forget IDLE in > windows: while Windows console windows are something from the middle > ages, IDLE seems to stem from a period before that! > > > Cheers & hth., > > - Alf > > PS: Shameless plug: take a look at http://tinyurl.com/programmingbookP3>, it's for Windows. From bruno.42.desthuilliers at websiteburo.invalid Mon Dec 21 03:25:57 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 21 Dec 2009 09:25:57 +0100 Subject: Anybody use web2py? In-Reply-To: References: <6oidnWzFKdtK6LHWnZ2dnUVZ_opi4p2d@supernews.com> <320b6ef5-8508-4258-9e70-0d987d77e85f@u7g2000yqm.googlegroups.com> Message-ID: <4b2f3115$0$30643$426a74cc@news.free.fr> AppRe Godeck a ?crit : (snip) > Thanks for your replies, I was hoping to hear from some django people as > well. Especially if you choose django over web2py, and why. I don't know what a "django people" is - but if you mean "django core developper", I'm not one of them. Now wrt while I use Django instead of web2py, the answer is quite simple: web2py didn't exist when I started using Django !-) From bruno.42.desthuilliers at websiteburo.invalid Mon Dec 21 03:32:04 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 21 Dec 2009 09:32:04 +0100 Subject: Anybody use web2py? In-Reply-To: <1f7a5a2d-1681-4377-9560-a5d8502d96a1@v25g2000yqk.googlegroups.com> References: <6oidnWzFKdtK6LHWnZ2dnUVZ_opi4p2d@supernews.com> <320b6ef5-8508-4258-9e70-0d987d77e85f@u7g2000yqm.googlegroups.com> <1f7a5a2d-1681-4377-9560-a5d8502d96a1@v25g2000yqk.googlegroups.com> Message-ID: <4b2f3284$0$12689$426a34cc@news.free.fr> Thadeus Burgess a ?crit : (snip) > Spend one > day working on a simple django application, polls, blog, image > gallery, family pet tree, you name it. Then take the next day, and > write the same application with web2py, and you decide. In the end, > both are tools and you need to figure out what is best for YOU. The problem is not how easy it makes to write a *simple* (should I say "braindead" ?) dummy test app, but how easy - or even possible -it makes writing and maintaining a *real-world* complex application. From bruno.42.desthuilliers at websiteburo.invalid Mon Dec 21 03:50:17 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 21 Dec 2009 09:50:17 +0100 Subject: Anybody use web2py? In-Reply-To: <39d22fcc-c721-4da3-952d-f2bc178a3122@l13g2000yqb.googlegroups.com> References: <6oidnWzFKdtK6LHWnZ2dnUVZ_opi4p2d@supernews.com> <39d22fcc-c721-4da3-952d-f2bc178a3122@l13g2000yqb.googlegroups.com> Message-ID: <4b2f36c9$0$14448$426a34cc@news.free.fr> mdipierro a ?crit : > On Dec 19, 12:42 am, AppRe Godeck wrote: >> Just curious if anybody prefers web2py over django, and visa versa. I >> know it's been discussed on a flame war level a lot. I am looking for a >> more intellectual reasoning behind using one or the other. > > Of course I am the most biased person in the world on this topic Indeed !-) > > - In web2py models and controllers are not modules. They are not > imported. They are executed. I assume you mean "executed in an environment defined by the framework"... > This means you do not need to import > basic web2py symbols. They are already defined in the environment that > executes the models and controllers Ok. As far as I'm concerned : show stops here. >(like in Rails). This also means > you do not need to restart the web server when you edit your app. The dev server that comes with Django do the autorestart thing. And you *don't* "edit yoour app" directly on the production server, do you ? > - You have a web based IDE with editor, Why should I care ? I have a way better development environment on my own box. > some conflict resolution, > Mercurial integration, What if use something else than mercurial ? > ticketing system, ...doesn't belong to the framework. FWIW, I already have a ticketing system that's language/techno agnostic, thanks. > > - The DAL supports transactions. It means it will create and/or ALTER > tables for you as your model changes. Err... how does schema changes relates to transactions ??? Now FWIW, when my schema do change, the create/alter table code is usually the most trivial part - there are quite a few other things to do, that no framework will ever be abale to guess. IOW, you *do* have to write a migration script anyway. > > - The DAL has partial support for some legacy databases that do not > have an 'id' auto increment primary key. Django's ORM has full support for tables that don't use an "auto_id" key. > Anyway, I think both system are great. Spend 15 minutes (no more) with > each to make up your mind, and stick with it. Once again, while doing a quick dummy test app can give you a first general "feel" of the tool, it means nothing wrt/ complex real-world applications. From bruno.42.desthuilliers at websiteburo.invalid Mon Dec 21 03:55:40 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 21 Dec 2009 09:55:40 +0100 Subject: Anybody use web2py? In-Reply-To: <0b32658a-b067-4ee6-93ea-ea626384e3f0@z10g2000prh.googlegroups.com> References: <6oidnWzFKdtK6LHWnZ2dnUVZ_opi4p2d@supernews.com> <0b32658a-b067-4ee6-93ea-ea626384e3f0@z10g2000prh.googlegroups.com> Message-ID: <4b2f380c$0$2027$426a74cc@news.free.fr> Anand Vaidya a ?crit : > On Dec 19, 2:42 pm, AppRe Godeck wrote: >> Just curious if anybody prefers web2py over django, and visa versa. I >> know it's been discussed on a flame war level a lot. I am looking for a >> more intellectual reasoning behind using one or the other. > > Hi, > > I am not very familiar with Django, anyway, my reasons for selecting > web2py are: > > - I believe Django naturally "fits in" to a publishing type of > application. I just don't get why so many people have this antipattern... None of the projects I did with Django were on the CMS side. Django is *NOT* a "CMS-growned-into-a-framework" in any way, it's a web development framework, period. Don't "believe", check. > web2py seems to be more focussed on being a front-end to > "applications" not so much for CMS type or newspaper type publishing. Please provide *any* evidence of your (plain wrong) assertions and assumptions... From vmail at mycircuit.org Mon Dec 21 05:16:41 2009 From: vmail at mycircuit.org (Peter) Date: Mon, 21 Dec 2009 11:16:41 +0100 Subject: AttributeError: logging module bug ? In-Reply-To: References: <4dc0cfea0912151005g7cf389ddx2e3d9d5a62338344@mail.gmail.com> <4B27D721.2010707@mrabarnett.plus.com> <4dc0cfea0912151112n235fa28vd509a36ddfc4ade9@mail.gmail.com> <4B2C4602.2070401@mycircuit.org> Message-ID: <4B2F4B09.2070006@mycircuit.org> On 12/21/2009 08:35 AM, Gabriel Genellina wrote: > En Sat, 19 Dec 2009 00:18:26 -0300, Peter escribi?: > >> This was somehow unexpected for me, since in a module using >> logger.py, I could use either import: >> >> from mylogger import logger # without package name >> >> or >> >> from of.mylogger import logger # with package name >> >> but this does not seem to work for the class specification in the >> config file (only the former works). > > Then you have a big problem with the Python search path (sys.path): you > should *not* have two different (absolute) ways to refer to the same > module, ever. > If "of" is a package, it should not be listed in sys.path > Thanks a lot for this helpful advice, in fact the package/module system is for me ( coming from compiled languages with libaries ) the most unintuitive thing in python. Peter From petro at brc.hu Mon Dec 21 06:02:51 2009 From: petro at brc.hu (petro at brc.hu) Date: Mon, 21 Dec 2009 12:02:51 +0100 Subject: No subject Message-ID: <20091221120251.14354mci2k82wlaz@webmail.brc.hu> -- Petro Khoroshyy Institute of Biophysics Biological Research Center of the Hungarian Academy of Sciences Temesvari krt. 62, P.O.Box 521 Szeged, Hungary, H-6701 ---------------------------------------------------------------- This message was sent using IMP, the Internet Messaging Program. From jeanmichel at sequans.com Mon Dec 21 06:03:58 2009 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Mon, 21 Dec 2009 12:03:58 +0100 Subject: [ANN] pylint 0.19 / astng 0.19.2 In-Reply-To: <20091218175547.GA11027@lupus.logilab.fr> References: <20091218123918.GH24924@lupus.logilab.fr> <4B2BBACB.1060605@sequans.com> <20091218175547.GA11027@lupus.logilab.fr> Message-ID: <4B2F561E.70504@sequans.com> Sylvain Th?nault wrote: > On 18 d?cembre 18:24, Jean-Michel Pichavant wrote: > >> Sylvain Th?nault wrote: >> >>> Hi, >>> >>> I'm very pleased to announce the release of pylint 0.19 / astng 0.19.2 release! >>> >>> More information / download on http://www.logilab.org/project/pylint/0.19.0. >>> >>> This is a "community" release, including the work we've done during the pylint >>> bug day [1] and patches mostly from James Lingard and Vincent Ferotin. >>> >>> Many thanks to James Lingard which provided two long waited features: >>> >>> * check of function call arguments >>> * check string interpolation consistency >>> >>> >>> So, happy christmas, enjoy! >>> >>> [1] http://www.logilab.org/blogentry/19260 >>> >> I have troubles after updating pylint: >> >> easy_install pylint -U --install-dir >> /opt/tools/python/python2.3/site-packages >> >> >>> pylint >>> >> File "/opt/tools/python/python2.3/site-packages/logilab_astng-0.19.2-py2.5.egg/logilab/astng/infutils.py", >> line 28, in >> from logilab.astng._nodes import Proxy_, List, Tuple, Function, >> If, TryExcept >> ImportError: No module named _nodes >> >> There is no _nodes.py file within the egg. Has anyone experienced >> the same issue ? >> > > yep someone else on the list have the same pb. I think I've identified it: > > python setup.py register sdist upload > > *doesn't* regenerate MANIFEST if one is found... So packages uploaded to pypi > had some missing files. Should be fixed now, sorry for this pb. > Works fine by now. Thanks for providing such great tool. JM From ndbecker2 at gmail.com Mon Dec 21 06:09:47 2009 From: ndbecker2 at gmail.com (Neal Becker) Date: Mon, 21 Dec 2009 06:09:47 -0500 Subject: use mudflap with python extensions? Message-ID: Is it possible to build python extensions using gcc's -fmudflap to check memory access? I'm not real familiar with mudflap usage, not sure if it works on building shared objects. Perhaps it requires a rebuilt python main? Hopefully not. From petro at brc.hu Mon Dec 21 06:10:16 2009 From: petro at brc.hu (petro at brc.hu) Date: Mon, 21 Dec 2009 12:10:16 +0100 Subject: No subject Message-ID: <20091221121016.70496te5fsykr0k8@webmail.brc.hu> -- Petro Khoroshyy Institute of Biophysics Biological Research Center of the Hungarian Academy of Sciences Temesvari krt. 62, P.O.Box 521 Szeged, Hungary, H-6701 ---------------------------------------------------------------- This message was sent using IMP, the Internet Messaging Program. From bruno.42.desthuilliers at websiteburo.invalid Mon Dec 21 06:34:46 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 21 Dec 2009 12:34:46 +0100 Subject: Moving from PHP to Python. Is it Possible In-Reply-To: References: <7ole38F3qetj5U1@mid.uni-berlin.de> <4b2603bc$0$30660$426a34cc@news.free.fr> <4b26209b$0$7608$426a74cc@news.free.fr> Message-ID: <4b2f5d55$0$9772$426a74cc@news.free.fr> AppRe Godeck a ?crit : > On Mon, 14 Dec 2009 12:25:16 +0100, Bruno Desthuilliers wrote: > >> r0g a ?crit : >>> Bruno Desthuilliers wrote: >>>> Sancar Saran a ?crit : >>>> (snip) >>>>> My problem is with PHP syntax and performance. I'm just trying to >>>>> replicate my recepies in python... >>>> Python is not PHP, and trying to write PHP in Python won't buy you >>>> much except pain and frustration. >>> >>> I think people are being a little harsh here. Replicating exactly what >>> PHP code does on a micro level i.e. line by line is probably a bad idea >>> but for all we know a lot of the macro level stuff might be fine, or >>> mostly fine i.e. structures, algorithms, classes and functions etc. >> I was talking about trying to replicate PHP's execution model and idioms >> in Python - the "framework" part -, not about application specific >> algos, data structures etc. > > Try web2py I think you will surprise yourself with its simplicity and > speed :) I don't like what I've seen from web2py, thanks. Also and FWIW, I don't see how it relates to the OP ? From rolf.oltmans at gmail.com Mon Dec 21 06:38:01 2009 From: rolf.oltmans at gmail.com (Oltmans) Date: Mon, 21 Dec 2009 03:38:01 -0800 (PST) Subject: Regex help needed! Message-ID: <19de1d6e-5ba9-42b5-9221-ed7246e39b4a@u36g2000prn.googlegroups.com> Hello,. everyone. I've a string that looks something like ---- lksjdfls
        kdjff lsdfs
        sdjfls
        sdfsd
        welcome
        ---- >From above string I need the digits within the ID attribute. For example, required output from above string is - 35343433 - 345343 - 8898 I've written this regex that's kind of working re.findall("\w+\s*\W+amazon_(\d+)",str) but I was just wondering that there might be a better RegEx to do that same thing. Can you kindly suggest a better/improved Regex. Thank you in advance. From ndbecker2 at gmail.com Mon Dec 21 07:00:12 2009 From: ndbecker2 at gmail.com (Neal Becker) Date: Mon, 21 Dec 2009 07:00:12 -0500 Subject: difflib get_close_matches improvement? Message-ID: difflib.get_close_matches looks useful. But, I don't see where it defines 'close'. Besides that, wouldn't it be much more useful if one could supply their own distance metric? From cumakt at gmail.com Mon Dec 21 07:05:56 2009 From: cumakt at gmail.com (Umakanth) Date: Mon, 21 Dec 2009 04:05:56 -0800 (PST) Subject: Regex help needed! References: <19de1d6e-5ba9-42b5-9221-ed7246e39b4a@u36g2000prn.googlegroups.com> Message-ID: How about re.findall(r'\d+(?:\.\d+)?',str) extracts only numbers from any string.... ~uk On Dec 21, 4:38?pm, Oltmans wrote: > Hello,. everyone. > > I've a string that looks something like > ---- > lksjdfls
        kdjff lsdfs
        sdjfls
        = ? "amazon_35343433">sdfsd
        welcome
        > ---- > > From above string I need the digits within the ID attribute. For > example, required output from above string is > - 35343433 > - 345343 > - 8898 > > I've written this regex that's kind of working > re.findall("\w+\s*\W+amazon_(\d+)",str) > > but I was just wondering that there might be a better RegEx to do that > same thing. Can you kindly suggest a better/improved Regex. Thank you > in advance. From solipsis at pitrou.net Mon Dec 21 07:24:09 2009 From: solipsis at pitrou.net (Antoine Pitrou) Date: Mon, 21 Dec 2009 12:24:09 +0000 (UTC) Subject: Python3.1: gzip encoding with UTF-8 fails References: <7p70hgFlt3U1@mid.dfncis.de> Message-ID: Hello, Le Sun, 20 Dec 2009 17:08:33 +0100, Johannes Bauer a ?crit?: > > #!/usr/bin/python3 > import gzip > x = gzip.open("testdatei", "wb") > x.write("?") The bug here is that you are trying to write an unicode text string ("?") to a binary file (a gzip file). This bug has been fixed now; in the next 3.x versions it will raise a TypeError: >>> x = gzip.open("testdatei", "wb") >>> x.write("?") Traceback (most recent call last): File "", line 1, in File "/home/antoine/py3k/__svn__/Lib/gzip.py", line 227, in write self.crc = zlib.crc32(data, self.crc) & 0xffffffff TypeError: must be bytes or buffer, not str You have to encode manually if you want to write text strings to a gzip file: >>> x = gzip.open("testdatei", "wb") >>> x.write("?".encode('utf8')) Regards Antoine. From mik3l3374 at gmail.com Mon Dec 21 07:42:00 2009 From: mik3l3374 at gmail.com (mik3) Date: Mon, 21 Dec 2009 04:42:00 -0800 (PST) Subject: Regex help needed! References: <19de1d6e-5ba9-42b5-9221-ed7246e39b4a@u36g2000prn.googlegroups.com> Message-ID: <60872b5c-ee47-449a-8f92-07a662b08028@g4g2000pri.googlegroups.com> On Dec 21, 7:38?pm, Oltmans wrote: > Hello,. everyone. > > I've a string that looks something like > ---- > lksjdfls
        kdjff lsdfs
        sdjfls
        = ? "amazon_35343433">sdfsd
        welcome
        > ---- > > From above string I need the digits within the ID attribute. For > example, required output from above string is > - 35343433 > - 345343 > - 8898 > > I've written this regex that's kind of working > re.findall("\w+\s*\W+amazon_(\d+)",str) > > but I was just wondering that there might be a better RegEx to do that > same thing. Can you kindly suggest a better/improved Regex. Thank you > in advance. don't need regular expression. just do a split on amazon >>> s="""lksjdfls
        kdjff lsdfs
        sdjfls
        sdfsd
        welcome
        """ >>> for item in s.split("amazon_")[1:]: ... print item ... 345343'> kdjff lsdfs
        sdjfls
        sdfsd
        welcome
        then find ' or " indices and do index slicing. From __peter__ at web.de Mon Dec 21 07:58:55 2009 From: __peter__ at web.de (Peter Otten) Date: Mon, 21 Dec 2009 13:58:55 +0100 Subject: Regex help needed! References: <19de1d6e-5ba9-42b5-9221-ed7246e39b4a@u36g2000prn.googlegroups.com> Message-ID: Oltmans wrote: > I've a string that looks something like > ---- > lksjdfls
        kdjff lsdfs
        sdjfls
        = "amazon_35343433">sdfsd
        welcome
        > ---- > > From above string I need the digits within the ID attribute. For > example, required output from above string is > - 35343433 > - 345343 > - 8898 > > I've written this regex that's kind of working > re.findall("\w+\s*\W+amazon_(\d+)",str) > > but I was just wondering that there might be a better RegEx to do that > same thing. Can you kindly suggest a better/improved Regex. Thank you > in advance. >>> from BeautifulSoup import BeautifulSoup >>> bs = BeautifulSoup("""lksjdfls
        kdjff lsdfs
        sdjfls
        sdfsd
        welcome
        """) >>> [node["id"][7:] for node in bs(id=lambda id: id.startswith("amazon_"))] [u'345343', u'35343433', u'8898'] I think BeautifulSoup is a better tool for the task since it actually "understands" HTML. Peter From rolf.oltmans at gmail.com Mon Dec 21 08:06:08 2009 From: rolf.oltmans at gmail.com (Oltmans) Date: Mon, 21 Dec 2009 05:06:08 -0800 (PST) Subject: Regex help needed! References: <19de1d6e-5ba9-42b5-9221-ed7246e39b4a@u36g2000prn.googlegroups.com> Message-ID: On Dec 21, 5:05?pm, Umakanth wrote: > How about re.findall(r'\d+(?:\.\d+)?',str) > > extracts only numbers from any string.... > Thank you. However, I only need the digits within the ID attribute of the DIV. Regex that you suggested fails on the following string ---- lksjdfls
        kdjff lsdfs
        sdjfls
        sdfsd
        welcome
        hello, my age is 86 years old and I was born in 1945. Do you know that PI is roughly 3.1443534534534534534 ---- > ~uk > > On Dec 21, 4:38?pm, Oltmans wrote: > > > Hello,. everyone. > > > I've a string that looks something like > > ---- > > lksjdfls
        kdjff lsdfs
        sdjfls
        > = ? "amazon_35343433">sdfsd
        welcome
        > > ---- > > > From above string I need the digits within the ID attribute. For > > example, required output from above string is > > - 35343433 > > - 345343 > > - 8898 > > > I've written this regex that's kind of working > > re.findall("\w+\s*\W+amazon_(\d+)",str) > > > but I was just wondering that there might be a better RegEx to do that > > same thing. Can you kindly suggest a better/improved Regex. Thank you > > in advance. > > From fetchinson at googlemail.com Mon Dec 21 09:03:03 2009 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Mon, 21 Dec 2009 15:03:03 +0100 Subject: Class variables static by default? In-Reply-To: References: <4b2d735b$1@dnews.tpgi.com.au> <033d925d$0$1305$c3e8da3@news.astraweb.com> Message-ID: >>> In python, 'class variable' is a variable that belongs to a class; not >>> to the instance and is shared by all instance that belong to the class. >> >> Surely, since string variables are strings, and float variables are >> floats, and bool variables are bools, and module variables are modules, a >> class variable will be a class and an instance variable will be an >> instance? >> >>> In contrast, 'instance variable' belongs to the instance, and each >>> instance can make their instance variables refers to different objects >>> than the other instances. >> >> The usual term used in Python is "class attribute" and "instance >> attribute" for the named fields of a class or instance. > > I agree with your interpretation of "class variable", but you'll have to > rewrite parts of the official Python documentation so it becomes > consistent with it. The phrase "class variable" appears about 30 times, > always meaning "class attribute"; four of them in the Language Reference, > section "Class definitions", where the OP's issue is discussed: > > "Programmer?s note: Variables defined in the class definition are class > variables; they are shared by all instances. To create instance variables, > they can be set in a method with self.name = value. Both class and > instance variables are accessible through the notation ?self.name?, and an > instance variable hides a class variable with the same name when accessed > in this way. Class variables can be used as defaults for instance > variables, but using mutable values there can lead to unexpected results. > For new-style classes, descriptors can be used to create instance > variables with different implementation details." I don't think Steven cares much, he loves this type of nitpicking and uber pedantic formulations, but only if he can apply it to other people's post :) I found that his posts are generally useful and helpful, one just has to cut all the nitpicking, an example of which is the one you responded to, and then everything is fine. Duck and run..... Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From cumakt at gmail.com Mon Dec 21 09:04:49 2009 From: cumakt at gmail.com (Umakanth) Date: Mon, 21 Dec 2009 06:04:49 -0800 (PST) Subject: Regex help needed! References: <19de1d6e-5ba9-42b5-9221-ed7246e39b4a@u36g2000prn.googlegroups.com> Message-ID: Ok. how about re.findall(r'\w+_(\d+)',str) ? returns ['345343', '35343433', '8898', '8898'] ! On Dec 21, 6:06?pm, Oltmans wrote: > On Dec 21, 5:05?pm, Umakanth wrote: > > > How about re.findall(r'\d+(?:\.\d+)?',str) > > > extracts only numbers from any string.... > > Thank you. However, I only need the digits within the ID attribute of > the DIV. Regex that you suggested fails on the following string > > ---- > lksjdfls
        kdjff lsdfs
        sdjfls
        = ? "amazon_35343433">sdfsd
        welcome
        > hello, my age is 86 years old and I was born in 1945. Do you know that > PI is roughly 3.1443534534534534534 > ---- > > > ~uk > > > On Dec 21, 4:38?pm, Oltmans wrote: > > > > Hello,. everyone. > > > > I've a string that looks something like > > > ---- > > > lksjdfls
        kdjff lsdfs
        sdjfls
        > > = ? "amazon_35343433">sdfsd
        welcome
        > > > ---- > > > > From above string I need the digits within the ID attribute. For > > > example, required output from above string is > > > - 35343433 > > > - 345343 > > > - 8898 > > > > I've written this regex that's kind of working > > > re.findall("\w+\s*\W+amazon_(\d+)",str) > > > > but I was just wondering that there might be a better RegEx to do that > > > same thing. Can you kindly suggest a better/improved Regex. Thank you > > > in advance. > > From petro at brc.hu Mon Dec 21 09:31:47 2009 From: petro at brc.hu (petro at brc.hu) Date: Mon, 21 Dec 2009 15:31:47 +0100 Subject: No subject Message-ID: <20091221153147.448853kdegkistlf@webmail.brc.hu> -- Petro Khoroshyy Institute of Biophysics Biological Research Center of the Hungarian Academy of Sciences Temesvari krt. 62, P.O.Box 521 Szeged, Hungary, H-6701 ---------------------------------------------------------------- This message was sent using IMP, the Internet Messaging Program. From lukepadawan at gmail.com Mon Dec 21 09:39:46 2009 From: lukepadawan at gmail.com (Lucas Prado Melo) Date: Mon, 21 Dec 2009 11:39:46 -0300 Subject: For...in statement and generators Message-ID: <9f4be2240912210639g58da0549jb0c81450947ef032@mail.gmail.com> Is there a way to send() information back to a generator while using the for...in statement? Thanks in advance. -------------- next part -------------- An HTML attachment was scrubbed... URL: From albert at spenarnc.xs4all.nl Mon Dec 21 09:53:38 2009 From: albert at spenarnc.xs4all.nl (Albert van der Horst) Date: 21 Dec 2009 14:53:38 GMT Subject: switch References: <335204.99872.qm@web57905.mail.re3.yahoo.com> Message-ID: In article , Steven D'Aprano wrote: >On Wed, 09 Dec 2009 18:50:29 +0000, Nobody wrote: >> >> Compiled languages' switch statements typically require constant labels >> as this enables various optimisations. > >Pascal, for example, can test against either single values, enumerated >values, or a range of values: > >case n of > 0: > writeln('zero'); > 1, 2: > writeln('one or two'); > 3...10: > writeln('something between three and ten'); > else writeln('something different'); > end; This shows where the merit of a switch/case statement lies. It guarantees both to the compiler and to the human reader that we are dealing with mutually exclusive and constant cases. This allows optimisation (c) and verification (h) advantages. A chain of elif's OTOH doesn't do that. On the top of my toes I will have to check every line whether the regularity breaks down. As regards polymorphism. It is dubious that an inherently different technique can be consistently and confidently promoted as an alternative. Sometimes it is, sometimes it isn't. Polymorphism is IMO promoted for far too much situations. As a maintenance programmer (being at least twice as smart as the people who wrote the original code) I can testify that code can be polymorphed to the point that it stops working and/or that it practically stops working and/or that it stops working practically. I'm the author of PostItFixup assembler. This assembler manages to assemble code with no control structures at all. 1] No IF, no FOR, no WHILE, no CASES. Nothing conditional, and no looping. How's that for a change? Although this is truly remarkable and well worth studying, I will not promote this style of programming as the ultimate alternative for everything. (And it breaks down at a point, sure.) Bottom line: "Give to the Caesar what belongs to the Caesar..." Not adding a switch to python is a matter of taste, good taste as far as I'm concerned. Adding a switch to C was also good taste, by the way. >-- >Steven Groetjes Albert -- 1] Only in the error checking there is an IF. -- Albert van der Horst, UTRECHT,THE NETHERLANDS Economic growth -- being exponential -- ultimately falters. albert at spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst From massimodipierro71 at gmail.com Mon Dec 21 10:02:50 2009 From: massimodipierro71 at gmail.com (mdipierro) Date: Mon, 21 Dec 2009 07:02:50 -0800 (PST) Subject: Anybody use web2py? References: <6oidnWzFKdtK6LHWnZ2dnUVZ_opi4p2d@supernews.com> <39d22fcc-c721-4da3-952d-f2bc178a3122@l13g2000yqb.googlegroups.com> <4b2f36c9$0$14448$426a34cc@news.free.fr> Message-ID: <00f3d953-0979-4ed6-b8a2-2ce1ad90b1dd@b2g2000yqi.googlegroups.com> > > On Dec 19, 12:42 am, AppRe Godeck wrote: > >> Just curious if anybody prefers web2py over django, and visa versa. I > >> know it's been discussed on a flame war level a lot. I am looking for a > >> more intellectual reasoning behind using one or the other. > > > Of course I am the most biased person in the world on this topic > > Indeed !-) > > - In web2py models and controllers are not modules. They are not > > imported. They are executed. > > I assume you mean "executed in an environment defined by the framework"... yes > > This means you do not need to import > > basic web2py symbols. They are already defined in the environment that > > executes the models and controllers > > Ok. As far as I'm concerned : show stops here. It is your choice but, why? Exec/eval is only true distinctive feature of an interpreted language vs a compiled language. > >(like in Rails). This also means > > you do not need to restart the web server when you edit your app. > > The dev server that comes with Django do the autorestart thing. And you > *don't* "edit yoour app" directly on the production server, do you ? Unfortunately it has happened. In my experience the distinction between development and production is fiction. > > - You have a web based IDE with editor, > > Why should I care ? I have a way better development environment on my > own box. I only use emacs. I do not use the web based IDE much myself but I found it really helps in learning how to use the framework. > > some conflict resolution, > > Mercurial integration, > > What if use something else than mercurial ? You can use any version control you want, the same way you would in Django. web2py itself is version controlled in both bazaar and mercurial. The only think about mercurial is that, if you have it installed, the web based IDE lets you commit at the click on a