ANN: GMPY 1.11rc1 is available
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! casevh -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations/
[ANN] BleachBit 0.7.2
BleachBit (a pure PyGTK app) deletes traces of online Internet usage and recovers wasted disk space. Highlight of changes since 0.7.1: * Clear Konqueror cache, cookies, and history * Improve notifications (show them less often and for shorter a period of time) * Show system information for reporting bugs * Clear Microsoft Paint MRU * Clear more of WinRAR and Adobe Reader 6 * Request escalated (administrator) privileges on Windows Vista and Windows 7 * Fix many bugs Detailed release notes http://bleachbit.sourceforge.net/news/bleachbit-071-released Download http://bleachbit.sourceforge.net/download -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations/
[ANN] pyxser-1.3r --- Python XML Serialization/Deserialization Extension
-BEGIN PGP SIGNED MESSAGE- Hash: SHA512 Hello Python Community. I'm pleased to announce pyxser-1.3r, a python extension which contains functions to serialize and deserialize Python Objects into XML. It is a model based serializer. Here is the ChangeLog entry for this release: - ---8--- 1.3r (2009.11.30): Daniel Molina Wegener d...@coder.cl * pyxser_tools.c: Removed bug concerning deserialization of collection elements; pyxser now can handle extension declared classes, such as boost::python ones --- thanks to the suggestions made by Daniel Filonik. * pyxser.c: Added /selector/ as optional argument used as callback to select object attributes to being serialized. * pyxser_string.c: Removed bug concerning unicode serialization. Thanks pyxser users for your feedback... - ---8--- The project is hosted at: http://sourceforge.net/projects/pyxser/ The web page for the project is located at: http://coder.cl/products/pyxser/ For a sample article on how to integrate pyxser with ZSI WebServices: http://coder.cl/2009/10/18/pyxser-and-zsi-webservices/ Thanks and best regards, - -- | Daniel Molina Wegener dmw [at] coder [dot] cl | | IT Consulting Software Developer | | http://coder.cl/| -BEGIN PGP SIGNATURE- Version: GnuPG v1.4.9 (GNU/Linux) iQIcBAEBCgAGBQJLFJIpAAoJEHxqfq6Y4O5NCWsQAJaaIaPZM8BH3XemmYNaJPK8 8G9mzOhKiZrX9LVASamkDwnfNBxhrrEayJgPpmXT9lJbiCdOJx7kzURuT6/oLdEX V4dq802zoKq4Y0UN1sC3RJApei3nVVENCPl4735VFrhLGGNcYeybBmQ4LvFkqB37 4l7pAbqJyB+LJqEw0mbVdiMjR6Ioze78Rmi8VRh5yK7cq1iFahrIV9mqykMtcdzD UYVZrv8z5yFv7Wm8hlaCX59wOsVElpCMbbhYdEfJlMS4oftlW+sAMzsfLl0LHxSr XU+dsQ0nBxmyn2IzidfYuD+cSe06L8WtVdicXG1drORlamj9TVyc647H424AfveB hBEdBQPz9s2jhoNGYG6ANXVXu0KRHQFftS8JnyMu/WRLM3eevGW9MPtE0OU1AfGR unyKCSj6w8q+oOG0jnP8Ad82NtxuYbK/D9nHSb5mxYYu9tknz67xS+jeWA5tBYns KhHm6OCf7XoHo7wJ/GSipOprI5zJE29ztPgdD4DYoCL3Cz+ASTJ3bng3FhcdxjOg joBMhgs/0ktBcNeIeUk2BzHRhM+fM4C7dKYtw0WVATA3LkCE3tr9u3Cwn0IFIktB OalbRARnbc6N1gvHcHIGiYzSxpeQDUnFVluV1ERVfhv7Jl8UubvTPYhPR+MPnm8P NiiemOI48BrGPqjJYDmg =yx79 -END PGP SIGNATURE- -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations/
Unpacking Tuples
I hate to post such a simple Q and A here, but I seriously can't find it anywhere. Python (unsure of starting with which version) enables the remainder of the tuple to be placed in a catch-all, for example: myTuple = (1,2,3,4) varOne, varTwo, *remaindingTuple = myTuple. where the values left unpacked get thrown into a tuple referenced to by remaindingTuple I included the asterix because it seems like I remember that being the operator that specifying the tuple's dumping ground. Which brings me to my two questions: 1) what's the syntax for this operation 2) what version does it start with? -- http://mail.python.org/mailman/listinfo/python-list
Re: python and vc numbers
On Mon, Nov 30, 2009 at 02:21:54PM +1300, Gregory Ewing wrote: I use to figure out what tty my program was invoked from? Here's one way: % python Python 2.5 (r25:51908, Apr 8 2007, 22:22:18) [GCC 3.3 20030304 (Apple Computer, Inc. build 1809)] on darwin Type help, copyright, credits or license for more information. import os os.popen(tty).read() That did the trick, thanks, after I append [-2] It works great. Thanks Dan signature.asc Description: Digital signature -- http://mail.python.org/mailman/listinfo/python-list
Running function from Win32 dll
Hi all, I want to run function from win32 dll. I used ctypes.windll.LoadLibrary to load the DLL. But I don't know how to select function and run it. Dll example attached (pylab.dll). It includes 2 functions: double Add(double a,double b) - adds 2 double numbers double Random(void) - generates random number Thank you, Nadav pylab.rar Description: pylab.rar -- http://mail.python.org/mailman/listinfo/python-list
Re: Unpacking Tuples
On Mon, Nov 30, 2009 at 12:17 AM, Joel Davis callmeclaud...@gmail.com wrote: I hate to post such a simple Q and A here, but I seriously can't find it anywhere. Python (unsure of starting with which version) enables the remainder of the tuple to be placed in a catch-all, for example: myTuple = (1,2,3,4) varOne, varTwo, *remaindingTuple = myTuple. where the values left unpacked get thrown into a tuple referenced to by remaindingTuple I included the asterix because it seems like I remember that being the operator that specifying the tuple's dumping ground. Which brings me to my two questions: 1) what's the syntax for this operation Exactly as you showed above (well, minus the period obviously). 2) what version does it start with? Python 3.0 It might be backported into 2.7 when it gets released: http://bugs.python.org/issue2340 Cheers, Chris -- http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Unpacking Tuples
Joel Davis wrote: I hate to post such a simple Q and A here, but I seriously can't find it anywhere. Python (unsure of starting with which version) enables the remainder of the tuple to be placed in a catch-all, for example: myTuple = (1,2,3,4) varOne, varTwo, *remaindingTuple = myTuple. where the values left unpacked get thrown into a tuple referenced to by remaindingTuple I included the asterix because it seems like I remember that being the operator that specifying the tuple's dumping ground. Which brings me to my two questions: 1) what's the syntax for this operation 2) what version does it start with? 1) Syntax is just as you have it. (Not including the period you have at the end.) 2) Python 3.0 Gary Herron -- http://mail.python.org/mailman/listinfo/python-list
Running function from win32 dll
Hi all, I want to run function from win32 dll. I used ctypes.windll.LoadLibrary to load the DLL. But I don't know how to select function and run it. Thank you, Nadav -- http://mail.python.org/mailman/listinfo/python-list
Re: semantics of ** (unexpected/inconsistent?)
Esmail wrote: Wow .. never heard of Concatenative_languages languages before or the distinction you make. Your distinction explains the behavior, but I find it somewhat counter-intuitive. You shouldn't find it any more surprising than the fact that a = 2 + 3 print a * 5 gives a different result from print 2 + 3 * 5 -- Greg -- http://mail.python.org/mailman/listinfo/python-list
Re: Creating a local variable scope.
Hi Steve! On Nov 30, 1:46 am, Steve Howell showel...@yahoo.com wrote: I occasionally make the error you make, but I think the real problem you are having is lack of attention to detail. If name collisions are a common problem for you, consider writing shorter methods Yes, this could be a solution, though I believe that too many (sub) methods called by a single method turn the code less readable. or develop the habit of using more descriptive variable names. Also a good suggestion. Alternatively I have considered to do the opposite, to use weird (the opposite of descriptive) names for variables that should exist only inside the block, in order to differentiate them from the variables that should persist. In the code above, you could have easily cleaned up the namespace by extracting a method called get_arg_columns(). Having to spend 15 minutes tracking down a bug usually indicates that you are not being systematic in your thinking. If you are rushing too much, slow down. If you are tired, take a break. If you make the same mistake twice, commit to yourself not to make it a third time. Also, test your methods one at a time and get them rock solid before writing more code. Nice suggestions thanks, all of them apply to me!...:-) Compared to the normal coder I have a strong tendency to loose myself in details. That is why I have to be very systematic, write lots of defensive code (to catch the bugs as soon as possible), write unit tests (great habit I've developped recently!). Python is fantastic for those goals. The only laking feature I find is really the survival of variables, a problem that does not exist in C++ or in Perl (with use strict). Besides this kind of bug I have noticed only 2 other sources of bug I had more than once with python code. - expecting float from integer division (easily avoidable, either with 3.0 or from __future__...) - expecting diferent objects in a list have having the same several times (deepcopy issue, also easily avoidable once we know it) So my only other problem is with this survival feature. I consider to write my own version of Python, the one that would not allow the usage of varaibles outside the block it was created. Of course I won't rewrite CPython but I could add an error (or warning) to pylint. With some luck it already exists, I will investigate... Greets! Marko -- http://mail.python.org/mailman/listinfo/python-list
Creating a datetime object from a C Extention
HI, I'm writing a python C Extension and need to create datetime objects but when I call value = PyDateTime_FromDateAndTime(ti-tm_year+1900, ti-tm_mon, ti-tm_mday, ti-tm_hour, ti-tm_min, ti-tm_sec, u); I get an SegFault. ti = {tm_sec = 25, tm_min = 37, tm_hour = 8, tm_mday = 30, tm_mon = 10, tm_year = 109, tm_wday = 1, tm_yday = 333, tm_isdst = 0, tm_gmtoff = 0, tm_zone = 0x800fd20c8 UTC} u = 0 Is there an Dokumentation or example code HowTo create a datetime object from a C Extension. Regards Estartu -- Gerhard Schmidt| http://www.augusta.de/~estartu/| Fischbachweg 3 || PGP Public Key 86856 Hiltenfingen | JabberID: esta...@augusta.de | auf Anfrage/ Tel: 08232 77 36 4 | IRCNET: Estartu | on request Fax: 08232 77 36 3 || signature.asc Description: OpenPGP digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: delete column content
On 11月30日, 上午2时27分, Diez B. Roggisch de...@nospam.web.de wrote: Francesco Pietra schrieb: Hi: How to replace with blank the single-character in column 21 of a pdb file (in pdb numbering it is column 22). Attached is an incomplete exercise with slices. I am unable to get real plain text with gmail. Thanks for help Wasn't the help you already got a few days ago sufficient? Diez http://www.mbthome.net/ mbt shoes -- http://mail.python.org/mailman/listinfo/python-list
Re: Creating a datetime object from a C Extention
I'm writing a python C Extension and need to create datetime objects but when I call value = PyDateTime_FromDateAndTime(ti-tm_year+1900, ti-tm_mon, ti-tm_mday, ti-tm_hour, ti-tm_min, ti-tm_sec, u); I get an SegFault. ti = {tm_sec = 25, tm_min = 37, tm_hour = 8, tm_mday = 30, tm_mon = 10, tm_year = 109, tm_wday = 1, tm_yday = 333, tm_isdst = 0, tm_gmtoff = 0, tm_zone = 0x800fd20c8 UTC} u = 0 Is there an Dokumentation or example code HowTo create a datetime object from a C Extension. You need to put PyDateTime_IMPORT; into your module's init function. HTH, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: Creating a local variable scope.
On Nov 30, 4:46 am, Dave Angel da...@ieee.org wrote: markolopa wrote: Antoher 15 minutes lost because of that Python feature... Is it only me??? Yep, I think so. Not very consoling but thanks anyway!...:- You're proposing a much more complex scoping rule, where if a variable already exists before entering a loop, then the loop uses that existing variable, but if not, it creates its own local one and destroys it when exiting the loop. Alternatively you could forbid the creation of a variable in a inner block if it already exists. Either that or forbid the usage of the variable in an outter block later if it exists both in an inner and outer block. Aren't there languages that forbid the declarations of variables in a function with the same name as global variables? I know that this is an extreme defensive measure, but I have to say that I like it. Allowing to create a new variable when a variable with the same name is already exists in the namespace makes for harm that good, for me at least. Of course this issue is much broader than the one I proposed initially. I think if you had your wish, you'd find that you had more exceptions where you had to pre-declare things, than the times when you avoided the bugs you describe. You are probably right, otherwise Guido would have done what I suggest... but I really don't see why. I don't like languages that make me write extra stuff 100 times, to save one instance of extra debugging. If Python already required declarations, then I might buy your arguments. But it wouldn't be Python. My guess is that if the change I propose was implemented, the number additional lines that would be needed to make the present python code work would be 1 in a thousand or less. Of course I may be wrong... Besides this additional line can make the code more readable, strassing the fact that the variable inside the block actually belongs to outside. In your particular case, the compiler couldn't guess whether you used the first loop to decide which domain to use in the second loop, That is what I wish the compiler should forbid...:- or whether you accidentally reused the same name without giving it a new value in the new loop. That is what I do regularly...8- If you need to use the same name, you could always follow your loops with the del statement to invalidate the name. Several people have suggested explicit destruction of the variables I don't need. Python allows it but of course this does not solve my problem. It does not make sense to use such a clean language as Python and regularly delete all variables used inside the blocks when leaving it. And of course the bug comes because I have no idea that I am using the same name again. Cheers! Marko -- http://mail.python.org/mailman/listinfo/python-list
Re: ANN: GMPY 1.11rc1 is available
casevh cas...@gmail.com wrote: 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: [snip] 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. You could have variant types of mpz etc which do release the GIL so you could mix and match accordingly. 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. Mutable integers - whatever will they think of next ;-) Thanks for maintaining gmpy - it is an excellent bit of software! -- Nick Craig-Wood n...@craig-wood.com -- http://www.craig-wood.com/nick -- http://mail.python.org/mailman/listinfo/python-list
Re: Creating a local variable scope.
On 11/30/2009 8:13 PM, markolopa wrote: On Nov 30, 4:46 am, Dave Angelda...@ieee.org wrote: markolopa wrote: Antoher 15 minutes lost because of that Python feature... Is it only me??? Yep, I think so. Not very consoling but thanks anyway!...:- You're proposing a much more complex scoping rule, where if a variable already exists before entering a loop, then the loop uses that existing variable, but if not, it creates its own local one and destroys it when exiting the loop. Alternatively you could forbid the creation of a variable in a inner block if it already exists. Either that or forbid the usage of the variable in an outter block later if it exists both in an inner and outer block. Of course, the best solution would be to allow assignment only in a single line of source of code. Reassignment by different lines of code would be a syntax error. You're forced to have different names if you want assign something multiple times. That way, no bugs is possible. -- http://mail.python.org/mailman/listinfo/python-list
Re: python and vc numbers
On Mon, Nov 30, 2009 at 07:20:59PM +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 so a certain command ran under screen process A isn't confused with a command ran under screen process B? Thanks Dan signature.asc Description: Digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: Object Not Callable, float?
On Mon, 30 Nov 2009 01:07:53 -0500, Mel wrote: In FORTRAN and PL/I words were un-reserved to a degree that's really bizarre. A short post can't begin to do it justice -- let's just mention that IF and THEN could be variable names, and DO 100 I=1.10 . The syntaxes were carefully crafted so that context completely determined whether a symbol would be taken in a reserved sense or a programmer-defined sense, so any possibility for conflict was a syntax error. And then Lisp and Tcl just don't have reserved words. Many symbols are pre-defined, but you're free to re-define them (Lisp won't let you use 'quote' as a function name, but you can still use it as a variable name). -- http://mail.python.org/mailman/listinfo/python-list
Re: python and vc numbers
On Mon, Nov 30, 2009 at 2:02 AM, Daniel Dalton d.dal...@iinet.net.au wrote: On Mon, Nov 30, 2009 at 07:20:59PM +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 so a certain command ran under screen process A isn't confused with a command ran under screen process B? From what I can find, virtual console == tty. Quoting http://en.wikipedia.org/wiki/Virtual_console_%28PC%29 The virtual consoles are represented by device special files /dev/tty1, /dev/tty2 etc. Also, in my quickie newbie experimentation with `screen`, each screen window seems to get a unique tty#. Admittedly I am running OS X here, so if your notion of virtual console differs from Wikipedia's and is Linux-specific or something... Perhaps if you could explain your problem in greater detail? Cheers, Chris -- http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Creating a local variable scope.
markolopa wrote: On Nov 30, 4:46 am, Dave Angel da...@ieee.org wrote: markolopa wrote: Antoher 15 minutes lost because of that Python feature... Is it only me??? Yep, I think so. Not very consoling but thanks anyway!...:- You're proposing a much more complex scoping rule, where if a variable already exists before entering a loop, then the loop uses that existing variable, but if not, it creates its own local one and destroys it when exiting the loop. Alternatively you could forbid the creation of a variable in a inner block if it already exists. Somehow you seem to think there's some syntax for creating a variable. 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 a variable (except the global statement, which does it sort-of). So you'd be disallowing the following: counter = 5 for item in itemlist: if item 19: counter = counter + 5 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. Either that or forbid the usage of the variable in an outter block later if it exists both in an inner and outer block. You need to define exists in order to make discussion unambiguous. Without extra declarations of some type, I can't believe there's any way to make any variation of this concept work in the general case. Aren't there languages that forbid the declarations of variables in a function with the same name as global variables? I know that this is an extreme defensive measure, but I have to say that I like it. Allowing to create a new variable when a variable with the same name is already exists in the namespace makes for harm that good, for me at least. Of course this issue is much broader than the one I proposed initially. I can't think of any, among the 35 languages I've programmed in professionally over the years. All right, to be fair, about half of those were assembly languages at various levels. And I don't believe I worked in any assembly language that even had separate scoping for functions. DaveA -- http://mail.python.org/mailman/listinfo/python-list
Re: Creating a local variable scope.
On Mon, 30 Nov 2009 02:11:12 +0100, Alf P. Steinbach wrote: I think if one could somehow declare names as const (final, readonly, whatever) then that would cover the above plus much more. Having real constants is one feature that I miss. Because Python doesn't have constants, I find I've lost the discipline to avoid magic numbers (and strings) in my code. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Creating a local variable scope.
Steven D'Aprano wrote: On Mon, 30 Nov 2009 02:11:12 +0100, Alf P. Steinbach wrote: I think if one could somehow declare names as const (final, readonly, whatever) then that would cover the above plus much more. Having real constants is one feature that I miss. Because Python doesn't have constants, I find I've lost the discipline to avoid magic numbers (and strings) in my code. I don't get you, this can be easily avoid with a strong naming convention. I mean, despite they are not really constants, you can still use variables to name your numbers and string, to give the reader a usefull hint on the meaning of your code. Yet it is still a matter of discipline, it is sometimes very tempting to put the string directly (unlike numbers string can be meaningful sometimes) JM -- http://mail.python.org/mailman/listinfo/python-list
Re: python and vc numbers
On Mon, Nov 30, 2009 at 02:26:14AM -0800, Chris Rebert wrote: Also, in my quickie newbie experimentation with `screen`, each screen window seems to get a unique tty#. Admittedly I am running OS X Correct (Which creates the problem) Perhaps if you could explain your problem in greater detail? Sure, well, first I am running screen in a console. Under screen I open many windows, but in my .screenrc file, after 15 minutes screen runs screen lock which is the equivalent of /usr/local/bin/lock /usr/local/bin/lock is my python script, basically it checks to see if file /tmp/.vlock.run exists and if it does, will not run vlock again, but if it doesn't then passes onto vlock. When vlock returns a clean exit, eg. the user unlocks the term, my program removes that statefile and exits nicely. (the purpose of this is so screen doesn't lock the system hundreds of times, asking for a password hundreds of times, or when using -na it doesn't create a bunch of useless blank lock windows in my screen session. This works well, but it is only useful for one tty, because if you lock tty1 then it blocks tty2 etc. I know I could have a bunch of different scripts using different files, but this just gets to complicated to manage, so the logical solution is to append vc number to the filename: /tmp/.vlock.run.1 /tmp/.vlock.run.2 etc So we can identify which consoles have been locked, and which haven't. The problem lies with the fact, 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. I am totally blind, and therefore use a package called brltty, and this package has the ability to show me what number console I'm in, and even under screen always works reliably and consistently. So anyone know of a better solution, now I have described the issue in great detail? Thanks very much for all the help. Cheers, Dan signature.asc Description: Digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: Imitating tail -f
On 22 Nov, 05:10, exar...@twistedmatrix.com wrote: tail -f is implemented by sleeping a little bit and then reading to see if there's anything new. This was the apparent assertion behind the 99 Bottles concurrency example: http://wiki.python.org/moin/Concurrency/99Bottles However, as I pointed out (and as others have pointed out here), a realistic emulation of tail -f would actually involve handling events from operating system mechanisms. Here's the exchange I had at the time: http://wiki.python.org/moin/Concurrency/99Bottles?action=diffrev2=12rev1=11 It can be very tricky to think up good examples of multiprocessing (which is what the above page was presumably intended to investigate), as opposed to concurrency (which can quite easily encompass responding to events asynchronously in a single process). Paul P.S. What's Twisted's story on multiprocessing support? In my limited experience, the bulk of the work in providing usable multiprocessing solutions is in the communications handling, which is something Twisted should do very well. -- http://mail.python.org/mailman/listinfo/python-list
Re: Exec Statement Question
On Sun, Nov 29, 2009 at 10:23 PM, Dave Angel da...@ieee.org wrote: exec is a statement, and statements don't have return values. It's not a function, so there are no parentheses in its syntax, either. exec is also a technique of last resort; there's nearly always a better/safer/faster way to accomplish what you might want, but of course you don't say what that is. As for returning values, exec by default uses the same global space as your app, so you can just modify a global variable in your called code and use it afterwards. abc = 42 value = 12 exec abc = %d % value print abc Taking out the parenthesis did it! Thanks. Now, you state this is an option of last resort. Although this does indeed achieve my desired aim, here is a complete example of what I am trying to achieve. The following is from 'createTables2.py': for table in tables: try: exec 'from options import %s' % table except: pass try: exec '%s()' % table except: pass The following is from 'options.py': def jewelry(which=''): code = [] names = [] meanings = [] code.append(['5', '5frac12;', '6', '6frac12;', '7', '7frac12;', '8', '8frac12;', '9', '9frac12;', '10', '10frac12;', '11', '11frac12;', '12', '12frac12;', '13', '13frac12;']) meanings.append('The standard ring sizes.') names.append('ringSizes') code.append(['Petite (7#34;)', 'Average (7frac12;#34;)', 'Large (8#34;)', 'Extra-large (8frac12;#34;)']) meanings.append('The standard bracelet sizes.') names.append('braceletSizes') code.append(['16#34;', '18#34;', '20#34;', '22#34;', '24#34;']) meanings.append('The standard necklace sizes.') names.append('necklaceSizes') code.append(['14K gold', '18K gold', 'silver', '14K white gold', '18K white gold', 'platinum', 'tungsten', 'titanium']) meanings.append('The standard jewelry metals.') names.append('metals') code.append(['diamond', 'emerald', 'ruby', 'sapphire', 'pearl', 'opal', 'topaz', 'onyx', 'lapiz lazuli', 'tanzanite', 'garnet', 'quartz', 'rose quartz', 'amethyst', 'alexandrite', 'peridot', 'tourmaline', 'citrine', 'turquoise']) meanings.append('The standard jewelry stones.') names.append('stones') if which == '': i = 0 all = '' while i len(meanings): table = '%s\n' % meanings[i] table += table\n tr\n td colspan='8' align='center'%s/td\n /tr % names[i] j = 0 for elt in code: if (j + 8) % 8 == 0: table += ' tr\n' table += ' td%s/td\n' % code[i] if (j + 8) % 8 == 0: table += ' /tr\n' j += 1 if table[-6:] != '/tr\n': table += ' /tr\n' table += '/table\n' all += table + 'br /br /' i += 1 print all This all works fine; however, if there is a better way of doing it, please let me know. Thanks, V -- http://mail.python.org/mailman/listinfo/python-list
Re: Creating a local variable scope.
* Jean-Michel Pichavant: Steven D'Aprano wrote: On Mon, 30 Nov 2009 02:11:12 +0100, Alf P. Steinbach wrote: I think if one could somehow declare names as const (final, readonly, whatever) then that would cover the above plus much more. Having real constants is one feature that I miss. Because Python doesn't have constants, I find I've lost the discipline to avoid magic numbers (and strings) in my code. I don't get you, this can be easily avoid with a strong naming convention. I mean, despite they are not really constants, you can still use variables to name your numbers and string, to give the reader a usefull hint on the meaning of your code. Yet it is still a matter of discipline, it is sometimes very tempting to put the string directly (unlike numbers string can be meaningful sometimes) It may be surprising how many things turn out to be readonly. Consider the OP's code: code class ValueColumn(AbstractColumn): def __init__(self, name, header, domain_names): if type(domain_names) != tuple: raise ValueError('a tuple of domain names must be given') for name in domain_names: if type(name) != str: raise ValueError('a tuple of domain names must be given') self.domain_names = domain_names super(ValueColumn, self).__init__(name, header) /code Here the arguments should ideally be read only names, which would have cought the bug of reusing 'name' in the for loop. But you really wouldn't code this as code class ValueColumn(AbstractColumn): def __init__(SELF, NAME, HEADER, DOMAIN_NAMES): if type(DOMAIN_NAMES) != tuple: raise ValueError('a tuple of domain names must be given') for name in DOMAIN_NAMES: # Argh, at this point 'name' is readonly, but cannot express that. if type(name) != str: raise ValueError('a tuple of domain names must be given') SELF.domain_names = domain_names super(ValueColumn, SELF).__init__(NAME, HEADER) /code Or, at least I wouldn't do that. It's ugly. And you have to /change the names/ as the readonly-ness changes. Cheers, - Alf -- http://mail.python.org/mailman/listinfo/python-list
Re: semantics of ** (unexpected/inconsistent?)
one point of confusion could be the use of ** instead of superscript. it might make things a little bit more counterintuitive-looking than with superscripts, since the issue with would only apply to exponents, as -5*4 and a = -5 a*4 return the same answer, and superscripts make it a little easier to associate the exponent value with the base more than with the - before it. On Mon, Nov 30, 2009 at 3:46 AM, Gregory Ewing greg.ew...@canterbury.ac.nz wrote: Esmail wrote: Wow .. never heard of Concatenative_languages languages before or the distinction you make. Your distinction explains the behavior, but I find it somewhat counter-intuitive. You shouldn't find it any more surprising than the fact that a = 2 + 3 print a * 5 gives a different result from print 2 + 3 * 5 -- Greg -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
FW: IDE+hg
From: NiklasRTZ [mailto:nikla...@gmail.com] Sent: 26 November 2009 12:38 PM To: python-list@python.org Subject: Re: IDE+hg On Nov 25, 7:28 am, alex23 wuwe...@gmail.com wrote: NiklasRTZ nikla...@gmail.com wrote: no py IDE I found has easy hg access. ActiveState's Komodo IDE has support for CVS, Perforce, subversion, bazaar, git and mercurial. unavailable via synaptic ubuntu karmic repos, presuming its commercially bound like wing. Boa constructor, PIDA, Eric, drPython are 4 where all should be configurable for obvious reasons + I like it. thanks for anyway prompt reply my friend Eclipse with PyDev and SVN Team Provider works very well too. -- http://mail.python.org/mailman/listinfo/python-list
Brent's variation of a factorization algorithm
Maybe someone'll make use of it: def gcd(x, y): if y == 0: return x return gcd(y, x % y) def brent(n): c = 11 y, r, q, m = 1, 1, 1, 137 while 1: x = y for i in range(1, r + 1): y = (y * y + c) % n k = 0 while 1: ys = y for i in range(1, min(m, r - k) + 1): y = (y * y + c) % n q = (q * abs(x - y)) % n g = gcd(q, n) k += m if k =r or g 1: break r *= 2 if g 1: break if g == n: while 1: ys = (ys * ys + c) % n g = gcd(abs(x - ys), n) if g 1: break return g while 1: n = eval(raw_input()) g = brent(n) print '==', g, '*', n / g IDLE 1.2 No Subprocess 1170999422783 * 10001 == 73 * 160426920921271 1170999422783 * 254885996264477 == 1170999422783 * 254885996264477 1170999422783 * 415841978209842084233328691123 == 1170999422783 * 415841978209842084233328691123 51539607551 * 80630964769 == 51539607551 * 80630964769 304250263527209 * 792606555396977 == 304250263527209 * 792606555396977 -- http://mail.python.org/mailman/listinfo/python-list
Cookie name and expiration
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 as http://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 as http://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 directly http://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 -- http://mail.python.org/mailman/listinfo/python-list
Intro To Python Using Turtle Graphics
Done by Northland Polytechnic, available for download under CC-BY-NC-ND here http://www.archive.org/details/IntroductionToPythonUsingTurtleGraphics. Thanks to Colin Jackson for the link. -- http://mail.python.org/mailman/listinfo/python-list
Re: Access to file in Windows Xp
On 27 Nov, 12:37, Jon Clements jon...@googlemail.com wrote: On Nov 27, 11:26 am, FelixCatus fram...@gmail.com wrote: Good morning to all, I have written a simple python script that extracts data from a lot (800Mb) of text files. Now... In Linux the extraction runs in more or less 1s in Windows Xp it takes 325 - 326 s. I find that really hard to believe; I don't think I'd even be convinced 1s is correct if all the files were mounted under a ramfs, with blazingly fast RAM and huge amounts of multi-core CPUs running in parallel. I was not clear in my message, I don't have to open all files, but just a smaller amount of them. I'd guess your code has a subtle flaw that: 1) under Linux causes it to not do some work 2) under XP causes it to do too much work Can you confirm you get the same results, and maybe post some code? Jon. Just now I have found the issues. First of all in the win xp system I have discovered that there is the same processor of the linux station but much more less ram and so the system uses intensive swapping. With my personal computer wich has a smaller amount of ram and a not so good processor (not the one on the mounting station) it took more or less the same time of the mounting station in the first try but I have discovered that the problem was the AVG Anti-virus that makes some analysis each time you open a file. Stopping the antivirus the execution time is reduced down to 56s. On monday I can try to disable the antivirus also on the mounting station and watch how many time it spends to process the files. In Linux I don't have the antivirus nor a lot of processes that runs concurrently as it happens in windows. So... Sorry for the inconvenience, this is not a real python issue but just a computer problem. Thanks for your support :-) -- http://mail.python.org/mailman/listinfo/python-list
Re: Can self crush itself?
Why would you want to do that in the first place? I don't know... :-) As Schoepenhauer put it: The man can do what he wants to do but he can't want to want what he wants to do -- http://mail.python.org/mailman/listinfo/python-list
Re: Can self crush itself?
Ok ok Of course, it's a local name; -- just my silly slip. And seems it belongs to no dict[]... Just an internal volatile elf -- http://mail.python.org/mailman/listinfo/python-list
Re: Converting a float to a formatted outside of print command
On Nov 23, 3:17 pm, Dan Bishop danb...@yahoo.com wrote: You meant: x = '%.1f' % y Thanks, I'm a dufus today. -- http://mail.python.org/mailman/listinfo/python-list
Re: Feature request: String-inferred names
Lie Ryan a écrit : (snip) setattr, getattr, and delattr are already sugar for accessing instance.__dict__. They are actually much more than that - else descriptors and inheritance wouldn't work. -- http://mail.python.org/mailman/listinfo/python-list
Re: Feature request: String-inferred names
Cameron Simpson c...@zip.com.au writes: The Zen promotes the guideline that there should be only one (obvious) way to do most things and that's a surprisingly effective design rule. It's also important to realise that the Zen places the “preferably only one” in a parenthetical, and note that “preferably” qualifier. That is, it's: There should be one obvious way to do it. without that parenthetical. I think that “obvious” is the important part there, and seems to be to be the design principle that (far more than “only one”) is guiding in Python's development. -- \ “Too many pieces of music finish too long after the end.” —Igor | `\ Stravinskey | _o__) | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: Feature request: String-inferred names
P.S., not trying to start a flame war. It's just that I can't stand to keep silent on the matter any longer. -- Brad Harms -- http://mail.python.org/mailman/listinfo/python-list
Re: Filling in a tuple from unknown size list
On Fri, 27 Nov 2009 04:18:08 -0800, boblatest wrote: Here's my question: Given a list of onknown length, I'd like to be able to do the following: (a, b, c, d, e, f) = list If the list has fewer items than the tuple, I'd like the remaining tuple elements to be set to None. If the list is longer, I'd like the excess elements to be ignored. I'd call that a code-smell. If I saw that in code, I'd think long and hard about why it was there and if I could eliminate the names a...f and just work directly with the list. But if you really do need it, I think the simplest and best way is to use the technique Stefan suggested: a, b, c, d, e, f = (list + [None]*6)[:6] provided list is short. If you fear that list might be huge and copying it will be prohibitively expensive: a, b, c, d, e, f = (list[:6] + [None]*6)[:6] -- Steven -- http://mail.python.org/mailman/listinfo/python-list
reading from a text file
hi all i would like to create a python program that would read from a text file and returns one result at random. e.g in the text file i have these data 1.hello 2.my name 3.is 4.World Your help is highly appreciated..thnx in advance $LIM $...@dy _ Windows Live: Friends get your Flickr, Yelp, and Digg updates when they e-mail you. http://www.microsoft.com/middleeast/windows/windowslive/see-it-in-action/social-network-basics.aspx?ocid=PID23461::T:WLMTAGL:ON:WL:en-xm:SI_SB_3:092010-- http://mail.python.org/mailman/listinfo/python-list
Re: Filling in a tuple from unknown size list
On Nov 27, 11:18 pm, boblatest boblat...@googlemail.com wrote: Hello all, (sorry for posting from Google. I currently don't have access to my normal nntp account.) Here's my question: Given a list of onknown length, I'd like to be able to do the following: (a, b, c, d, e, f) = list If the list has fewer items than the tuple, I'd like the remaining tuple elements to be set to None. If the list is longer, I'd like the excess elements to be ignored. WRONG -- sweeping excess input under the carpet is a nasty perlish trick. -- http://mail.python.org/mailman/listinfo/python-list
Re: Go versus Brand X
a...@pythoncraft.com (Aahz) writes: Comparing Go to another computer language -- do you recognize it? http://www.cowlark.com/2009-11-15-go/ If you skip to the conclusion, you'll be better off. The author has an interesting point. Go (the language) is not really ground-breaking. I don't understand why they're so busy creating their own walled garden... Their own browser, their own programming languages, their own file systems, etc. Weird. -- http://mail.python.org/mailman/listinfo/python-list
Re: Go versus Brand X
J Kenneth King wrote: a...@pythoncraft.com (Aahz) writes: Comparing Go to another computer language -- do you recognize it? http://www.cowlark.com/2009-11-15-go/ If you skip to the conclusion, you'll be better off. The author has an interesting point. Go (the language) is not really ground-breaking. I don't understand why they're so busy creating their own walled garden... Their own browser, their own programming languages, their own file systems, etc. because they can, no? Normal business logic doesn't apply to Google. -- http://mail.python.org/mailman/listinfo/python-list
Re: High-performance Python websites
If you need an example one is in front of you and you are using it now. Google uses python at their thousands of servers. But as you see Google gains this performance from the power of hundreds of thousands servers. The main idea behind the Google search engine was indexing the whole web through hundreds of servers. So you can imagine where Google's power comes from.. Regards On Nov 26, 2:33 am, ShoqulKutlu kursat.ku...@gmail.com 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.. Regards, Kutlu On Nov 26, 2:24 am, Nick Mellor nick.mellor.gro...@pobox.com wrote: Hi all, I'm contemplating setting up a Python-powered website for the tourist industry, which will involve a web service, a good deal of XML processing, and a Django-powered front-end. If the project works, it could get a lot of traffic. I'm sure it can be done, but I'm looking to find out more about how existing high-volume Python sites have managed their workload. Can anyone give me examples of high-volume Python-powered websites, if possible with some idea of their architecture? Many thanks, Nick- Hide quoted text - - Show quoted text - -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I correctly download Wikipedia pages?
On Wed, 25 Nov 2009 19:58:57 -0800, ShoqulKutlu wrote: Hi, Try not to be caught if you send multiple requests :) Have a look at here: http://wolfprojects.altervista.org/changeua.php Thanks, that seems to work perfectly. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: How to Detect Use of Unassigned(Undefined) Variable(Function)
Jon Clements wrote: pychecker returns test.py:3: No global (o) found for the above, and can be found at http://pychecker.sourceforge.net/ There's also pylint and another one whose name I can't remember... pyflakes. I use that one -- http://mail.python.org/mailman/listinfo/python-list
Re: IDE+hg
In article qqitt6-ke@spamfence.net, Günther Dietrich gd_use...@spamfence.net wrote: Since no py IDE I found has easy hg access. Obviously, you didn't try Eclipse with PyDev (http://www.pydev.org) and Mercurial Eclipse (http://www.vectrace.com/mercurialeclipse/) plugins. This combination is also available stuffed into one package as 'EasyEclipse for Python' (http://www.easyeclipse.org). Correction: EasyEclipse for Python does not contain the Mercurial Eclipse plugin. That has to be installed by hand in both cases. Sorry, Günther -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Statements/Keyword Localization
Terry Reedy wrote: A 'pro' argument: Python was designed for learning and is good for that and *is* used in schools down to the elementary level. But kids cannot be expected to know foreign alphabets and words whill still learning their own. I taught myself BASIC at 9 by reading magazines, but had my first english lessons five years later. Knowing english would have helped to understand the operating/language manuals, not the language keywords themselves. I suppose if you were to try what the OP suggested, you would need to translate a lot of the standard library, parameter names, and such... nonsense. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python-URL! - weekly Python news and links (Nov 24)
Cameron Laird a écrit : Grant Edwards on the best way to get help from this group :) http://groups.google.com/group/comp.lang.python/t/b8a0c32cae495522/21e80ac383745d88?#21e80ac383745d88 This one really deserves a POTM award !-) -- http://mail.python.org/mailman/listinfo/python-list
Re: Python-URL! - weekly Python news and links (Nov 24)
On Nov 24, 8:21 pm, Bruno Desthuilliers bdesth.quelquech...@free.quelquepart.fr wrote: Cameron Laird a écrit : Grant Edwards on the best way to get help from this group :) http://groups.google.com/group/comp.lang.python/t/b8a0c32cae495522/21... This one really deserves a POTM award !-) Absolutely -- thumbs up to Grant. All we need to do is merge in the other bullet points, and put it as a How-To-Not-Post-FAQ :) Jon. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python3 - encoding issues
No, sorry, i must correct me. There is a paragraph below on the quoted site. .index is still under Mutable sequence types - but bytes are treated below. -- http://mail.python.org/mailman/listinfo/python-list
Re: Sorting: too different times. Why?
On Sun, 22 Nov 2009 09:15:57 -0800, n00m wrote: Or take Drips by Eminem. What on earth do the drips mean? When you have a cold or flu, your nose drips. Some sexually transmitted diseases make your genitals drip. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Sorting: too different times. Why?
Some sexually transmitted diseases make your genitals drip. I suspected this :-) Eminem is a famous misogynist -- http://mail.python.org/mailman/listinfo/python-list
Re: Trying to understand += better
In article 4b0a01a...@dnews.tpgi.com.au, Lie Ryan lie.1...@gmail.com wrote: The semantic of the in-place operator is something like: x += y becomes x = x.__iadd__(y) thus foo.bar += baz becomes foo.bar = foo.bar.__iadd__(baz) So the call sequence is, foo.__getattr__('bar') == x x.__iadd__(baz) == y foo.__setattr__('bar', y) I don't get where the __setattr__() call comes from in this situation. I thought the whole idea of __iadd__(self, other) is that it's supposed to mutate self. So, why is there another assignment happening after the __iadd__() call? -- http://mail.python.org/mailman/listinfo/python-list
Re: Trying to understand += better
The first statement is creating a whole new list; Yes but *imo* not quite exactly so. We can't think of 2 lists as of absolutely independent things. ... x = [[0]] ... id(x) 19330632 ... id(x[0]) 19316608 ... z = x + [3] ... id(z) 19330312 ... id(z[0]) 19316608 ... ... z[0] is x[0] # ? True ... x[0][0] = 1 ... ... z[0][0] 1 -- http://mail.python.org/mailman/listinfo/python-list
Re: Trying to understand += better
On Nov 22, 8:38 pm, Roy Smith r...@panix.com wrote: In article 4b0a01a...@dnews.tpgi.com.au, Lie Ryan lie.1...@gmail.com wrote: The semantic of the in-place operator is something like: x += y becomes x = x.__iadd__(y) thus foo.bar += baz becomes foo.bar = foo.bar.__iadd__(baz) So the call sequence is, foo.__getattr__('bar') == x x.__iadd__(baz) == y foo.__setattr__('bar', y) I don't get where the __setattr__() call comes from in this situation. I thought the whole idea of __iadd__(self, other) is that it's supposed to mutate self. So, why is there another assignment happening after the __iadd__() call? Non-mutable types can also use += syntax. x = MagicalNumber(42) x += 5 # x gets reassigned to MagicalNumber(47) There is nothing that says that __iadd__ has to return self, but if you are designing a mutable type, you will generally do that. http://docs.python.org/reference/datamodel.html ''' These methods are called to implement the augmented arithmetic assignments (+=, -=, *=, /=, //=, %=, **=, =, =, =, ^=, |=). These methods should attempt to do the operation in-place (modifying self) and return the result (which could be, but does not have to be, self). If a specific method is not defined, the augmented assignment falls back to the normal methods. For instance, to execute the statement x += y, where x is an instance of a class that has an __iadd__() method, x.__iadd__(y) is called. If x is an instance of a class that does not define a __iadd__() method, x.__add__(y) and y.__radd__(x) are considered, as with the evaluation of x + y. ''' -- http://mail.python.org/mailman/listinfo/python-list
Re: TypeError: an integer is required
On Sun, 22 Nov 2009 18:29:25 +, MRAB wrote: os.open(C://Users//lutfi//Documents//te//log.txt , a ) open(C://Users//lutfi//Documents//te//log.txt , a ) Backslashes need to be doubled; forward slashes don't. -- http://mail.python.org/mailman/listinfo/python-list
Re: delete column content
On 11月30日, 上午2时12分, Francesco Pietra francesco.pie...@accademialucchese.it wrote: Hi: How to replace with blank the single-character in column 21 of a pdb file (in pdb numbering it is column 22). Attached is an incomplete exercise with slices. I am unable to get real plain text with gmail. Thanks for help francesco pietra delete.label.py 1K查看下载 http://www.mbthome.net/ mbt shoes -- http://mail.python.org/mailman/listinfo/python-list
Re: delete column content
On 11月30日, 上午2时48分, Vlastimil Brom vlastimil.b...@gmail.com wrote: 2009/11/29 Francesco Pietra francesco.pie...@accademialucchese.it: Hi: How to replace with blank the single-character in column 21 of a pdb file (in pdb numbering it is column 22). Attached is an incomplete exercise with slices. I am unable to get real plain text with gmail. Thanks for help francesco pietra -- http://mail.python.org/mailman/listinfo/python-list Do you mean something like line=abcdefghijklmnopqrstuvwxyz line[:21]+line[22:] 'abcdefghijklmnopqrstuwxyz' ? vbr http://www.mbthome.net/ mbt shoes -- http://mail.python.org/mailman/listinfo/python-list
Re: hex int and string
On 11月27日, 下午4时54分, luca72 lucabe...@libero.it wrote: hello i have a problem i have this str = 'D3' and i need to trasform in 0xd3 type int and not type string how i can do this? if i do hex(int(str,16) ) i obtain a string and this is not what i need. thanks Luca p stronga title=sport jersey href=http://www.jerseysup.com; target=sport jerseysport jersey/a/strong a title=sport jersey href=http://www.sport-jersey.net; target=sport jerseystrongsports jersey /strong/astrong /stronga title=ugg women href=http://www.uggwomen.net; target=ugg womenstronguggboot /strong/astrong /stronga title=nike market href=http://www.nike-market.com; target=nike marketstrongnike/strong/a/p -- http://mail.python.org/mailman/listinfo/python-list
Re: hex int and string
On 11月27日, 下午6时59分, Marco Mariani ma...@sferacarta.com wrote: Ben Finney wrote: i'm using pyscard I don't know what that is; can you give a link to what you're referring to? Simple story: he has seen the examples with hex literals and didn't know what they were. p stronga title=sport jersey href=http://www.jerseysup.com; target=sport jerseysport jersey/a/strong a title=sport jersey href=http://www.sport-jersey.net; target=sport jerseystrongsports jersey /strong/astrong /stronga title=ugg women href=http://www.uggwomen.net; target=ugg womenstronguggboot /strong/astrong /stronga title=nike market href=http://www.nike-market.com; target=nike marketstrongnike/strong/a/p -- http://mail.python.org/mailman/listinfo/python-list
Re: hex int and string
On 11月27日, 下午6时59分, Marco Mariani ma...@sferacarta.com wrote: Ben Finney wrote: i'm using pyscard I don't know what that is; can you give a link to what you're referring to? Simple story: he has seen the examples with hex literals and didn't know what they were. http://www.mbthome.net/ mbt shoes http://www.nike-airyeezy.com discount nike air yeezy -- http://mail.python.org/mailman/listinfo/python-list
Re: hex int and string
On 11月28日, 上午11时41分, 84715...@qq.com 84715...@qq.com wrote: On 11月27日, 下午4时54分, luca72 lucabe...@libero.it wrote: hello i have a problem i have this str = 'D3' and i need to trasform in 0xd3 type int and not type string how i can do this? if i do hex(int(str,16) ) i obtain a string and this is not what i need. thanks Luca p stronga title=sport jersey href=http://www.jerseysup.com; target=sport jerseysport jersey/a/strong a title=sport jersey href=http://www.sport-jersey.net; target=sport jerseystrongsports jersey /strong/astrong /stronga title=ugg women href=http://www.uggwomen.net; target=ugg womenstronguggboot /strong/astrong /stronga title=nike market href=http://www.nike-market.com; target=nike marketstrongnike/strong/a/p http://www.mbthome.net/ mbt shoes -- http://mail.python.org/mailman/listinfo/python-list
Re: how to format a python source file with tools?
On 11月27日, 下午2时40分, 李白,字一日 calid...@gmail.com wrote: or is it possible for large source files? p stronga title=sport jersey href=http://www.jerseysup.com; target=sport jerseysport jersey/a/strong a title=sport jersey href=http://www.sport-jersey.net; target=sport jerseystrongsports jersey /strong/astrong /stronga title=ugg women href=http://www.uggwomen.net; target=ugg womenstronguggboot /strong/astrong /stronga title=nike market href=http://www.nike-market.com; target=nike marketstrongnike/strong/a/p -- http://mail.python.org/mailman/listinfo/python-list
Re: jython and java application
Kutlu, I already have a first born, else I would name her after you. You are brilliant. That's what it was. Kudos. For future ref for fellow boneheads like me, in Eclipse, under Project properties, Jython Class Path, Add External JAR... Thanks a million! -- http://mail.python.org/mailman/listinfo/python-list
Re: jython and java application
Welcome a million :) On Nov 26, 5:33 am, KB ke...@nekotaku.com wrote: Kutlu, I already have a first born, else I would name her after you. You are brilliant. That's what it was. Kudos. For future ref for fellow boneheads like me, in Eclipse, under Project properties, Jython Class Path, Add External JAR... Thanks a million! -- http://mail.python.org/mailman/listinfo/python-list
Re: need clarification on -0
moijes12 wrote: I know the value -0 is quite meaningless and makes little sense.But I was just fiddling.I am unable to figure out the below result -0 and True 0 -- (Why is this 0 and not say True or False) -0 and false 0 -0 or True True Could someone please provide me some resources on how these operations take place.I'd wanna find it out myself Your questions have nothing to do with -0, as it's no different from 0: 0 == -0 True Your examples work the same way with simply 0, which is considered a false value: bool(0) False 0 and True 0 0 and False 0 0 or True True What you're seeing is simply the short-circuiting behavior of the `and` and `or` operators; they return the last (relevant) value they encountered before making their determination of the value of the overall expressions. See python.org/doc for more information. -- Erik Max Francis m...@alcyone.com http://www.alcyone.com/max/ San Jose, CA, USA 37 18 N 121 57 W AIM/Y!M/Skype erikmaxfrancis You'll survive / A true Darwin star -- Des'ree -- http://mail.python.org/mailman/listinfo/python-list
Re: need clarification on -0
On Nov 28, 12:55 pm, Erik Max Francis m...@alcyone.com wrote: moijes12 wrote: I know the value -0 is quite meaningless and makes little sense.But I was just fiddling.I am unable to figure out the below result -0 and True 0 -- (Why is this 0 and not say True or False) -0 and false 0 -0 or True True Could someone please provide me some resources on how these operations take place.I'd wanna find it out myself Your questions have nothing to do with -0, as it's no different from 0: 0 == -0 True Your examples work the same way with simply 0, which is considered a false value: bool(0) False 0 and True 0 0 and False 0 0 or True True What you're seeing is simply the short-circuiting behavior of the `and` and `or` operators; they return the last (relevant) value they encountered before making their determination of the value of the overall expressions. See python.org/doc for more information. -- Erik Max Francis m...@alcyone.com http://www.alcyone.com/max/ San Jose, CA, USA 37 18 N 121 57 W AIM/Y!M/Skype erikmaxfrancis You'll survive / A true Darwin star -- Des'ree Thanks Erik -- http://mail.python.org/mailman/listinfo/python-list
Re: scanning under windows WIA with custom settings (dpi / etc )
On Nov 22, 11:32 am, News123 news...@free.fr wrote: - This script works fine for me under Windows 7, however I'm unable to specify additional parameters, like dpi and color mode. I have found something interesting but have no idea HOW to implement it?? It seems the setting for the scanner are in the registry and must be changed that way or by specifically calling these constants on the device. WIA_IPS_YRES (ScannerPictureYres) Contains the current vertical resolution, in pixels per inch, for the device. An application sets this property to set the vertical resolution. The minidriver creates and maintains this property. Type: VT_I4, Access: Read/Write or Read Only, Valid Values: WIA_PROP_RANGE or WIA_PROP_LIST WIA_IPS_XRES (ScannerPictureXres) Contains the current horizontal resolution, in pixels per inch, for the device. An application sets this property to set the horizontal resolution. The minidriver creates and maintains this property. Type: VT_I4, Access: Read/Write or Read Only, Valid Values: WIA_PROP_RANGE or WIA_PROP_LIST WIA_IPS_OPTICAL_XRES (ScannerPictureOpticalXres) Note This property is supported only by Windows Vista and later. Horizontal Optical Resolution. Highest supported horizontal optical resolution in DPI. This property is a single value. This is not a list of all resolutions that can be generated by the device. Rather, this is the resolution of the device's optics. The minidriver creates and maintains this property. This property is required for all items. Type: VT_I4, Access: Read Only, Valid values: WIA_PROP_NONE WIA_IPS_OPTICAL_YRES (ScannerPictureOpticalYres) Note This property is supported only by Windows Vista and later. Vertical Optical Resolution. Highest supported vertical optical resolution in DPI. This property is a single value. This is not a list of all resolutions that are generated by the device. Rather, this is the resolution of the device's optics. The minidriver creates and maintains this property. This property is required for all items.Type: VT_I4, Access: Read Only, Valid values: WIA_PROP_NONE WIA_IPS_BRIGHTNESS (ScannerPictureBrightness) The image brightness values available within the scanner.Contains the current hardware brightness setting for the device. An application sets this property to the hardware's brightness value. The minidriver creates and maintains this property. Type: VT_I4, Access: Read/Write, Valid Values: WIA_PROP_RANGE WIA_IPS_CONTRAST (ScannerPictureContrast) Contains the current hardware contrast setting for a device. An application sets this property to the hardware's contrast value. The minidriver creates and maintains this property. Type: VT_I4, Access: Read/Write, Valid Values: WIA_PROP_RANGE WIA_IPS_ORIENTATION (ScannerPictureOrientation) Specifies the current orientation of the documents to be scanned. The minidriver creates and maintains this property. Type: VT_I4, Access: Read/Write, Valid Values: WIA_PROP_LIST Image Intent Constants Image intent constants specify what type of data the image is meant to represent. The WIA_IPS_CUR_INTENT scanner property uses these flags. To provide an intent, combine an intended image type flag with an intended size/quality flag by using the OR operator. WIA_INTENT_NONE should not be combined with any other flags. Note that an image cannot be both grayscale and color. WIA_INTENT_IMAGE_TYPE_COLOR (ImageTypeColor) WIA_INTENT_IMAGE_TYPE_GRAYSCALE (ImageTypeGrayscale) WIA_INTENT_IMAGE_TYPE_TEXT (ImageTypeText) WIA_INTENT_MINIMIZE_SIZE (MinimizeSize) WIA_INTENT_MAXIMIZE_QUALITY (MaximizeQuality) WIA_INTENT_BEST_PREVIEW (BestPreview) -- http://mail.python.org/mailman/listinfo/python-list
Re: scanning under windows WIA with custom settings (dpi / etc )
more *maybe useful dump? for i in dev.Items: for p in i.Properties: if not p.IsReadOnly: print p.Name, '-', p.Value Color Profile Name - sRGB Color Space Profile Brightness - 0 Contrast - 0 Private Highlight Level - 0 Private Midtone Level - 0 Private Shadow Level - 0 Private Gamma - 2200 Private Saturation - 1000 Private Hue X - 0 Private Hue Y - 0 Private Sharpen Level - 3 Threshold - 55 Horizontal Resolution - 200 Vertical Resolution - 200 Horizontal Start Position - 0 Vertical Start Position - 0 Horizontal Extent - 1700 Vertical Extent - 2338 Current Intent - 0 Data Type - 3 Media Type - 128 Format - {B96B3CAA-0728-11D3-9D7B-F81EF32E} Private Source Depth - 0 Private Preview - 0 Private Exposure Method - 0 Private Smoothing - 1 Private Color Enhanced - 0 Private TMA Method - 0 dev.DeviceID u'{6BDD1FC6-810F-11D0-BEC7-08002BE2092F}\\' for p in dev.Properties: print p.Name, '-', p.Value Item Name - Root Full Item Name - \Root Item Flags - 76 Unique Device ID - {6BDD1FC6-810F-11D0-BEC7-08002BE2092F}\ Manufacturer - Hewlett-Packard Description - HP Deskjet F300 Type - 65538 Port - \\.\Usbscan0 Name - HP Deskjet F300 Server - local Remote Device ID - UI Class ID - {0A8DC120-D685-4247-9CD1-8712F6BB2DED} Hardware Configuration - 0 BaudRate - STI Generic Capabilities - 48 WIA Version - 2.0 Driver Version - 0.0.0.216 PnP ID String - \\?\usb#vid_03f0pid_5511mi_00#62def7e70# {6bdd1fc6-810f-11d0-bec7-08002be2092f} STI Driver Version - 2 Horizontal Bed Size - 8500 Vertical Bed Size - 11690 Horizontal Bed Registration - 0 Vertical Bed Registration - 0 Access Rights - 3 Horizontal Optical Resolution - 2400 Vertical Optical Resolution - 2400 Firmware Version - 1.0.na Max Scan Time - 50 Now how to set the values... hmmm? -- http://mail.python.org/mailman/listinfo/python-list
The Strong Relationship between MatLab and MatPlotLib? What One Needs to Know?
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? -- http://mail.python.org/mailman/listinfo/python-list
Trying to understand += better
If I've got an object foo, and I execute: foo.bar += baz exactly what happens if foo does not have a 'bar' attribute? It's pretty clear that foo.__getattr__('bar') gets called first, but it's a little murky after that. Assume for the moment that foo.__getattr__ ('bar') returns an object x. I think the complete sequence of calls is: foo.__getattr__('bar') == x x.__add__(baz) == y foo.__setattr__('bar', y) but I'm not 100% sure. It would be nice if it was, because that would let me do some very neat magic in a system I'm working on :-) How would things change if X defined __iadd__()? -- http://mail.python.org/mailman/listinfo/python-list
dbapi2 select where IN (...)
hello, I couldn't find how the dbapi2 planned to handle the sql IN statement. ex : SELECT * FROM table WHERE num IN (2,3,8,9); I'd be glad to take advantage of the ? mechanism, but what about tuples ! execute(SELECT * FROM table WHERE num IN ?; , ((2,3,8,9),))...fail... what would be the most pythonic way to do this ? -- http://mail.python.org/mailman/listinfo/python-list
multiprocessing.connection with ssl
Hello I've hacked multiprocessing.connection (in a basic way) to allow ssl encryption using ssl.wrap_socket. Anybody knows how i can contribute this to main developers? Thanks in advance -- http://mail.python.org/mailman/listinfo/python-list
Completely OT
Hi; I need a recommendation. I want to print out data like this: td bgcolor='blue'a href='???'blue/a/td td bgcolor='red'a href='???'red/a/td and enable the user to select the various colors he wants to add to a list that would populate itself on the same page where the selections are, and then, once he's selected all the colors he wants, click to add them all at once to a table in a database, and move on to the next page. I believe this is achieved through JSON and AJAX; however, I haven't been able to google any demonstrations of this sort. Am I correct, or should I use some other sort of technology? TIA, Victor -- http://mail.python.org/mailman/listinfo/python-list
Can't print Chinese to HTTP
Hello. The upgrade to Python 3.1 has been disaster so far. I can't figure out how to print Chinese to a browser. If my script is: #!/usr/bin/python print(Content-type:text/html\n\n) print('晉') the Chinese string simply does not print. It works in interactive Terminal no problem, and also works in Python 2.6 (which my server is still running) in 4 different browsers. What am I doing wrong? BTW searched Google for 2 days no solution, if this doesn't get solved soon I will have to roll back to 2.6. Thanks for any clue. -- Gnarlie http://Gnarlodious.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Can't print Chinese to HTTP
Gnarlodious wrote: Hello. The upgrade to Python 3.1 has been disaster so far. I can't figure out how to print Chinese to a browser. If my script is: #!/usr/bin/python print(Content-type:text/html\n\n) print('晉') the Chinese string simply does not print. It works in interactive Terminal no problem, and also works in Python 2.6 (which my server is still running) in 4 different browsers. What am I doing wrong? BTW searched Google for 2 days no solution, if this doesn't get solved soon I will have to roll back to 2.6. Thanks for any clue. In the CGI case, Python cannot figure out what encoding to use for output, so it raises an exception. This exception should show up in the error log of your web server, please check. One way of working around this problem is to encode the output explicitly: #!/usr/bin/python print(Content-type:text/plain;charset=utf-8\n\n) sys.stdout.buffer.write('晉\n'.encode(utf-8)) FWIW, the Content-type in your example is wrong in two ways: what you produce is not HTML, and the charset parameter is missing. Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
flattening and rebuilding a simple list of lists
Hi, I have a list of lists. The number of sublists may vary. The sizes of the sublists may also vary. For instance, here I have a list with 3 sublists of differing sizes. [['a', 'b', 'c'], ['d', 'e'], ['f', 'g', 'h', 'i']] This list will never be any deeper than this one level. What I would like to do is flatten this list, rearrange the items in the new flattened list and then recreate the list of sublists with the new content. I would like the sublists to have the same size and order (relative to each other) as before. My code below seems to work, but it feels a bit hack'ish, and I am concerned about efficiency - so I would appreciate suggestions. Again, the number of sublists may vary, and sizes of sublists are not always the same (there will always be at least one sublist). thanks! Esmail Here is my working code so far. #!/usr/bin/env python from random import shuffle ## def flatten_list(parts): flatten parts, and return index vals where to split line = sum(parts, []) # join all parts into one idx_vals = [] idx = 0 for item in parts: # keep track of lengths/index values idx += len(item) idx_vals.append(idx) return line, idx_vals ## def rebuilt_lists(line, idx): rebuild list of list new_list = [line[0:idx[0]]] for i in xrange(len(idx)-1): new_list.append(line[idx[i]:idx[i+1]]) return new_list ## def main(): indi = [['a', 'b', 'c'], ['d', 'e'], ['f', 'g', 'h', 'i']] print 'indi:', indi # flatten list of list new_indi, idx_vals = flatten_list(indi) print 'new_indi:', new_indi print 'lengths :', idx_vals print # manipulate list print 'shuffling new_indi' shuffle(new_indi) print 'new_indi:', new_indi print # rebuild list of lists new_list = rebuilt_lists(new_indi, idx_vals) print 'new_list:', new_list if __name__ == '__main__': main() -- http://mail.python.org/mailman/listinfo/python-list
Re: reading from a text file
2009/11/27 baboucarr sanneh sanne...@hotmail.com: hi all i would like to create a python program that would read from a text file and returns one result at random. e.g in the text file i have these data 1.hello 2.my name 3.is 4.World Your help is highly appreciated..thnx in advance Hi babourarr; import random with open(c:/test.txt) as f: lines = f.read().splitlines() random_line = lines[random.randrange(len(lines))] print(random_line) $LIM $...@dy Windows Live: Friends get your Flickr, Yelp, and Digg updates when they e-mail you. -- http://mail.python.org/mailman/listinfo/python-list -- twitter.com/olofb olofb.wordpress.com olofb.wordpress.com/tag/english -- http://mail.python.org/mailman/listinfo/python-list
Re: reading from a text file
2009/11/27 baboucarr sanneh sanne...@hotmail.com: hi all i would like to create a python program that would read from a text file and returns one result at random. This might be of use: http://code.activestate.com/recipes/426332/#c2 -- Cheers, Simon B. -- http://mail.python.org/mailman/listinfo/python-list
Re: how to format a python source file with tools?
On 2009-11-27, Diez B. Roggisch de...@nospam.web.de wrote: The only thing that migh be automatized after a piece of code is valid is normalization, like de-tabifying or making everything based on 4 space characters indention. No idea if there is something out there that does that. In vim, you can do something like: :set tabstop=4 :set expandtab :retab -- Neil Cerutti -- http://mail.python.org/mailman/listinfo/python-list
Re: reading from a text file
baboucarr sanneh wrote: i would like to create a python program that would read from a text file and returns one result at random. #!/usr/bin/env python # assuming the file fits into memory, and you are interested in # random lines from random import randrange f = open('data.txt') data = f.readlines() number = len(data) pick = randrange(0, number) print data[pick] should do the trick. Esmail -- http://mail.python.org/mailman/listinfo/python-list
problem with lambda / closures
I have run into what seems to be a major bug, but given my short exposure to Python is probably just a feature: running Python 2.6.4 (r264:75821M, Oct 27 2009, 19:48:32) [GCC 4.0.1 (Apple Inc. build 5493)] on darwin with file foo.py containing: == clip here def p(d): print d l=[ ] for k in [1,2,3]: l.append(lambda : p(k)) for f in l: f() == clip here I get output 3 3 3 instead of 1 2 3 which I would expect. Can anyone explain this or give me a workaround? Thank you -- http://mail.python.org/mailman/listinfo/python-list
Re: flattening and rebuilding a simple list of lists
Esmail wrote: Hi, I have a list of lists. The number of sublists may vary. The sizes of the sublists may also vary. For instance, here I have a list with 3 sublists of differing sizes. [['a', 'b', 'c'], ['d', 'e'], ['f', 'g', 'h', 'i']] This list will never be any deeper than this one level. What I would like to do is flatten this list, rearrange the items in the new flattened list and then recreate the list of sublists with the new content. I would like the sublists to have the same size and order (relative to each other) as before. My code below seems to work, but it feels a bit hack'ish, and I am concerned about efficiency - so I would appreciate suggestions. I don't think it's hackish, but here's an alternative: items = [['a', 'b', 'c'], ['d', 'e'], ['f', 'g', 'h', 'i']] flat = sum(items, []) flat.reverse() from itertools import imap, islice flat = iter(flat) [list(islice(flat, size)) for size in imap(len, items)] [['i', 'h', 'g'], ['f', 'e'], ['d', 'c', 'b', 'a']] Peter -- http://mail.python.org/mailman/listinfo/python-list
TDD with nose or py.test
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 -- http://mail.python.org/mailman/listinfo/python-list
Re: problem with lambda / closures
Louis Steinberg wrote: I have run into what seems to be a major bug, but given my short exposure to Python is probably just a feature: Yes, it works as advertised :-/ which I would expect. Can anyone explain this or give me a workaround? like this? def p(d): print d l=[ ] for k in [1,2,3]: l.append(lambda k=k: p(k)) for f in l: f() -- http://mail.python.org/mailman/listinfo/python-list
Re: problem with lambda / closures
Louis Steinberg l...@cs.rutgers.edu wrote: == clip here def p(d): print d l=[ ] for k in [1,2,3]: l.append(lambda : p(k)) for f in l: f() == clip here I get output 3 3 3 instead of 1 2 3 which I would expect. Can anyone explain this or give me a workaround? Thank you There's nothing magic about lambda. The same holds true for any function definition. When you have a function that accesses a variable declared at an outer or global scope it always use the value of the variable at the time when it is accessed, not the value when it was defined. Your for loop is exactly equivalent to: def foo(): return p(k) l = [ foo, foo, foo ] k = 3 where it should be more obvious that you will always get the same result. Try this instead: from functools import partial l = [ partial(p, k) for k in [1, 2, 3]] -- Duncan Booth http://kupuguy.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: flattening and rebuilding a simple list of lists
On 2009-11-30, Esmail ebo...@hotmail.com wrote: I have a list of lists. The number of sublists may vary. The sizes of the sublists may also vary. For instance, here I have a list with 3 sublists of differing sizes. [['a', 'b', 'c'], ['d', 'e'], ['f', 'g', 'h', 'i']] This list will never be any deeper than this one level. What I would like to do is flatten this list, rearrange the items in the new flattened list and then recreate the list of sublists with the new content. I would like the sublists to have the same size and order (relative to each other) as before. Depending on your usage pattern, directly mutating the original through a simple view might be a viable alternative: def set_flattened(lst, i, val): j = 0 while i = len(lst[j]): i -= len(lst[j]) j += 1 lst[j][i] = val def get_flattened(lst, i): j = 0 while i = len(lst[j]): i -= len(lst[j]) j += 1 return lst[j][i] A view should be easier to use and debug than your current flatten, mutate and unflatten approach. The above functions obviously make the maximum number of assumptions about your data structures, and currently don't work sensibly with negative indices. -- Neil Cerutti -- http://mail.python.org/mailman/listinfo/python-list
Re: python logging filters
On Nov 30, 6:52 am, Grimsqueaker grimsqueake...@gmail.com 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 -- http://mail.python.org/mailman/listinfo/python-list
Re: Imitating tail -f
On 11:15 am, p...@boddie.org.uk wrote: On 22 Nov, 05:10, exar...@twistedmatrix.com wrote: tail -f is implemented by sleeping a little bit and then reading to see if there's anything new. This was the apparent assertion behind the 99 Bottles concurrency example: http://wiki.python.org/moin/Concurrency/99Bottles However, as I pointed out (and as others have pointed out here), a realistic emulation of tail -f would actually involve handling events from operating system mechanisms. Here's the exchange I had at the time: http://wiki.python.org/moin/Concurrency/99Bottles?action=diffrev2=12rev1=11 It can be very tricky to think up good examples of multiprocessing (which is what the above page was presumably intended to investigate), as opposed to concurrency (which can quite easily encompass responding to events asynchronously in a single process). Paul P.S. What's Twisted's story on multiprocessing support? In my limited experience, the bulk of the work in providing usable multiprocessing solutions is in the communications handling, which is something Twisted should do very well. Twisted includes a primitive API for launching and controlling child processes, reactor.spawnProcess. It also has several higher-level APIs built on top of this aimed at making certain common tasks more convenient. There is also a third-party project called Ampoule which provides a process pool to which it is is relatively straightforward to send jobs and then collect their results. Jean-Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: how to format a python source file with tools?
On Nov 27, 9:58 am, Diez B. Roggisch de...@nospam.web.de wrote: [...] so i would like to have a tool to intelligently format the code for me and make the code more beautiful and automated. This is not possible. Consider the following situation: [...] Both are semantically radically different, and only you know which one is the right one. Diez I have to agree with Diez, there is no way to automate this. Some human intervention is needed. What I would like is an editor that will indicate what Python will consider a logical block (and sub-block, and sub-sub-block, etc.) It's complicated. I've tried to think of a way to do it, and have gotten lost after a few changes of indentation. Does anyone know of such a thing? I miss curly braces with an editor that will highlight matching parentheses, braces, etc. Gil -- http://mail.python.org/mailman/listinfo/python-list
Re: * for generic unpacking and not just for arguments?
On Sun, 29 Nov 2009 13:45:18 -0600, Tim Chase wrote: The feature is available in Python 3.x: a, b, *c = 1, 2, 3, 4, 5 a, b, c (1, 2, [3, 4, 5]) a, *b, c = 1, 2, 3, 4, 5 a, b, c (1, [2, 3, 4], 5) This is a nice feature of 3.x but I'm disappointed (especially in light of the move to make more things iterators/generators), that the first form unpacks and returns a list instead returning the unexhausted generator. So you want *x behave radically different in subtly different contexts? a, *x, b = iterator would give x a list and iterator run to exhaustion, whereas: a, b, *x = iterator would give x identical to iterator, which hasn't run to exhaustion, while both of these: a, *x, b = sequence a, b, *x = sequence would give x a list, but in the second case, unlike the case of iterators, x would not be identical to sequence. No thank you, I'd prefer a nice, consistent behaviour than a magical Do what I mean function. However, having some syntax giving the behaviour you want would be nice. Something like this perhaps? a, b, c = *iterable equivalent to: _t = iter(iterable) a = next(_t) b = next(_t) c = next(_t) # and so on for each of the left-hand names del _t That would be useful. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: problem with lambda / closures
I figured out the answer to my own query. In the original example (see below), there was only one binding for k, which was shared by all the closures, so they all saw the same value. Consider: def fie2(k): return lambda: fie3(k) def fie3(m): print m def fie1(j): return fie2(j) l=map(fie1,[1,2,3]) map(lambda f:f(), l) This prints 1 2 3 because each lambda has its own binding of k. On Nov 30, 2009, at 7:35 AM, Louis Steinberg wrote: I have run into what seems to be a major bug, but given my short exposure to Python is probably just a feature: running Python 2.6.4 (r264:75821M, Oct 27 2009, 19:48:32) [GCC 4.0.1 (Apple Inc. build 5493)] on darwin with file foo.py containing: == clip here def p(d): print d l=[ ] for k in [1,2,3]: l.append(lambda : p(k)) for f in l: f() == clip here I get output 3 3 3 instead of 1 2 3 which I would expect. Can anyone explain this or give me a workaround? Thank you -- http://mail.python.org/mailman/listinfo/python-list
Re: dbapi2 select where IN (...)
yota.n...@gmail.com wrote: hello, I couldn't find how the dbapi2 planned to handle the sql IN statement. ex : SELECT * FROM table WHERE num IN (2,3,8,9); I'd be glad to take advantage of the ? mechanism, but what about tuples ! execute(SELECT * FROM table WHERE num IN ?; , ((2,3,8,9),))...fail... [...] You cannot use parameter binding when the number of parameters is unknown in advance. So you'll have to create this part of the SQL query differently. For example: ids = [2, 3, 8, 9] in_clause = ( + ,.join([str(id) for id in ids]) + ) query = select * from table where num in + in_clause -- Gerhard -- http://mail.python.org/mailman/listinfo/python-list
Re: Exec Statement Question
Victor Subervi wrote: if which == '': i = 0 all = '' while i len(meanings): table = '%s\n' % meanings[i] table += table\n tr\n td colspan='8' align='center'%s/td\n /tr % names[i] j = 0 for elt in code: if (j + 8) % 8 == 0: table += ' tr\n' table += ' td%s/td\n' % code[i] if (j + 8) % 8 == 0: table += ' /tr\n' j += 1 if table[-6:] != '/tr\n': table += ' /tr\n' table += '/table\n' all += table + 'br /br /' i += 1 print all This all works fine; however, if there is a better way of doing it, please let me know. Thanks, V I wonder which is worse, looking at your python code, or being blind :o) You should have a look at http://tottinge.blogsome.com/meaningfulnames/ Cheers, Jean-Michel -- http://mail.python.org/mailman/listinfo/python-list
Re: reading from a text file
Olof Bjarnason wrote: 2009/11/27 baboucarr sanneh sanne...@hotmail.com: hi all i would like to create a python program that would read from a text file and returns one result at random. e.g in the text file i have these data 1.hello 2.my name 3.is 4.World Your help is highly appreciated..thnx in advance Hi babourarr; import random with open(c:/test.txt) as f: lines = f.read().splitlines() random_line = lines[random.randrange(len(lines))] print(random_line) Or, slightly more simply: import random with open (c:/test.txt) as f: print random.choice (list (f)) You need the list () because random.choice only works on a finite iterable. TJG -- http://mail.python.org/mailman/listinfo/python-list
Re: dbapi2 select where IN (...)
Gerhard Häring g...@ghaering.de wrote: execute(SELECT * FROM table WHERE num IN ?; , ((2,3,8,9),))...fail... [...] You cannot use parameter binding when the number of parameters is unknown in advance. So you'll have to create this part of the SQL query differently. For example: ids = [2, 3, 8, 9] in_clause = ( + ,.join([str(id) for id in ids]) + ) query = select * from table where num in + in_clause You can use parameter bindings when you don't know the number of parameters in advance. Just don't create the query string until you do know the number of parameters: ids = [2, 3, 8, 9] query = select * from table where num in (%s) % ','.join('?'*len(ids)) execute(query, ids) -- Duncan Booth http://kupuguy.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: problem with lambda / closures
On Monday, November 30, 2009, Louis Steinberg l...@cs.rutgers.edu wrote: I have run into what seems to be a major bug, but given my short exposure to Python is probably just a feature: running Python 2.6.4 (r264:75821M, Oct 27 2009, 19:48:32) [GCC 4.0.1 (Apple Inc. build 5493)] on darwin with file foo.py containing: == clip here def p(d): print d l=[ ] for k in [1,2,3]: l.append(lambda : p(k)) for f in l: f() == clip here I get output 3 3 3 instead of 1 2 3 which I would expect. Can anyone explain this or give me a workaround? Thank you -- http://mail.python.org/mailman/listinfo/python-list I don't know if anyone considers python's incomplete implementation of closures a feature but it's documented so it's not really a bug either. I believe there is a trick with default arguments to get this to work, but I don't use lambdas enough to remember it. -- http://mail.python.org/mailman/listinfo/python-list
pywintypes error
Hi, When I try to use Django with Apache and mod_python, I am facing an issue. Since this is a very usual configuration, I hope this issue is already solved. My web sites fail with the following error : C:\\Python24\\Lib\\site-packages\\win32\\lib\\pywintypes.py, line 124, in?\n __import_pywin32_system_module__(pywintypes, globals()) [Mon Nov 30 15:13:50 2009] [error] [client 127.0.0.1] FileC:\ \Python24\\Lib\\site-packages\\win32\\lib\\pywintypes.py, line 114, in__import_pywin32_system_module__\n assert sys.modules[modname] isold_mod [Mon Nov 30 15:13:50 2009] [error] [client 127.0.0.1] AssertionError I checked the code in pywintypes and it is a sure assertion error: old_mod = sys.modules[modname] # Python can load the module mod = imp.load_dynamic(modname, found) # Check the sys.modules[] behaviour we describe above is true... if sys.version_info (3,0): assert sys.modules[modname] is old_mod assert mod is old_mod else: assert sys.modules[modname] is not old_mod assert sys.modules[modname] is mod # as above - re-reset to the *old* module object then update globs. sys.modules[modname] = old_mod globs.update(mod.__dict__) I have python 2.4 so, it goes to the first check and fails. Has anyone else faced this issue? How to solve the same? -- http://mail.python.org/mailman/listinfo/python-list