Re: status of Programming by Contract (PEP 316)?
Russ [EMAIL PROTECTED] writes: try: blah blah with as many return statements as you want finally: something that gets executed unconditionally at the end Thanks. I didn't think of that. So design by contract *is* relatively easy to use in Python already. The main issue, I suppose, is one of aesthetics. Do I want to use a lot of explicit function calls for pre and post-conditions and try/ finally blocks in my code to get DbC (not to mention a global variable to enable or disable it)? I still don't understand why you don't like the decorator approach, which can easily implement the above. I personally use Python for its clean syntax and its productivity with my time, so I am certainly not denigrating it. For the RD work I do, I think it is very appropriate. But I did raise a few eyebrows when I first started using it. I used C++ several years ago, and I thought about switching to Ada a few years ago, but Ada just seems to be fading away (which I think is very unfortunate, but that's another story altogether). It seems to be getting displaced by Java, which has some of the same benefits and costs as Ada does. I've gotten interested in static functional languages (including proof assistants like Coq, that can generate certified code from your mechanically checked theorems). But I haven't done anything serious with any of them yet. I think we're in a temporary situation where all existing languages suck (some more badly than others) but the functional languages seem like a more promising direction to get out of this hole. -- http://mail.python.org/mailman/listinfo/python-list
howto compile recursively all *.py files to *.pyc (from a directory my_dir)?
howto compile recursively all *.py files to *.pyc (from a directory my_dir)? Thank you in advance, D. -- http://mail.python.org/mailman/listinfo/python-list
Re: status of Programming by Contract (PEP 316)?
On Sep 1, 10:05 pm, Russ [EMAIL PROTECTED] wrote: changing the language itself. Someone please correct me if I am wrong, but I think PEP adds only to the libraries. I meant to write PEP 316, of course. -- http://mail.python.org/mailman/listinfo/python-list
Re: So what exactly is a complex number?
Tim Daneliuk wrote: Grzegorz Słodkowicz wrote: [...] You're mixing definition with application. You didn't say a word about what complex numbers are, not a word about the imaginary unit, where I was trying to motivate the idea by means of analogy. This is a legitimate thing to do. It helps lead people to a conceptual understanding long before they understand the minutae. I am well aware of the imaginary unit and from whence complex analysis springs. I just didn't think that was the best place to start explicating the *concept*. Gotta side with Grzegorz on this. Simplifying an explanation of complex numbers to the point of omitting the imaginary unit helps lead people to a conceptual *misunderstanding*. I don't like feeling confused, but where I really screw up is where I think I understand what I do not. -- --Bryan -- http://mail.python.org/mailman/listinfo/python-list
Re: status of Programming by Contract (PEP 316)?
On Sep 1, 11:04 pm, Paul Rubin wrote: I still don't understand why you don't like the decorator approach, which can easily implement the above. Well, maybe decorators are the answer. If a function needs only one decorator for all the conditions and invariants (pre and post- conditions), and if it can just point to functions defined elsewhere (rather than defining everything inline), then perhaps they make sense. I guess I need to read up more on decorators to see if this is possible. In fact, the ideal would be to have just a single decorator type, say contract or self_test, that takes an argument that points to the relevant functions to use for the function that the decorator applies to. Then the actual self-test functions could be pushed off somewhere else, and the footprint on the primary code would be minimal -- http://mail.python.org/mailman/listinfo/python-list
Re: How can I wait for all the threads I spawn for 5 minutes
herman wrote: In my python program, I would to like to spwan 5 threads, for the them for 5 minutes maximum and the continue. Here is my script: threads = [] for j in range(5): t = MyThread() threads.append(t) for t in threads: t.join(60*5) print thread join\n # wait for 5 minutes for all the threads to complete , and # then continue But this code ends up waiting 5 minutes for **each** thread. that is not what I want. I just want to wait for 5 minutes for all threads. how can I do that? Untested: from time import time deadline = time() + 60*5 for t in threads: t.join(max(0, deadline - time())) And after 5 minutes, i want to kill off all the threads I spawn earlier, how can I do that in python. That's harder. Python has no threadicide method, and its absence is not an oversight. Can you arrange for your threads to check a flag periodically, or might they be hung? Your other choice is to end the entire process. -- --Bryan -- http://mail.python.org/mailman/listinfo/python-list
Re: How best to dynamically define methods (and functions)?
Kenneth McDonald schrieb: I can see an obvious but hacky way to define a Python function at runtime. I can't see any obvious way to add a method to a class at runtime (though I'm sure one could do just about anything by digging into the metaclass stuff, which I will do if needed). But pointers to cleaner or easier existing ways to do this would be most appreciated. In case it's of interest in the context of the question, I need to define a largish set of functions (and similar methods) that define a XML-type markup language. Most of these functions will just be of the form def fun(...): return Node('fun', ...) so it'd definitely be nice to just create most of them automatically, and only do the special cases by hand. Then don't do it that way, but use __getattr__. It will exactly do what you want: class Foo(object): def __getattr__(self, name): return Node(name, ) def some_node(self): ... # hand coded stuff Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Windows Media Player Playlist
Lamonte Harris wrote: Is it possible to use python to get the current playlist of the current playing songs from Windows Media Player or Windows Player Classic? I don't know what the answer is (not least because I never use Windows Media Player) but a good guideline for this sort of question is: can it be done *without* python? The chances are that someone, somewhere, has tried to do this before and has found an answer using VBScript or C# or whatever. If you look around the internet and find such an answer, then people on this list can hopefully help you translate that into Python. TJG -- http://mail.python.org/mailman/listinfo/python-list
Re: How best to dynamically define methods (and functions)?
Kenneth McDonald wrote: I can see an obvious but hacky way to define a Python function at runtime. What way is this? All Python function definitions in your code are executed at runtime. In case it's of interest in the context of the question, I need to define a largish set of functions (and similar methods) that define a XML-type markup language. Most of these functions will just be of the form def fun(...): return Node('fun', ...) so it'd definitely be nice to just create most of them automatically, and only do the special cases by hand. This looks cumbersome to me. If you reworked the interface (perhaps using dicts or a generic function) it might get clearer. Regards, Björn -- BOFH excuse #241: _Rosin_ core solder? But... -- http://mail.python.org/mailman/listinfo/python-list
Re: localizing a sort
Am Sat, 01 Sep 2007 18:56:38 -0300 schrieb Ricardo Aráoz: Hi, I've been working on sorting out some words. My locale is : import locale locale.getdefaultlocale() ('es_AR', 'cp1252') I do : a = 'áéíóúäëïöüàèìòù' print ''.join(sorted(a, cmp=lambda x,y: locale.strcoll(x,y))) aeiouàáäèéëìíïòóöùúü The lambda is superfluous. Just write cmp=locale.strcoll instead. This is not what I am expecting. I was expecting : aáàäeéèëiíìï.etc. The reason is that if you want to order some words (say for a dictionary (paper dict, where you look up words)) this is what happens : a = 'palàbra de pàlabra de pblabra' print ' '.join(sorted(a.split(), cmp=lambda x,y: locale.strcoll(x, y))) de de palàbra pblabra pàlabra While any human being would expect : de de palàbra pàlabra pblabra Does anybody know a way in which I could get the desired output? I suppose it would work on your machine if you set the locale first with locale.setlocale(locale.LC_ALL, ) 'de_DE.UTF-8' I have to resort to a list instead of a string on mine because it uses the UTF-8 encoding where one character may consist of more than one byte. (Providing key is more efficient than cmp.) a = ['á', 'é', 'í', 'ó', 'ú', 'ä', 'ë', 'ï', 'ö', 'ü', 'à', 'è', 'ì', 'ò', 'ù', 'a', 'e', 'i', 'o', 'u'] print .join(sorted(a, key=locale.strxfrm)) aáàäeéèëiíìïoóòöuúùü However, to make your program a bit more portable I recommend that you use unicode instead of str: import locale locale.setlocale(locale.LC_ALL, ) 'de_DE.UTF-8' encoding = locale.getlocale()[1] def sortkey(s): ... return locale.strxfrm(s.encode(encoding)) ... print .join(sorted(uáéíóúäëïöüàèìòùaeiou, key=sortkey)) aáàäeéèëiíìïoóòöuúùü Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: howto compile recursively all *.py files to *.pyc (from a directory my_dir)?
On Sep 2, 7:21 am, dmitrey [EMAIL PROTECTED] wrote: howto compile recursively all *.py files to *.pyc (from a directory my_dir)? Thank you in advance, D. import compileall compileall.compile_dir('my/python/project/') -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list
Re: So what exactly is a complex number?
In message [EMAIL PROTECTED], Tim Daneliuk wrote: No, but go to my other example of an aircraft in flight and winds aloft. It is exactly the case that complex numbers provide a convenient way to add these two vectors (don't wince, please) to provide the effective speed and direction of the aircraft. Numerous such examples abound in physics, circuit analysis, the analysis of rotating machinery, etc. Not really. The thing with complex numbers is that they're numbers--mathematically, they comprise a number system with operations called addition, subtraction, multiplication and division having certain well-defined properties (e.g. associativity of multiplication, all numbers except possibly one not having a multiplicative inverse). An aircraft in flight amidst winds needs only vector addition (and possibly scalar multiplication) among the basic operations to compute its path--you don't need to work with complex numbers as such for that purpose. For my AC circuit theory example, however, you do. -- http://mail.python.org/mailman/listinfo/python-list
ANN: Python bindings for mjpegtools (yuv4mpeg)
Hi, I've built some bindings for the yuv4mpeg API, supporting both Python and C++. http://www.freenet.org.nz/pyyuv4mpeg/ Based on SWIG, implements virtually the whole API as given in yuv4mpeg.h, and also implements a high-level 'Stream' class in both C++ and Python. These bindings allow easy creation of video filters, in Python or C++, that work to the mjpegtools 'yuv4mpegpipe' standard - reading YUV4MPEG frames into stdin and/or writing YUV4MPEG frames to stdout. Enjoy Cheers David -- http://mail.python.org/mailman/listinfo/python-list
Re: status of Programming by Contract (PEP 316)?
Alex Martelli wrote: Ricardo Aráoz [EMAIL PROTECTED] wrote: ... We should remember that the level of security of a 'System' is the same as the level of security of it's weakest component, ... You win the argument, and thanks you prove my point. You typically concerned yourself with the technical part of the matter, yet you completely ignored the point I was trying to make. That's because I don't particularly care about the point you were trying to make (either for or against -- as I said, it's a case of ROI for different investments [in either security, or, more germanely to this thread, reliability] rather than of useful/useless classification of the investments), while I care deeply about proper system thinking (which you keep failing badly on, even in this post). And here you start, followed by 'F- at system thinking', 'glib and false assertions', 'falsities', etc. I don't think you meant anything personal, how could you, we don't know each other. But the outcome feels like a personal attack instead of an attack on the ideas exposed. If that's not what you intended, you should check your communication abilities and see what is wrong. If that is what you meant well... So I will not answer your post. I'll let it rest for a while till I don't feel the sting, then I'll re-read it and try to learn as much as I can from your thoughts (thank you for them). And even though some of your thinking process I find objectionable I will not comment on it as I'm sure it will start some new flame exchange which will have a lot to do with ego and nothing to do with python. -- http://mail.python.org/mailman/listinfo/python-list
Why is this loop heavy code so slow in Python? Possible Project Euler spoilers
I'm pretty new to python, but am very happy with it. As well as using it at work I've been using it to solve various puzzles on the Project Euler site - http://projecteuler.net. So far it has not let me down, but it has proved surprisingly slow on one puzzle. The puzzle is: p is the perimeter of a right angle triangle with integral length sides, {a,b,c}. which value of p 1000, is the number of solutions {a,b,c} maximised? Here's my python code: #!/usr/local/bin/python solutions = [0] * 1001 p = 0 for a in xrange(1, 1000): for b in xrange(1, 1000 - a): for c in xrange(1, 1000 - a - b): p = a + b + c if p 1000: if a ** 2 + b ** 2 == c ** 2: solutions[p] += 1 max = 0 maxIndex = 0 index = 0 for solution in solutions: if solution max: max = solution maxIndex = index index += 1 print maxIndex It takes 2 minutes and twelve seconds on a 2.4GHz Core2Duo MacBook Pro. Surprised at how slow it was I implemented the same algorithm in C: #include stdio.h #include stdlib.h int main() { int* solutions = calloc(1000, sizeof(int)); int p; for(int a = 1; a 1000; ++a) { for(int b = 1; b 1000 - a; ++b) { for(int c = 1; c 1000 - a - b; ++c) { p = a + b + c; if(p 1000) { if(a * a + b * b == c * c) { solutions[p] += 1; } } } } } int max = 0; int maxIndex = 0; for(int i = 0; i 1000; ++i) { if(solutions[i] max) { max = solutions[i]; maxIndex = i; } } printf(%d\n, maxIndex); return 0; } gcc -o 39 -std=c99 -O3 39.c The resulting executable takes 0.24 seconds to run. I'm not expecting a scripting language to run faster than native code, but I was surprised at how much slower it was in this case. Any ideas as to what is causing python so much trouble in the above code? -- http://mail.python.org/mailman/listinfo/python-list
Re: Why is this loop heavy code so slow in Python? Possible Project Euler spoilers
On Sep 2, 12:51 pm, [EMAIL PROTECTED] wrote: I'm pretty new to python, but am very happy with it. As well as using it at work I've been using it to solve various puzzles on the Project Euler site -http://projecteuler.net. So far it has not let me down, but it has proved surprisingly slow on one puzzle. The puzzle is: p is the perimeter of a right angle triangle with integral length sides, {a,b,c}. which value of p 1000, is the number of solutions {a,b,c} maximised? Here's my python code: #!/usr/local/bin/python solutions = [0] * 1001 p = 0 for a in xrange(1, 1000): for b in xrange(1, 1000 - a): for c in xrange(1, 1000 - a - b): p = a + b + c if p 1000: if a ** 2 + b ** 2 == c ** 2: solutions[p] += 1 max = 0 maxIndex = 0 index = 0 for solution in solutions: if solution max: max = solution maxIndex = index index += 1 print maxIndex It takes 2 minutes and twelve seconds on a 2.4GHz Core2Duo MacBook Pro. Surprised at how slow it was I implemented the same algorithm in C: #include stdio.h #include stdlib.h int main() { int* solutions = calloc(1000, sizeof(int)); int p; for(int a = 1; a 1000; ++a) { for(int b = 1; b 1000 - a; ++b) { for(int c = 1; c 1000 - a - b; ++c) { p = a + b + c; if(p 1000) { if(a * a + b * b == c * c) { solutions[p] += 1; } } } } } int max = 0; int maxIndex = 0; for(int i = 0; i 1000; ++i) { if(solutions[i] max) { max = solutions[i]; maxIndex = i; } } printf(%d\n, maxIndex); return 0; } gcc -o 39 -std=c99 -O3 39.c The resulting executable takes 0.24 seconds to run. I'm not expecting a scripting language to run faster than native code, but I was surprised at how much slower it was in this case. Any ideas as to what is causing python so much trouble in the above code? from math import sqrt solutions = [0] * 1001 p = 0 for a in xrange(1, 1000): a2 = a*a for b in xrange(1, 1000 - a): c = sqrt(a2 + b*b) if c == int(c) and a+b+c 1000: solutions[a+b+int(c)] += 1 max = 0 maxIndex = 0 index = 0 for solution in solutions: if solution max: max = solution maxIndex = index index += 1 print maxIndex -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list
Re: Why is this loop heavy code so slow in Python? Possible Project Euler spoilers
On Sep 2, 7:20 am, Arnaud Delobelle [EMAIL PROTECTED] wrote: On Sep 2, 12:51 pm, [EMAIL PROTECTED] wrote: I'm pretty new to python, but am very happy with it. As well as using it at work I've been using it to solve various puzzles on the Project Euler site -http://projecteuler.net. So far it has not let me down, but it has proved surprisingly slow on one puzzle. The puzzle is: p is the perimeter of a right angle triangle with integral length sides, {a,b,c}. which value of p 1000, is the number of solutions {a,b,c} maximised? Here's my python code: #!/usr/local/bin/python solutions = [0] * 1001 p = 0 for a in xrange(1, 1000): for b in xrange(1, 1000 - a): for c in xrange(1, 1000 - a - b): p = a + b + c if p 1000: if a ** 2 + b ** 2 == c ** 2: solutions[p] += 1 max = 0 maxIndex = 0 index = 0 for solution in solutions: if solution max: max = solution maxIndex = index index += 1 print maxIndex It takes 2 minutes and twelve seconds on a 2.4GHz Core2Duo MacBook Pro. Surprised at how slow it was I implemented the same algorithm in C: #include stdio.h #include stdlib.h int main() { int* solutions = calloc(1000, sizeof(int)); int p; for(int a = 1; a 1000; ++a) { for(int b = 1; b 1000 - a; ++b) { for(int c = 1; c 1000 - a - b; ++c) { p = a + b + c; if(p 1000) { if(a * a + b * b == c * c) { solutions[p] += 1; } } } } } int max = 0; int maxIndex = 0; for(int i = 0; i 1000; ++i) { if(solutions[i] max) { max = solutions[i]; maxIndex = i; } } printf(%d\n, maxIndex); return 0; } gcc -o 39 -std=c99 -O3 39.c The resulting executable takes 0.24 seconds to run. I'm not expecting a scripting language to run faster than native code, but I was surprised at how much slower it was in this case. Any ideas as to what is causing python so much trouble in the above code? from math import sqrt solutions = [0] * 1001 p = 0 for a in xrange(1, 1000): a2 = a*a for b in xrange(1, 1000 - a): c = sqrt(a2 + b*b) if c == int(c) and a+b+c 1000: solutions[a+b+int(c)] += 1 max = 0 maxIndex = 0 index = 0 for solution in solutions: if solution max: max = solution maxIndex = index index += 1 print maxIndex -- Arnaud For the curious: O O + P A A + P === === === === 2:22.56 0:25.65 0:00.75 0:00.20 O = Original Implementation P = Psyco (psyco.full()) A = Arnaud's Revised Implementation -- http://mail.python.org/mailman/listinfo/python-list
Re: Why is this loop heavy code so slow in Python? Possible Project Euler spoilers
[EMAIL PROTECTED] wrote in news:[EMAIL PROTECTED]: The puzzle is: p is the perimeter of a right angle triangle with integral length sides, {a,b,c}. which value of p 1000, is the number of solutions {a,b,c} maximised? Here's my python code: #!/usr/local/bin/python solutions = [0] * 1001 p = 0 for a in xrange(1, 1000): for b in xrange(1, 1000 - a): for c in xrange(1, 1000 - a - b): p = a + b + c if p 1000: if a ** 2 + b ** 2 == c ** 2: solutions[p] += 1 Once p = 1000, it ain't goin' back. If you break out of the innermost loop here after that happens, you'll save a bunch of time. max = 0 maxIndex = 0 index = 0 for solution in solutions: if solution max: max = solution maxIndex = index index += 1 print maxIndex It takes 2 minutes and twelve seconds on a 2.4GHz Core2Duo MacBook Pro. [...] The resulting executable takes 0.24 seconds to run. I'm not expecting a scripting language to run faster than native code, but I was surprised at how much slower it was in this case. Any ideas as to what is causing python so much trouble in the above code? -- http://mail.python.org/mailman/listinfo/python-list
Re: Why is this loop heavy code so slow in Python? Possible Project Euler spoilers
[snip code] Thanks for that. I realise that improving the algorithm will speed things up. I wanted to know why my less than perfect algorithm was so much slower in python than exactly the same algorithm in C. Even when turning off gcc's optimiser with the -O0 flag, the C version is still 100 times quicker. -- http://mail.python.org/mailman/listinfo/python-list
Re: Why is this loop heavy code so slow in Python? Possible Project Euler spoilers
On Sep 2, 9:45 am, [EMAIL PROTECTED] wrote: [snip code] Thanks for that. I realise that improving the algorithm will speed things up. I wanted to know why my less than perfect algorithm was so much slower in python than exactly the same algorithm in C. Even when turning off gcc's optimiser with the -O0 flag, the C version is still 100 times quicker. Well, for one thing, you're creating half a million xrange objects in the course of the search. All the C code has to do is increment a few integers. Mark -- http://mail.python.org/mailman/listinfo/python-list
Re: list index()
On Aug 30, 11:23 am, [EMAIL PROTECTED] wrote: Neil, Steve, Thanks for the responses on sets. I have not used them before and was not even aware Python had them. I will try them out. And if there weren't sets you would still not use find or index but a brute force method or dictionaries for each in dir_a_list : if each not in dir_b_list : print each, not in dir_b -- http://mail.python.org/mailman/listinfo/python-list
Re: Why is this loop heavy code so slow in Python? Possible Project Euler spoilers
On Sep 2, 9:45 pm, [EMAIL PROTECTED] wrote: [snip code] Thanks for that. I realise that improving the algorithm will speed things up. I wanted to know why my less than perfect algorithm was so much slower in python than exactly the same algorithm in C. Even when turning off gcc's optimiser with the -O0 flag, the C version is still 100 times quicker.- Hide quoted text - - Show quoted text - Maybe Python is the slowest programming language in the world. So there is a joke: some python hater said that python can only crawl rather than run. :) Python is slow because: (1) dynamic binding (2) it is a interpretation language For example, in C code, an interger expression a+b will directly generate an assembly code add for x86 processors. A python interpreter, on the other side, need detect the type of a and b first, then choose the right + operation for them and use a evaluation stack to get the result. Psyco is a JIT compiler with just in time specialization which can somehow solve these two problems -- http://mail.python.org/mailman/listinfo/python-list
Re: Pivy problem and some other stuff
On Aug 30, 8:10 pm, Scott David Daniels [EMAIL PROTECTED] wrote: Marc 'BlackJack' Rintsch wrote: A fine repy In [57]: funcs = [a, b] In [58]: funcs Out[58]: [function a at 0xb7792e2c, function b at 0xb779e1ec] In [59]: funcs[0]() Out[59]: 1 In [60]: funcs[1]() Out[60]: 2 and a list comprehension allows you to call these things no matter how long the list is. So after the above: results = [f() for f in funcs] print results [1, 2] You can also use exec, but someone will tell you that the sky is going to fall if you do. I am one of the ones who think that calling a function with results = [f() for f in funcs] doesn't work because it gives a meaningless error message that the calling line didn't work. There is already enough discussion about this, so if you use some_string() to call a function, wrap it in a try/except with a traceback. -- http://mail.python.org/mailman/listinfo/python-list
Re: Let's Unite Against Jews and Mongrels!
On Aug 28, 4:50 am, Richard B. Gilbert [EMAIL PROTECTED] wrote: Unless, of course, someone has a working Killbot. If anyone has such a thing, please kill that MI5victim moron as well! I reported MI5victim to [EMAIL PROTECTED] and it appears to be gone, as well as the free air conditioner's posts. (Thanks Steve Holden for the reminder that it doesn't have to be personal e-mail spam in order to be reported). If the OP posts again, report it. Something like 75% of internet mail is spam. -- http://mail.python.org/mailman/listinfo/python-list
Re: Why is this loop heavy code so slow in Python? Possible Project Euler spoilers
On Sep 2, 12:51 pm, [EMAIL PROTECTED] wrote: [...] The resulting executable takes 0.24 seconds to run. I'm not expecting a scripting language to run faster than native code, but I was surprised at how much slower it was in this case. Any ideas as to what is causing python so much trouble in the above code? Sorry I didn't answer your question at all in my previous post (although my modified method gets the answer in about 6s on a measly PB G4 1GHz :). Your little code snippet is just about the worst bit of code for python to be compared to C. Three loops, only integer arithmetic: that's not going to make Python shine! Nevertheless as you optimise your C snippet (-O3), there are probably a few things that the compiler does for you: * as in the inner loop, a*a + b*b always remain the same, it is probably stored in a register once and for all * in the second loop, a*a remains the same so it might be calculated once and for all as well. It gives this: M = 1000 solutions = [0] * M def f1(): Your original implementation for a in xrange(1, M): for b in xrange(1, M - a): for c in xrange(1, M - a - b): if a**2 + b**2 == c**2: solutions[a+b+c] += 1 def f2(): a*a + b*b precalculated for a in xrange(1, M): a2 = a*a for b in xrange(1, M - a): s = a2 + b*b for c in xrange(1, M - a - b): if s == c*c: solutions[a+b+c] += 1 It doesn't make it as quick as C of course, but more than halves the execution time. -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list
Re: localizing a sort
Peter Otten wrote: Am Sat, 01 Sep 2007 18:56:38 -0300 schrieb Ricardo Aráoz: Hi, I've been working on sorting out some words. My locale is : import locale locale.getdefaultlocale() ('es_AR', 'cp1252') I do : a = 'áéíóúäëïöüàèìòù' print ''.join(sorted(a, cmp=lambda x,y: locale.strcoll(x,y))) aeiouàáäèéëìíïòóöùúü The lambda is superfluous. Just write cmp=locale.strcoll instead. No it is not : print ''.join(sorted(a, cmp=locale.strcoll(x,y))) Traceback (most recent call last): File input, line 1, in module TypeError: strcoll expected 2 arguments, got 0 You need the lambda to assign both arguments. This is not what I am expecting. I was expecting : aáàäeéèëiíìï.etc. The reason is that if you want to order some words (say for a dictionary (paper dict, where you look up words)) this is what happens : a = 'palàbra de pàlabra de pblabra' print ' '.join(sorted(a.split(), cmp=lambda x,y: locale.strcoll(x, y))) de de palàbra pblabra pàlabra While any human being would expect : de de palàbra pàlabra pblabra Does anybody know a way in which I could get the desired output? I suppose it would work on your machine if you set the locale first with locale.setlocale(locale.LC_ALL, ) This works. Thanks Peter. -- http://mail.python.org/mailman/listinfo/python-list
Re: Let's Unite Against Jews and Mongrels!
Zentrader wrote: On Aug 28, 4:50 am, Richard B. Gilbert [EMAIL PROTECTED] wrote: Unless, of course, someone has a working Killbot. If anyone has such a thing, please kill that MI5victim moron as well! I reported MI5victim to [EMAIL PROTECTED] and it appears to be gone, as well as the free air conditioner's posts. (Thanks Steve Holden for the reminder that it doesn't have to be personal e-mail spam in order to be reported). If the OP posts again, report it. Something like 75% of internet mail is spam. MI5victim was alive and (I won't say well!!) a week ago. It remains to be seen if he's gone. And if you believe that reporting spam to [EMAIL PROTECTED] actually has any effect on spam, you must believe in the Tooth Fairy as well! There will be spam as long as there are morons who will send the spammers money for whatever they're peddling! I still get two or three Spanish Prisoner a/k/a 401 scams each week (this is the one where somebody has $30,000,000 US and will share it with you if only you will send him a little of your money)! The US government does seem to have cracked down on the Pharmacy spam and the internet pharmacies that were behind it. Remember, it costs essentially nothing to send spam to 30,000,000 people and if the spammer gets 0.5% response, he's ahead of the game! -- http://mail.python.org/mailman/listinfo/python-list
Re: list index()
On 9/2/07, Zentrader [EMAIL PROTECTED] wrote: On Aug 30, 11:23 am, [EMAIL PROTECTED] wrote: Neil, Steve, Thanks for the responses on sets. I have not used them before and was not even aware Python had them. I will try them out. And if there weren't sets you would still not use find or index but a brute force method or dictionaries for each in dir_a_list : if each not in dir_b_list : print each, not in dir_b This is O(N_a * N_b)... unless the list are always small, it's definitely better (if one is decided not to use sets) to use dictionaries :-) bye francesco -- http://mail.python.org/mailman/listinfo/python-list
Re: Why is this loop heavy code so slow in Python? Possible Project Euler spoilers
In article [EMAIL PROTECTED], Mark Dickinson [EMAIL PROTECTED] wrote: On Sep 2, 9:45 am, [EMAIL PROTECTED] wrote: [snip code] Thanks for that. I realise that improving the algorithm will speed things up. I wanted to know why my less than perfect algorithm was so much slower in python than exactly the same algorithm in C. Even when turning off gcc's optimiser with the -O0 flag, the C version is still 100 times quicker. Well, for one thing, you're creating half a million xrange objects in the course of the search. All the C code has to do is increment a few integers. Mark Right: Mr. Dickinson's original question is entirely legitimate, and it's not adequate to respond, as some follow-ups did, with ways to improve the Python-coded algorithm. The correct answer, which I want to reinforce, is that the exhibited Python and C versions are NOT exactly the same algorithm, at least not without more quali- fication. Part of Python expertise is to recognize that creation of xrange objects, mentioned above, is far from free. Also, -O3 gives C the opportunity, also remarked in a follow-up, to factor calculations outside their loops. -- http://mail.python.org/mailman/listinfo/python-list
Re: create Powerpoint via com
Well, my needs were very limited so the result is too, but in case someone else just needs to get started: http://econpy.googlecode.com/svn/trunk/utilities/mso.py Comments, suggestions, additions welcom. Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
RE: Pythonwin Install COM exceptions on Windows Vista Ultimate
Here are some steps I used to finally successfully install Python and Pythonwin on Vista Ultimate: 1. Uninstalled Python (could not see a way to uninstall Pythonwin) 2. Installed Python again (.MSI does not provide option to run as Administrator) 3. Rebooted computer 4. Installed Pythonwin with right click option Run as Administrator - This was different from the last time I installed this. Copied pythoncom25.dll to C:\Windows\system32\pythoncom25.dll Copied pywintypes25.dll to C:\Windows\system32\pywintypes25.dll Registered: Python.Interpreter Registered: Python.Dictionary Registered: Python - Software\Python\PythonCore\2.5\Help[None]=None - Software\Python\PythonCore\2.5\Help\Pythonwin Reference[None]='C:\\Python25\\Lib\\site-packages\\PyWin32.chm' Shortcut for Pythonwin created Shortcut to documentation created The pywin32 extensions were successfully installed. This time, no errors. 5. Started up a Python script from a directory using right-click | Open With | Pythonwin.exe and it works fine. Earlier it was giving an error about not being able to locate win32ui.pyd. I did not touch UAC or Router/Rooter/Firewall ... I did not know how to. Thanks. Sandipan -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of Sandipan News Sent: Wednesday, August 29, 2007 9:41 PM To: 'Méta-MCI (MVP)'; python-list@python.org Subject: RE: Pythonwin Install COM exceptions on Windows Vista Ultimate How do I deactivate UAC and Router? I did run as Administrator and installed both Python and Pythonwin into c:\Python25\ This is the error I got ... Here is the log at the end of the install: Copied pythoncom25.dll to C:\Outils\Python\pythoncom25.dll Copied pywintypes25.dll to C:\Outils\Python\pywintypes25.dll You do not have the permissions to install COM objects. The sample COM objects were not registered. - Software\Python\PythonCore\2.5\Help[None]=None - Software\Python\PythonCore\2.5\Help\Pythonwin Reference[None]='C:\\Outils\\Python\\Lib\\site-packages\\PyWin32.chm' Creating directory C:\Outils\Python\Lib\site-packages\win32com\gen_py Shortcut for Pythonwin created Shortcut to documentation created The pywin32 extensions were successfully installed. Thanks. Sandipan -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of Méta-MCI (MVP) Sent: Wednesday, August 29, 2007 9:19 AM To: python-list@python.org Subject: Re: Pythonwin Install COM exceptions on Windows Vista Ultimate Hi! Perso, on Vista, I : - deactive UAC - deactive firewall (I have a rooter) - run all like Administrator - install all in other DIR than Program Files Result : no problem. -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Glade + Python = No GUI
I made simple GUI in Glade 3 (Ubuntu 7.04) consisting of only 2 buttons. When I run 2buttonsgui.py, no GUI pops out #!/usr/bin/env python import pygtk import gtk.glade class TwoButtonsGUI: def __init__(self): self.window = gtk.glade.XML(/home/myusername/Desktop/ 2buttons.glade, window1) if __name__ == '__main__': TwoButtonsGUI() gtk.main() When interrupted, I get File gui.py, line 11, in module gtk.main() When GUI coded manually, all works. Thanks in advance -- http://mail.python.org/mailman/listinfo/python-list
Re: status of Programming by Contract (PEP 316)?
In article [EMAIL PROTECTED], Russ [EMAIL PROTECTED] wrote: Excellent points. As for no strong case for adding new features to Python specifically for design-by-contract, if you mean adding something to language itself, I agree, but I see nothing wrong with adding it to the standard libraries, if that is possible without changing the language itself. Someone please correct me if I am wrong, but I think PEP adds only to the libraries. You're wrong, but even aside from that, libraries need to prove themselves useful before they get added. -- Aahz ([EMAIL PROTECTED]) * http://www.pythoncraft.com/ Many customs in this life persist because they ease friction and promote productivity as a result of universal agreement, and whether they are precisely the optimal choices is much less important. --Henry Spencer http://www.lysator.liu.se/c/ten-commandments.html -- http://mail.python.org/mailman/listinfo/python-list
Re: Why is this loop heavy code so slow in Python? Possible Project Euler spoilers
Ivan Wang a écrit : On Sep 2, 9:45 pm, [EMAIL PROTECTED] wrote: [snip code] Thanks for that. I realise that improving the algorithm will speed things up. I wanted to know why my less than perfect algorithm was so much slower in python than exactly the same algorithm in C. Even when turning off gcc's optimiser with the -O0 flag, the C version is still 100 times quicker.- Hide quoted text - - Show quoted text - Maybe Python is the slowest programming language in the world. So there is a joke: some python hater said that python can only crawl rather than run. :) Python is slow because: (1) dynamic binding Yes. (2) it is a interpretation language Not quite. It's compiled to byte-code - just like Java (would you call Java an 'interpreted language' ?) -- http://mail.python.org/mailman/listinfo/python-list
Re: Why is this loop heavy code so slow in Python? Possible Project Euler spoilers
Mark Dickinson [EMAIL PROTECTED] wrote: On Sep 2, 9:45 am, [EMAIL PROTECTED] wrote: [snip code] Thanks for that. I realise that improving the algorithm will speed things up. I wanted to know why my less than perfect algorithm was so much slower in python than exactly the same algorithm in C. Even when turning off gcc's optimiser with the -O0 flag, the C version is still 100 times quicker. Well, for one thing, you're creating half a million xrange objects in the course of the search. All the C code has to do is increment a few integers. I don't think the creation of xrange objects is a meaningful part of Python's execution time here. Consider: M = 1000 solutions = [0] * M def f2(): a*a + b*b precalculated for a in xrange(1, M): a2 = a*a for b in xrange(1, M - a): s = a2 + b*b for c in xrange(1, M - a - b): if s == c*c: solutions[a+b+c] += 1 def f3(M=M, solutions=solutions): pull out all the stops xrs = [xrange(1, k) for k in xrange(0, M+1)] for a in xrs[M]: a2 = a*a for b in xrs[M-a]: s = a2 + b*b for c in xrs[M-a-b]: if s == c*c: solutions[a+b+c] += 1 import time t = time.time() f2() e = time.time() print e-t, max(xrange(M), key=solutions.__getitem__) solutions = [0]*M t = time.time() f3(M, solutions) e = time.time() print e-t, max(xrange(M), key=solutions.__getitem__) f2 is Arnaud's optimization of the OP's algorithm by simple hoisting; f3 further hoists the xrange creation -- it creates only 1000 such objects rather than half a million. And yet...: brain:~/py25 alex$ python puz.py 34.6613101959 840 36.2000119686 840 brain:~/py25 alex$ ...which suggests that creating an xrange object is _cheaper_ than indexing a list... Alex -- http://mail.python.org/mailman/listinfo/python-list
Re: localizing a sort
Ricardo Aráoz [EMAIL PROTECTED] wrote: Peter Otten wrote: ... print ''.join(sorted(a, cmp=lambda x,y: locale.strcoll(x,y))) aeiouàáäèéëìíïòóöùúü The lambda is superfluous. Just write cmp=locale.strcoll instead. No it is not : print ''.join(sorted(a, cmp=locale.strcoll(x,y))) Traceback (most recent call last): File input, line 1, in module TypeError: strcoll expected 2 arguments, got 0 You need the lambda to assign both arguments. No, your mistake is that you're CALLING locale.strcoll, while as Peter suggested you should just PASS it as the cmp argument. I.e., ''.join(sorted('ciao', cmp=locale.strcoll)) Using key=locale.strxfrm should be faster (at least when you're sorting long-enough lists of strings), which is why strxfrm (and key=...:-) exist in the first place, but cmp=locale.strcoll, while usually slower, is entirely correct. That lambda _IS_ superfluous, as Peter said. Alex -- http://mail.python.org/mailman/listinfo/python-list
Re: Why is this loop heavy code so slow in Python? Possible Project Euler spoilers
[EMAIL PROTECTED] (Alex Martelli) writes: ...which suggests that creating an xrange object is _cheaper_ than indexing a list... Why not re-use the xrange instead of keeping a list around? Python 2.4.4 (#1, Oct 23 2006, 13:58:00) a = xrange(3) print list(a) [0, 1, 2] print list(a) [0, 1, 2] -- http://mail.python.org/mailman/listinfo/python-list
Re: code check for modifying sequence while iterating over it?
Neal Becker [EMAIL PROTECTED] wrote: After just getting bitten by this error, I wonder if any pylint, pychecker variant can detect this error? I know pychecker can't (and I doubt pylint can, but I can't download the latest version to check as logilab's website is temporarily down for maintenance right now). It's a very thorny problem to detect a reasonable subset of likely occurrences of this bug by static analysis only, i.e., without running the code:-( Alex -- http://mail.python.org/mailman/listinfo/python-list
Re: Google spreadsheets
iapain [EMAIL PROTECTED] wrote: On Aug 31, 5:40 pm, Michele Simionato [EMAIL PROTECTED] wrote: I would like to upload a tab-separated file to a Google spreadsheet from Python. Does anybody have a recipe handy? TIA, Michele Simionato Probably its irrelevant to python. Use should see Google Spreadsheet API and use it in your python application. http://code.google.com/apis/spreadsheets/ For Python-specific use, you probably want to get the Python version of the GData client libraries, http://code.google.com/p/gdata-python-client/ ; an example of using it with a spreadsheet is at http://gdata-python-client.googlecode.com/svn/trunk/samples/spreadsheet s/spreadsheetExample.py . Alex -- http://mail.python.org/mailman/listinfo/python-list
Re: Pivy problem and some other stuff
On Sun, 02 Sep 2007 14:35:00 +, Zentrader wrote: You can also use exec, but someone will tell you that the sky is going to fall if you do. I am one of the ones who think that calling a function with results = [f() for f in funcs] doesn't work because it gives a meaningless error message that the calling line didn't work. What meaningless error message are you talking about!? Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Why is this loop heavy code so slow in Python? Possible Project Euler spoilers
Paul Rubin http://[EMAIL PROTECTED] wrote: [EMAIL PROTECTED] (Alex Martelli) writes: ...which suggests that creating an xrange object is _cheaper_ than indexing a list... Why not re-use the xrange instead of keeping a list around? Python 2.4.4 (#1, Oct 23 2006, 13:58:00) a = xrange(3) print list(a) [0, 1, 2] print list(a) [0, 1, 2] Reusing xranges is exactly what my code was doing -- at each for loop you need an xrange(1, k) for a different value of k, which is why you need some container to keep them around (and a list of xrange objects is the simplest applicable container). Your suggestion doesn't appear to make any sense in the context of the optimization problem at hand -- what list(...) calls are you thinking of?! Please indicate how your suggestion would apply in the context of: def f3(M=M, solutions=solutions): pull out all the stops xrs = [xrange(1, k) for k in xrange(0, M+1)] for a in xrs[M]: a2 = a*a for b in xrs[M-a]: s = a2 + b*b for c in xrs[M-a-b]: if s == c*c: solutions[a+b+c] += 1 Alex -- http://mail.python.org/mailman/listinfo/python-list
Re: Glade + Python = No GUI
Kveldulv wrote: I made simple GUI in Glade 3 (Ubuntu 7.04) consisting of only 2 buttons. When I run 2buttonsgui.py, no GUI pops out #!/usr/bin/env python import pygtk import gtk.glade class TwoButtonsGUI: def __init__(self): self.window = gtk.glade.XML(/home/myusername/Desktop/ 2buttons.glade, window1) if __name__ == '__main__': TwoButtonsGUI() gtk.main() When interrupted, I get File gui.py, line 11, in module gtk.main() When GUI coded manually, all works. Shouldnt there be more to that error message of yours? I would expect something like NameError: name 'gtk' is not defined? Because as it seems you haven't impored gtk (only gtk.glade). So adding import gtk at the beginning should help. I may be wrong; I recall some weird importing requirements for pygtk, so I'm not sure if I'm to uninformed to see the actual problem. /W -- http://mail.python.org/mailman/listinfo/python-list
Re: Why is this loop heavy code so slow in Python? Possible Project Euler spoilers
[EMAIL PROTECTED] (Alex Martelli) writes: Reusing xranges is exactly what my code was doing Oh cool, I missed that, I was just going by the text description. Looking at the code, yes, it's re-using the xranges. Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: Why is this loop heavy code so slow in Python? Possible Project Euler spoilers
On Sep 2, 12:55 pm, [EMAIL PROTECTED] (Alex Martelli) wrote: Mark Dickinson [EMAIL PROTECTED] wrote: Well, for one thing, you're creating half a million xrange objects in the course of the search. All the C code has to do is increment a few integers. I don't think the creation of xrange objects is a meaningful part of Python's execution time here. Consider: [...] Agreed---I just came to the same conclusion after doing some tests. So maybe it's the billion or so integer objects being created that dominate the running time? (Not sure how many integer objects actually are created here: doesn't Python cache *some* small integers?) Mark -- http://mail.python.org/mailman/listinfo/python-list
Re: Google spreadsheets
On Sep 2, 7:13 pm, [EMAIL PROTECTED] (Alex Martelli) wrote: iapain [EMAIL PROTECTED] wrote: On Aug 31, 5:40 pm, Michele Simionato [EMAIL PROTECTED] wrote: I would like to upload a tab-separated file to a Google spreadsheet from Python. Does anybody have a recipe handy? TIA, Michele Simionato Probably its irrelevant to python. Use should see Google Spreadsheet API and use it in your python application. http://code.google.com/apis/spreadsheets/ For Python-specific use, you probably want to get the Python version of the GData client libraries, http://code.google.com/p/gdata-python-client/ ; an example of using it with a spreadsheet is at http://gdata-python-client.googlecode.com/svn/trunk/samples/spreadsheet s/spreadsheetExample.py . Alex Thanks Alex, that's exactly what I was looking for. Michele -- http://mail.python.org/mailman/listinfo/python-list
Re: localizing a sort
Alex Martelli wrote: Ricardo Aráoz [EMAIL PROTECTED] wrote: Peter Otten wrote: ... print ''.join(sorted(a, cmp=lambda x,y: locale.strcoll(x,y))) aeiouàáäèéëìíïòóöùúü The lambda is superfluous. Just write cmp=locale.strcoll instead. No it is not : print ''.join(sorted(a, cmp=locale.strcoll(x,y))) Traceback (most recent call last): File input, line 1, in module TypeError: strcoll expected 2 arguments, got 0 You need the lambda to assign both arguments. No, your mistake is that you're CALLING locale.strcoll, while as Peter suggested you should just PASS it as the cmp argument. I.e., ''.join(sorted('ciao', cmp=locale.strcoll)) Using key=locale.strxfrm should be faster (at least when you're sorting long-enough lists of strings), which is why strxfrm (and key=...:-) exist in the first place, but cmp=locale.strcoll, while usually slower, is entirely correct. That lambda _IS_ superfluous, as Peter said. Alex Got it! And it is MUCH more elegant than my code. Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Adding attributes stored in a list to a class dynamically.
Hi, Sorry if the subject line of post is wrong, but I think that is what this is called. I want to create objects with class Coconuts(object): def __init__(self, a, b, *args, **kwargs): self.a = a self.b = b def spam( l ) return Coconuts( l.a, l.b, l.attributes ) l in a parse line of a file which is a tuple wrapped with attrcol..with attributes a, b and attributes (which is a list of strings in the format key=value ie... [ id=bar, test=1234, doh=qwerty ] ). I want to add attributes to Coconuts so that I can do print c.id, c.test, c.doh HOwever I m not sure how to do this: how can i assign args, kwargs within the constructor of coconuts and how can I deconstruct the list to form the correct syntax to be able to be used for args, kwargs. HOpe this makes sense, Thanks in advance, Nathan -- http://mail.python.org/mailman/listinfo/python-list
Re: Glade + Python = No GUI
On Sep 2, 7:29 pm, Wildemar Wildenburger [EMAIL PROTECTED] wrote: Shouldnt there be more to that error message of yours? I would expect something like NameError: name 'gtk' is not defined? Because as it seems you haven't impored gtk (only gtk.glade). So adding import gtk at the beginning should help. I may be wrong; I recall some weird importing requirements for pygtk, so I'm not sure if I'm to uninformed to see the actual problem. /W Nope, everything imports well, no errors. With import gtk added, I get the same thing... -- http://mail.python.org/mailman/listinfo/python-list
Would like to perform unpaid research work at a CS graduate school or center
To all, About twenty years ago, I was admitted to a Ph.D. program for computer science. It was also around that time that I was diagnosed for chronic depression, which forced me out of that program into the working word. I had done my best since then as a software engineer, until late 2005, when I was laid off by my most recent workplace. I have now been out of work for 2 years, with no hope of finding anything further. I have been on medication for my depression since 1998, which moderates it somewhat. Until that time the disease has played havoc with my interpersonal and employment relationships, I had always done my best to compensate by immersing myself in the actual work. Most ironically, I am now as strong as I ever was for being a researcher, even more so for my practical experience, and so long as I avoid a punishing work and study load I believe I could do better on a second attempt for a doctorate than I ever did on my first. The problem is obtaining research related references. I would like to find a graduate CS department or university research center that would allow me to perform unpaid research work on a remote basis. I have some interests in parallel computing, from an architecture, programming language, and applications point of view. I will also consider other topics. I hold a bachelor's degree in electrical engineering and a master's degree in computer science, with about 12 to 15 years of practical software experience in systems programming and embedded programming. I also hold an Amateur Extra ticket and have my own electronics laboratory. Please, this is a sincere request. Interested parties please send email to [EMAIL PROTECTED] I hold a bachelor's degree in electrical engineering and a master's degree in computer science, with about 12 to 15 years of practical software experience in systems programming and embedded programming. I also hold an Amateur Extra ticket and have my own electronics laboratory. Please, this is a sincere request. Interested parties please send email to [EMAIL PROTECTED] I hold a bachelor's degree in electrical engineering and a master's degree in computer science, with about 12 to 15 years of practical software experience in systems programming and embedded programming. I also hold an Amateur Extra ticket and have my own electronics laboratory. Please, this is a sincere request. Interested parties please send email to [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Pivy problem and some other stuff
What meaningless error message are you talking about!? Ciao, Marc 'BlackJack' Rintsch My mistake. It appears that this is no longer the case. And my apologies. It was probably in version 2.3 or earlier that this was a problem. Given the way that the Python community constantly improves the language, I should have checked first, but shoulds don't count. -- http://mail.python.org/mailman/listinfo/python-list
Re: Why is this loop heavy code so slow in Python? Possible Project Euler spoilers
(2) it is a interpretation language Not quite. It's compiled to byte-code - just like Java (would you call Java an 'interpreted language' ?) Python is not implemented like Java. In Java (at least in HotSpot), the byte code is further compiled to machine code before execution; in Python, the byte code is interpreted. Whether this makes Python an interpreter or a compiler, I don't know. Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: Why is this loop heavy code so slow in Python? Possible Project Euler spoilers
Mark Dickinson [EMAIL PROTECTED] wrote: On Sep 2, 12:55 pm, [EMAIL PROTECTED] (Alex Martelli) wrote: Mark Dickinson [EMAIL PROTECTED] wrote: Well, for one thing, you're creating half a million xrange objects in the course of the search. All the C code has to do is increment a few integers. I don't think the creation of xrange objects is a meaningful part of Python's execution time here. Consider: [...] Agreed---I just came to the same conclusion after doing some tests. So maybe it's the billion or so integer objects being created that dominate the running time? (Not sure how many integer objects actually are created here: doesn't Python cache *some* small integers?) Yep, some, say -5 to 100 or thereabouts; it also caches on a free-list all the empty integer-objects it ever has (rather than returning the memory for the system), so I don't think there's much optimization to be had on that score either. Alex -- http://mail.python.org/mailman/listinfo/python-list
Re: Adding attributes stored in a list to a class dynamically.
Nathan Harmston [EMAIL PROTECTED] wrote: Hi, Sorry if the subject line of post is wrong, but I think that is what this is called. I want to create objects with class Coconuts(object): def __init__(self, a, b, *args, **kwargs): self.a = a self.b = b def spam( l ) return Coconuts( l.a, l.b, l.attributes ) l in a parse line of a file which is a tuple wrapped with attrcol..with attributes a, b and attributes (which is a list of strings in the format key=value ie... [ id=bar, test=1234, doh=qwerty ] ). I want to add attributes to Coconuts so that I can do print c.id, c.test, c.doh HOwever I m not sure how to do this: how can i assign args, kwargs within the constructor of coconuts and how can I deconstruct the list to form the correct syntax to be able to be used for args, kwargs. If you want to pass the attributes list it's simpler to do that directly, avoiding *a and **k constructs. E.g.: def __init__(self, a, b, attrs): self.a = a self.b = b for attr in attrs: name, value = attr.split('=') setattr(self, name, value) You may want to add some better error-handling (this code just raises exceptions if any item in attrs has !=1 occurrences of the '=' sign, etc, etc), but I hope this gives you the general idea. Note that you'll have trouble accessing attributes that just happen to be named like a Python keyword, e.g. if you have yield=23 as one of your attributes you will NOT be able to just say c.yield to get at that attribute. Also, I'm assuming it's OK for all of these attributes' values to be strings, etc, etc. Alex -- http://mail.python.org/mailman/listinfo/python-list
Re: Why is this loop heavy code so slow in Python? Possible Project Euler spoilers
Martin v. Löwis wrote: (2) it is a interpretation language Not quite. It's compiled to byte-code - just like Java (would you call Java an 'interpreted language' ?) Python is not implemented like Java. In Java (at least in HotSpot), the byte code is further compiled to machine code before execution; in Python, the byte code is interpreted. OK, good. Naive question now comming to mind: Why doesn't Python do the latter as well? /W -- http://mail.python.org/mailman/listinfo/python-list
Re: Glade + Python = No GUI
Kveldulv wrote: When interrupted, I get File gui.py, line 11, in module gtk.main() Ah, I see now. Thats just telling you that *you* interrupted the function/method/whateverthatis. When GUI coded manually, all works. Hence: Something in your (generated) code or XML file is corrupt or missing. Perhaps some sort of show() call or attribute. I really only have marginal experience with pygtk so I'm just stabbing at thin air. sorry :( /W -- http://mail.python.org/mailman/listinfo/python-list
Re: Glade + Python = No GUI
On Sep 2, 9:07 pm, Wildemar Wildenburger [EMAIL PROTECTED] wrote: Kveldulv wrote: When interrupted, I get File gui.py, line 11, in module gtk.main() Ah, I see now. Thats just telling you that *you* interrupted the function/method/whateverthatis. When GUI coded manually, all works. Hence: Something in your (generated) code or XML file is corrupt or missing. Perhaps some sort of show() call or attribute. I really only have marginal experience with pygtk so I'm just stabbing at thin air. sorry :( /W I sorted it out and you're right. I didn't found out why this thing didn't work since it's c/pasted straight from the book I'm learning from but this did the trick: class TwoButtonsGUI: def __init__(self): xml = gtk.glade.XML(buttons.glade) self.window = xml.get_widget(window1) self.window.show() etc Thanks for help! -- http://mail.python.org/mailman/listinfo/python-list
Re: Why is this loop heavy code so slow in Python? Possible Project Euler spoilers
On Sep 2, 7:51 am, [EMAIL PROTECTED] wrote: The resulting executable takes 0.24 seconds to run. I'm not expecting a scripting language to run faster than native code, but I was surprised at how much slower it was in this case. Any ideas as to what is causing python so much trouble in the above code? Below is some code and some timings that show that Python is spending at least 1/3 of its time computing the squares: a*a, b*b and c*c. So to explain why Python is so much slower than C, it should be enough to explain what's going on with these multiplications. Here's my attempt at an explanation: To compute a*a, Python has to do the following, all at run-time (1) Find the type of a. (2) Look up the corresponding multiplication method for this type. (3) (In the multiplication method): find the type of the right-hand side, in this case a again. (4) Having established that both arguments are ints, worry about whether the result is going to overflow (in which case a long needs to be returned). (5) Do the multiplication. (6) Allocate a new Python integer to hold the result, and return it. The C code only has to do step (5), and this boils down to a single machine instruction. Mark Code and timings: (Python 2.5.1/G4.) def test(): solutions = [0] * 1000 for a in xrange(1, 1000): for b in xrange(1, 1000 - a): for c in xrange(1, 1000 - a - b): if a*a + b*b == c*c: solutions[a+b+c] += 1 return solutions def test2(): solutions = [0] * 1000 squares = [x*x for x in xrange(1000)] for a in xrange(1, 1000): for b in xrange(1, 1000 - a): for c in xrange(1, 1000 - a - b): if squares[a] + squares[b] == squares[c]: solutions[a+b+c] += 1 return solutions from profile import run run(l = test(); l2 = test2()) 5 function calls in 299.984 CPU seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 10.0100.0100.0100.010 :0(setprofile) 10.0000.000 299.973 299.973 string:1(module) 10.0000.000 299.984 299.984 profile:0(l = test(); l2 = test2()) 00.000 0.000 profile:0(profiler) 1 182.262 182.262 182.262 182.262 test.py:1(test) 1 117.711 117.711 117.711 117.711 test.py:10(test2) -- http://mail.python.org/mailman/listinfo/python-list
how can I find out the process ids with a process name
Hi, I would like to find out all the process id with the process name 'emacs'. In the shell, i can do this: $ ps -ef |grep emacs root 20731 8690 0 12:37 pts/200:00:09 emacs-snapshot-gtk root 25649 25357 0 13:55 pts/900:00:05 emacs-snapshot-gtk rtp.c root 26319 23926 0 14:06 pts/700:00:04 emacs-snapshot-gtk stressTestVideo.py root 26985 1 0 14:15 ?00:00:01 /usr/bin/emacs-snapshot- gtk root 27472 21066 0 14:23 pts/500:00:00 grep emacs and I can see the process id is 20731, 25649, etc, etc. But now I would like to do the programmically in my python script. I know I can use ' os.system(cmd)' to execute the command 'ps -ef | grep emacs', but how can I pipe the output of my 'ps -ef | grep emacs' to my python script and then run a regression expression with it to get the process Ids? Thank you. -- http://mail.python.org/mailman/listinfo/python-list
Re: how can I find out the process ids with a process name
the easiest but slowest way: you can send output to a file ps -ef |grep emacs output_file and then read the file content (I believe there is a much better way) On 9/2/07, herman [EMAIL PROTECTED] wrote: Hi, I would like to find out all the process id with the process name 'emacs'. In the shell, i can do this: $ ps -ef |grep emacs root 20731 8690 0 12:37 pts/200:00:09 emacs-snapshot-gtk root 25649 25357 0 13:55 pts/900:00:05 emacs-snapshot-gtk rtp.c root 26319 23926 0 14:06 pts/700:00:04 emacs-snapshot-gtk stressTestVideo.py root 26985 1 0 14:15 ?00:00:01 /usr/bin/emacs-snapshot- gtk root 27472 21066 0 14:23 pts/500:00:00 grep emacs and I can see the process id is 20731, 25649, etc, etc. But now I would like to do the programmically in my python script. I know I can use ' os.system(cmd)' to execute the command 'ps -ef | grep emacs', but how can I pipe the output of my 'ps -ef | grep emacs' to my python script and then run a regression expression with it to get the process Ids? Thank you. -- http://mail.python.org/mailman/listinfo/python-list -- Furkan Kuru -- http://mail.python.org/mailman/listinfo/python-list
Re: Automation and scheduling of FrontPage publishing using Python
On Sep 1, 10:48 pm, Jerry [EMAIL PROTECTED] wrote: andrew, I would try looking into Windows automation with Python.http://www.google.com/search?q=windows+automation+pythonshould get you started. The winGuiAuto package may help you out as it is like have a human click and move throughout the interface. The only downside is that there is no recorder to help you build the script, so I would try to do as much in VBA as you can (does FrontPage even support VBA?) and then just write your python script to get through the program enough to execute the macro. Yes.. Front page can be run by VB macro but I really did not want to go down that road if it could be avoided. This looks very promising. I've installed the module and run a couple of the basic examples.. Very cool. -- http://mail.python.org/mailman/listinfo/python-list
Re: how can I find out the process ids with a process name
On Sep 2, 2007, at 12:26 PM, herman wrote: I would like to find out all the process id with the process name 'emacs'. In the shell, i can do this: $ ps -ef |grep emacs root 20731 8690 0 12:37 pts/200:00:09 emacs-snapshot-gtk root 25649 25357 0 13:55 pts/900:00:05 emacs-snapshot-gtk rtp.c root 26319 23926 0 14:06 pts/700:00:04 emacs-snapshot-gtk stressTestVideo.py root 26985 1 0 14:15 ?00:00:01 /usr/bin/emacs-snapshot- gtk root 27472 21066 0 14:23 pts/500:00:00 grep emacs and I can see the process id is 20731, 25649, etc, etc. But now I would like to do the programmically in my python script. I know I can use ' os.system(cmd)' to execute the command 'ps -ef | grep emacs', but how can I pipe the output of my 'ps -ef | grep emacs' to my python script and then run a regression expression with it to get the process Ids? Are you targeting Linux? If so, have a look at the /proc system. Each process has a directory, and the 'status' file in each process' directory tells many things, including process name (the line that ends with the process name, begins with 'Name'). Here's a quick bashy way to get pid + process names: cd /proc for i in ls [0-9]*/status do echo $i `grep '^Name' $i | cut -f2` | sed 's/\/status//g' done hth, Michael --- If we had asked people what they wanted they would have said 'a faster horse'. --Henry Ford -- http://mail.python.org/mailman/listinfo/python-list
howto reload Python module?
my Python module was changed in HDD (hardware disk drive), moreover, changed its location (but still present in sys.path). how can I reload a func myfunc from the module? (or howto reload whole module)? Thank you in advance, D. -- http://mail.python.org/mailman/listinfo/python-list
Re: howto reload Python module?
dmitrey schrieb: my Python module was changed in HDD (hardware disk drive), moreover, changed its location (but still present in sys.path). how can I reload a func myfunc from the module? (or howto reload whole module)? Thank you in advance, D. By using *drumroll* the reload function! diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Adding attributes stored in a list to a class dynamically.
On Sep 2, 11:46 am, [EMAIL PROTECTED] (Alex Martelli) wrote: If you want to pass the attributes list it's simpler to do that directly, avoiding *a and **k constructs. E.g.: def __init__(self, a, b, attrs): self.a = a self.b = b for attr in attrs: name, value = attr.split('=') setattr(self, name, value) Alex: Thanks for the example. I too had been wondering about this for a while. One question though, which I haven't been able to find the answer from scouring the internet. What is the difference between calling __setattr__ and setattr or __getattr__ and getattr, for that matter? From my example that follows, it doesn't seem to make a difference? thanks -- brian class Person(object): def __init__(self): pass def newAttribute(self,name,value=None): setattr(self,name, value) def newAttribute2(self,name,value=None): self.__setattr__(name, value) def dump(self): for self.y in self.__dict__.keys(): yield self.y + = + getattr(self,self.y) p1 = Person() p1.newAttribute('fname','Brian') p1.newAttribute('lname','Munroe') p1.newAttribute2(mi,E) for x in p1.dump(): print x -- http://mail.python.org/mailman/listinfo/python-list
Weird gcc errors while installing MySQL-python module
Hi guys, I´m experiencing weird error messages while installing MySQL-python with easy_install... I have no idea where the errors come from. Read the whole output at http://pastebin.com/m3859cf40 It´s really a lot... Someone got ideas? Greets Jonas -- http://mail.python.org/mailman/listinfo/python-list
Re: Why is this loop heavy code so slow in Python? Possible Project Euler spoilers
On Sun, 02 Sep 2007 21:00:45 +0200, Wildemar Wildenburger wrote: Martin v. Löwis wrote: (2) it is a interpretation language Not quite. It's compiled to byte-code - just like Java (would you call Java an 'interpreted language' ?) Python is not implemented like Java. In Java (at least in HotSpot), the byte code is further compiled to machine code before execution; in Python, the byte code is interpreted. OK, good. Naive question now comming to mind: Why doesn't Python do the latter as well? /W There is no single version of Java, and the reference interpretation runs on a virtual machine just like Python. Today there are virtual machine implementations of Java, native compilers, and Just In Time compilers for Java, including HotSpot mentioned by Martin, but Java the language was originally defined to run on a VM. See, for example, here: http://schmidt.devlib.org/java/compilers.html There are costs to native compilation, the biggest one of course being the initial investment in time and effort in creating the native compiler. Sun and other commercial companies have invested a lot of money in Java, and I don't think the money invested in Python has come even close. Consequently, any work into JIT compilation for Java has been done by volunteers. Nevertheless, we have Psyco, which is a JIT compiler of sorts; work also continues on PyPy (Python implemented in Python) which, it is hoped, will lead to faster Python implementations. Part of the reason that native compilation for Python is hard is that Python's dynamic object model makes it very difficult to apply the same sorts of compiler optimizations that C and Java allow. Comparatively little of the work done by Python can be safely pushed from run time to compile time, so it is unlikely that the average Python application will ever run as fast as the equivalent C code -- although that ignores the question of what the equivalent C code could possibly mean. (If the C code includes all the dynamic high-level features of Python, it too would surely run as slowly as Python, and if it didn't, it can hardly be said to be equivalent.) Nevertheless, by using something like Psyco parts of your Python code can run at virtually the same speed as C. A big question mark in my mind is Lisp, which according to aficionados is just as dynamic as Python, but has native compilers that generate code running as fast as highly optimized C. I'm not qualified to judge whether the lessons learnt from Lisp can be applied to Python, but in any case Lisp is an old, old language -- only Fortran is older. The amount of development effort and money put into Lisp dwarfs that put into Python by possibly a hundred or more. So... if you'd like to see Python run as fast as C or Lisp, and you have a few tens of millions of dollars spare to invest in development, I think the Python Software Foundation would love to hear from you. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: Why is this loop heavy code so slow in Python? Possible Project Euler spoilers
Wildemar Wildenburger schrieb: Martin v. Löwis wrote: (2) it is a interpretation language Not quite. It's compiled to byte-code - just like Java (would you call Java an 'interpreted language' ?) Python is not implemented like Java. In Java (at least in HotSpot), the byte code is further compiled to machine code before execution; in Python, the byte code is interpreted. OK, good. Naive question now comming to mind: Why doesn't Python do the latter as well? because of the dynamic nature of it. Java is statically typed, so the JIT can heavily optimize. OTH psyco IS a JIT-compiler to optimize certain calculations which are mostly of a numerical nature. But this can't be done to the extend it is possible in java. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Adding attributes stored in a list to a class dynamically.
On Sun, 02 Sep 2007 21:41:43 +, Brian Munroe wrote: One question though, which I haven't been able to find the answer from scouring the internet. What is the difference between calling __setattr__ and setattr or __getattr__ and getattr, for that matter? Have you read the following? # setattr, getattr, delattr: http://www.python.org/doc/lib/built-in-funcs.html # __setattr__ etc. http://www.python.org/doc/ref/attribute-access.html If there is anything unclear about the descriptions, please ask. In a nutshell, like all double-underscore methods, __setattr__ are for overriding behaviour in your own classes. With very few exceptions, you shouldn't need to directly call double-underscore methods (although you often may _write_ double-underscore methods). -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: howto reload Python module?
On Sun, 02 Sep 2007 13:28:26 -0700, dmitrey wrote: my Python module was changed in HDD (hardware disk drive), moreover, changed its location (but still present in sys.path). how can I reload a func myfunc from the module? (or howto reload whole module)? Thank you in advance, D. You're moving the LOCATION of modules while they are running??? WHY??? Nevertheless, and much to my surprise, a quick test suggests that so long as the new location is in sys.path, reload() continues to do what it is supposed to do. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: how can I find out the process ids with a process name
On Sun, 02 Sep 2007 19:26:27 +, herman wrote: But now I would like to do the programmically in my python script. I know I can use ' os.system(cmd)' to execute the command 'ps -ef | grep emacs', but how can I pipe the output of my 'ps -ef | grep emacs' to my python script and then run a regression expression with it to get the process Ids? Use popen. f = os.popen('ps ax | grep -i PYTHON') print f.read() 1952 ?Ssl0:01 /usr/bin/python -E /usr/sbin/setroubleshootd 2117 ?S 0:00 python ./hpssd.py 2376 ?SN 3:19 /usr/bin/python /usr/sbin/yum-updatesd 18087 pts/4S+ 0:00 python 18115 pts/4S+ 0:00 sh -c ps ax | grep -i PYTHON 18117 pts/4R+ 0:00 grep -i python There is also a module popen2 which does similar but more advanced things. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: Looking for Delaunay triangulation module...
Grant Edwards wrote: Can anybody point me to a Delaunay triangulation module (for Win32)? I'm currently using http://flub.stuffwillmade.org/delny/ under Linux, but I have been unable to find a build for Windows. I don't have the tools (or skills) to build libqhull and Pythion extensions on Win32). I've also found the delaunay module in scipy's sandbox. I could never get that module to work under Linux, and I can't build it for Windows anyway. I'm working on it today. I'm going to break it out into a separate package. If you can remember what problems you had, I'd like to fix them. I'm clearing up a number of (really dumb) memory leaks. -- 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 -- http://mail.python.org/mailman/listinfo/python-list
Re: Glade + Python = No GUI
Note to myself and python noobs like me: Don't forget to set Visible to yes on main window in Glade :) -- http://mail.python.org/mailman/listinfo/python-list
Will Python 3.0 remove the global interpreter lock (GIL)
I'm afraid that the GIL is killing the usefullness of python for some types of applications now where 4,8 oder 64 threads on a chip are here or comming soon. What is the status about that for the future of python? I know that at the moment allmost nobody in the scripting world has solved this problem, but it bites and it bites hard. Only groovy as a Java Plugin has support but i never tried it. Writing an interpreter that does MT this seems to be extremely difficult to do it right, with lots of advanced stuff like CAS and lock free programming. Even Smalltalk and Common Lisp didn't get it until know (with the exception of certain experiments). -- http://mail.python.org/mailman/listinfo/python-list
Re: Why is this loop heavy code so slow in Python? Possible Project Euler spoilers
On 9/2/07, Diez B. Roggisch [EMAIL PROTECTED] wrote: Wildemar Wildenburger schrieb: Martin v. Löwis wrote: (2) it is a interpretation language Not quite. It's compiled to byte-code - just like Java (would you call Java an 'interpreted language' ?) Python is not implemented like Java. In Java (at least in HotSpot), the byte code is further compiled to machine code before execution; in Python, the byte code is interpreted. OK, good. Naive question now comming to mind: Why doesn't Python do the latter as well? because of the dynamic nature of it. Java is statically typed, so the JIT can heavily optimize. OTH psyco IS a JIT-compiler to optimize certain calculations which are mostly of a numerical nature. But this can't be done to the extend it is possible in java. Original code: 3 min, 9 seconds Original code with psyco: 30.28 seconds Original code, compiled with Pyrex: 1min 39 seconds (moves the for loops into C) Same, with a,b,c declared with cdef int: 20 seconds (uses c pow() instead of going through Python). Same, with the for..xrange loops rewritten to use C integer loops: 13 seconds (saves xrange use, but since the python loop was already gone, not too much savings). With a small amount of work, you should be able to implement the C algorithm in Pyrex (or even just use the C algorithm, in a wrapper that converts the return value to an int) and get the same speed as the C version + a constant marshalling factor. Adding pysco took all of 20 seconds (half that because I needed to move the module scope code into a function), and re-writing with pyrex took a minute or two. So, as a demonstration of numeric optmization, both of them can give you quite good rewards with minimal effort. -- http://mail.python.org/mailman/listinfo/python-list
Re: Will Python 3.0 remove the global interpreter lock (GIL)
On 9/2/07, llothar [EMAIL PROTECTED] wrote: I'm afraid that the GIL is killing the usefullness of python for some types of applications now where 4,8 oder 64 threads on a chip are here or comming soon. What is the status about that for the future of python? I know that at the moment allmost nobody in the scripting world has solved this problem, but it bites and it bites hard. Only groovy as a Java Plugin has support but i never tried it. Writing an interpreter that does MT this seems to be extremely difficult to do it right, with lots of advanced stuff like CAS and lock free programming. Even Smalltalk and Common Lisp didn't get it until know (with the exception of certain experiments). No. http://www.artima.com/weblogs/viewpost.jsp?thread=211430 -- http://www.advogato.org/person/eopadoan/ Bookmarks: http://del.icio.us/edcrypt -- http://mail.python.org/mailman/listinfo/python-list
Re: Will Python 3.0 remove the global interpreter lock (GIL)
No. http://www.artima.com/weblogs/viewpost.jsp?thread=211430 Ops, I meant: http://www.artima.com/forums/threaded.jsp?forum=106thread=211200 -- http://www.advogato.org/person/eopadoan/ Bookmarks: http://del.icio.us/edcrypt -- http://mail.python.org/mailman/listinfo/python-list
Soemthing wrong w/ urllib module or something.
Error Message in cmd: Traceback (most recent call last): File wniamp_lastest5_playlist.py, line 25, in module response = urllib2.urlopen(request) File C:\Python25\lib\urllib2.py, line 121, in urlopen return _opener.open(url, data) File C:\Python25\lib\urllib2.py, line 374, in open response = self._open(req, data) File C:\Python25\lib\urllib2.py, line 392, in _open '_open', req) File C:\Python25\lib\urllib2.py, line 353, in _call_chain result = func(*args) File C:\Python25\lib\urllib2.py, line 1100, in http_open return self.do_open(httplib.HTTPConnection, req) File C:\Python25\lib\urllib2.py, line 1075, in do_open raise URLError(err) urllib2.URLError: urlopen error (10053, 'Software caused connection abort') My script that works almost perfectly cept when trying to post: import urllib,urllib2 from winamp import * import winamp domain = http://DOMAINHERE/save_play.php; w = winamp.winamp() w.dumpList() List = getTrackList(rc:\Program Files\Winamp\winamp.m3u) fList = fixTrackList(List) x=0 playlist = [] while x 6: if x (len(fList)-1) or x == (len(fList)-1): if fList[x] != : e = %d.%s % (x,fList[x]) playlist.append(e) else: pass else: pass x = x + 1 ME = |.join(playlist) send = {'playlist':ME} data = urllib.urlencode(send) request = urllib2.Request(domain,data) response = urllib2.urlopen(request) PL = response.read() if PL == updated: print Updated Successful. raw_input(Press anything to close) For some reason its not acting right when trying to run. I get that error message and I never seen anything like it. -- http://mail.python.org/mailman/listinfo/python-list
Re: Getting subprocesses to be hidden on Windows
geoffbache wrote: As part of my efforts to write a test tool that copes with GUIs This is dead easy on UNIX with virtual displays like Xvfb. Can someone shed any light if it's possible on Windows Configure the virtual display first: http://en.wikipedia.org/wiki/Virtual_desktop Alternatively, run the process in a separate gui. Terminal Server client is one way to do that. [david] -- http://mail.python.org/mailman/listinfo/python-list
Re: Will Python 3.0 remove the global interpreter lock (GIL)
On 3 Sep., 07:38, Eduardo O. Padoan [EMAIL PROTECTED] wrote: No.http://www.artima.com/weblogs/viewpost.jsp?thread=211430 Ops, I meant:http://www.artima.com/forums/threaded.jsp?forum=106thread=211200 Thanks. I whish there would be a project for rewritting the C interpreter to make it better and more useable for threading use. But the CPU infrastructure is also not perfect enough so maybe it's good to wait with this a few more years until Intel and AMD know what they are doing. -- http://mail.python.org/mailman/listinfo/python-list
Re: reload(sys)
Sönmez Kartal wrote: I was using the XMLBuilder(xmlbuilder.py). I'm writing XML files as f.write(str(xml)). At execution of that line, it gives error with description, configure your default encoding... [and later] I get this when it happens: Decoding Error: You must configure default encoding which comes from in the code excerpt in xmlbuilder.py (http://rafb.net/p/9rURi822.html) Can you show the code where you populate the XMLBuilder? I'm guessing you're doing something like:: import xmlbuilder builder = xmlbuilder.XMLBuilder() builder.foo = dict(bar='® and ™') str(builder) That breaks because the string '® and ™' is not properly encoded. Have you declared an encoding in your source file? PEP 263 shows you how: http://www.python.org/dev/peps/pep-0263/ Note that with Python 2.5 the code above gives a SyntaxError without a proper encoding. You should also probably be prefixing your string literals containing weird characters with u to make them unicode. Doing both of these in the code above made it work for me. STeVe -- http://mail.python.org/mailman/listinfo/python-list
Crunchy release 0.9.8
Crunchy version 0.9.8 has been released. Crunchy is an application that transforms static html-based Python tutorials into interactive sessions within your browser (Firefox; other browsers *may* not fully support Crunchy). Crunchy is available from http://code.google.com/p/crunchy Since the last public release, the following changes have been introduced: * Important changes to security model. + 6 security levels. * New interpreter types * New interpreter options. * New option (used by default) to view tutorials that have no Crunchy- specific markup. * More documentation. * Friendlier tracebacks (for Python beginners) - translatable in languages other than English. * Automatic updating of sys.path so that tutorials can make use of Python's import statement. * More configuration options. * New math_graphics module. * New logo. * New look. * French translation of Crunchy/Python messages (not documentation) almost complete. + many more. Bug reports, comments and suggestions are always welcome. André -- http://mail.python.org/mailman/listinfo/python-list
Re: Adding attributes stored in a list to a class dynamically.
On Sep 2, 3:33 pm, Steven D'Aprano [EMAIL PROTECTED] cybersource.com.au wrote: In a nutshell, like all double-underscore methods, __setattr__ are for overriding behaviour in your own classes. With very few exceptions, you shouldn't need to directly call double-underscore methods (although you often may _write_ double-underscore methods). I think I understand. You are saying that if I wanted to override the normal behavior when doing something like p1.firstName = Brian then I'd override __setattr__()? But if I am doing something like creating dynamic attributes, the more 'correct' way is to use setattr? Even though they both appear to do the same thing, the more Pythonic way is to never directly call magic methods (if you can help it)? thanks -- brian -- http://mail.python.org/mailman/listinfo/python-list
Re: Why is this loop heavy code so slow in Python? Possible Project Euler spoilers
On 2007-09-02, Martin v. Löwis [EMAIL PROTECTED] wrote: (2) it is a interpretation language Not quite. It's compiled to byte-code - just like Java (would you call Java an 'interpreted language' ?) Python is not implemented like Java. In Java (at least in HotSpot), the byte code is further compiled to machine code before execution; in Python, the byte code is interpreted. Whether this makes Python an interpreter or a compiler, I don't know. I'd call it an integrated compiler and virtual machine--a classic combination. -- Neil Cerutti -- http://mail.python.org/mailman/listinfo/python-list
Re: [python-win32] How can I get the parentWindow.document object?
Hi! ie = win32com.client.Dispatch(InternetExplorer.Application) doc=ie.Document.parentWindow.document Use bridge variable : window=ie.Document.parentWindow And work with : print window.Document.body.name -- @-salutations Michel Claveau -- http://mail.python.org/mailman/listinfo/python-list
Re: Why is this loop heavy code so slow in Python? Possible Project Euler spoilers
On 2007-09-02, Steven D'Aprano [EMAIL PROTECTED] wrote: A big question mark in my mind is Lisp, which according to aficionados is just as dynamic as Python, but has native compilers that generate code running as fast as highly optimized C. I'm not qualified to judge whether the lessons learnt from Lisp can be applied to Python, but in any case Lisp is an old, old language -- only Fortran is older. The amount of development effort and money put into Lisp dwarfs that put into Python by possibly a hundred or more. Lisp, as far as I know, requires type declarations, discipline, deep knowledge of Lisp, and more than passing knowledge of your Lisp implementation in order to generate code that's competitive with C. On the other hand, Lisp afficionados don't have a problem meeting those requirements. ;) So... if you'd like to see Python run as fast as C or Lisp, and you have a few tens of millions of dollars spare to invest in development, I think the Python Software Foundation would love to hear from you. Hmmm. I have four dollars... almost five... -- Neil Cerutti -- http://mail.python.org/mailman/listinfo/python-list
Re: [python-win32] How can I get the parentWindow.document object?
Re! Sorry! The good exemple is : ie = win32com.client.Dispatch(InternetExplorer.Application) window=ie.Document.parentWindow print window.name another : window.alert(Aalleerrtt) -- @-salutations Michel Claveau -- http://mail.python.org/mailman/listinfo/python-list
Re: Will Python 3.0 remove the global interpreter lock (GIL)
On Sep 2, 11:16 pm, llothar [EMAIL PROTECTED] wrote: On 3 Sep., 07:38, Eduardo O. Padoan [EMAIL PROTECTED] wrote: No.http://www.artima.com/weblogs/viewpost.jsp?thread=211430 Ops, I meant:http://www.artima.com/forums/threaded.jsp?forum=106thread=211200 Thanks. I whish there would be a project for rewritting the C interpreter to make it better and more useable for threading use. But the CPU infrastructure is also not perfect enough so maybe it's good to wait with this a few more years until Intel and AMD know what they are doing. I read somewhere that PYPY won't have the interpreter lock (I may be wrong though). Check it out: http://codespeak.net/pypy -- http://mail.python.org/mailman/listinfo/python-list
PYTHONPATH not working on Windows XP (?)
Hi, I'm trying to add a personal folder to the path used by python in searching for packages and modules. This folder, C:\docs\utils , has some packages not yet ready for site-packages. First, I tried sys.path.append(C:\docs\utils) BUT this only lasts for the current python session. Then, I read about PYTHONPATH and went to Control Panel - System - Advanced - Enviromental Variables, and created a new variable (PYTHONPATH) containing the folder. However, sys.path does not detects it.. keeps printing the same old files: import sys; import pprint; pprint.pprint(sys.path) ['C:\\Program Files\\AutoHotkey', 'C:\\Program Files\\Python25\\Lib\\idlelib', 'C:\\WINDOWS\\system32\\python25.zip', 'C:\\Program Files\\Python25\\DLLs', 'C:\\Program Files\\Python25\\lib', 'C:\\Program Files\\Python25\\lib\\plat-win', 'C:\\Program Files\\Python25\\lib\\lib-tk', 'C:\\Program Files\\Python25', 'C:\\Program Files\\Python25\\lib\\site-packages'] (By the way, how did that AutoHotkey folder got there? Can I remove it from sys.path?) After my second failure, I went to the registry HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.5\PythonPath and added my folder there. Still nothing on sys.path , and my imports fail. Any suggestions for adding my path to sys.path permanently? I'm running out of ideas Thanks, Sergio -- http://mail.python.org/mailman/listinfo/python-list
[issue1071] unicode.translate() doesn't error out on invalid translation table
Georg Brandl added the comment: Marc-Andre Lemburg schrieb: Marc-Andre Lemburg added the comment: Nice idea, but why don't you use a dictionary iterator (PyDict_Next()) for the fixup ? I thought that is unsafe to use when the dictionary is mutated while iterating. __ Tracker [EMAIL PROTECTED] http://bugs.python.org/issue1071 __ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue1084] ''.find() gives wrong result in Python built with ICC
Martin v. Löwis added the comment: It definitely sounds like a compiler bug. Unless you can provide further details to the specific error in the C code of Python, it's likely that we can do little about it. If you want to analyze this further, here is a number of things you can try: - compile Python at various optimization levels. A compiler bug often manifests itself only at a specific set of optimization flags. - try tracing this invocation of .find() in a debugger. Doing so at a lower optimization level is easier, since the compiler may have inlined the various functions that form .find() under optimization. - if the debugger does not allow to pinpoint the erroneous function, add printf statements. Most of the code to study is in Objects/stringobject.c and Objects/stringlib/find.h. -- nosy: +loewis __ Tracker [EMAIL PROTECTED] http://bugs.python.org/issue1084 __ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue1085] OS X 10.5.x Build Problems
Martin v. Löwis added the comment: This is a duplicate of #1078. -- nosy: +loewis resolution: - duplicate status: open - closed superseder: - cachersrc.py using tuple unpacking args __ Tracker [EMAIL PROTECTED] http://bugs.python.org/issue1085 __ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue1084] ''.find() gives wrong result in Python built with ICC
Simon Anders added the comment: Martin, you are right: is is related to compiler optimization. I have boiled it down to a call of stringlib_find (defined in Python-2.5.1/Objects/stringlib/find.h) and this runs fine with 'icc -O2' but incorrectly for 'icc -O3'. (The test code is attached.) So, it seems that the lesson is simply once again: Do not use '-O3' with Intel's C compiler. (At least, for me, it is not the first time that this caused trouble.) On the other hand, Python's ./configure script is quite clear in its preference of GCC, anyway: It more or less ignores with option '--without-gcc' and uses the content of the CC environment variable only very occasionally. __ Tracker [EMAIL PROTECTED] http://bugs.python.org/issue1084 __#define STRINGLIB_CHAR char #define STRINGLIB_CMP memcmp #define STRINGLIB_LEN PyString_GET_SIZE #define STRINGLIB_NEW PyString_FromStringAndSize #define STRINGLIB_STR PyString_AS_STRING #define STRINGLIB_EMPTY nullstring #include /usr/site/hc-2.6/python/gnu/2.5.1/include/python2.5/Python.h #include ../Python-2.5.1/Objects/stringlib/fastsearch.h #include ../Python-2.5.1/Objects/stringlib/find.h int main () { STRINGLIB_CHAR* str = foo2/**bar**/; Py_ssize_t str_len = strlen (str); STRINGLIB_CHAR* sub = /**bar**/; Py_ssize_t sub_len = strlen (sub); Py_ssize_t offset = 0; Py_ssize_t res; res = stringlib_find(str, str_len, sub, sub_len, offset); printf (%d\n, res); return 0; } ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue1084] ''.find() gives wrong result in Python built with ICC
Martin v. Löwis added the comment: If you are curious, we could now try to find out what precisely goes wrong. The procedure would be this * after each step, check whether the problem still occurs a) resolve the includes manually, then strip everything that isn't needed. This could start with fastsearch.h and find.h; then remove everything that refers to Python.h (i.e. replace Py_ssize_t with ssize_t, Py_LOCAL_INLINE with static inline, and so on), then remove Python.h b) try simplifying the code, e.g. replace str_len and sub_len with their (constant) values, drop the sub_len == 0 block, and so on. c) when further simplification is not possible (while keeping the actual error), start looking at the assembler code. Alternatively, sent this or some further-simplified version to Intel (assuming they have some kind of bug-reporting channel for icc). With my compiler-vendor's hat on, I'd like to get a test case for bad code generation that comes as a single file, with no includes; for gcc, the request is to submit preprocessor output. Assuming this is too much effort, I'll close this as won't fix - third party. -- resolution: - wont fix status: open - closed versions: +3rd party -Python 2.5 __ Tracker [EMAIL PROTECTED] http://bugs.python.org/issue1084 __ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue1071] unicode.translate() doesn't error out on invalid translation table
Marc-Andre Lemburg added the comment: Ah, I hadn't noticed that you're actually manipulating the input dictionary. You should create a copy and fix that instead of changing the dict that the user passed in to the function. You can then use PyDict_Next() for fast iteration over the original dictionary. __ Tracker [EMAIL PROTECTED] http://bugs.python.org/issue1071 __ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue1084] ''.find() gives wrong result in Python built with ICC
Simon Anders added the comment: Martin: I've boiled down the test case a bit more and removed all Python-specific types and macros, so that it can now be compiled stand-alone. (Updated test case 'findtest.c' attached.) I didn't feel like diving into the code much deeper, and so I have sent it to Intel Premier Support as Issue #448807. Let's see if they bother to investigate it further. __ Tracker [EMAIL PROTECTED] http://bugs.python.org/issue1084 __/* Testcase for problem with 'icc -O3': The function 'fastsearch' is taken from the source code of Python 2.5 and looks for the substring 'p' (of length 'm') within the string 's' (of length 'n'). If 'mode' is 'FAST_COUNT' the number of occurences of p in s is returned, and for 'FAST_SEARCH', the position of the first occurence. For the specific values used in main() below, the function returns correctly '4', if compiled with at most optimization '-O2', but '-1' for optimization level '-O3'. I have just changed the Python-specific types to standard ones, otherwise fastsearc() is as defined in file Objects/stringlib/fastsearch.h of the Python 2.5.1 source code. It has been written by Fredrik Lundh and is described in his blog here: http://effbot.org/zone/stringlib.htm Simon Anders, [EMAIL PROTECTED], 2007-09-02 */ #include string.h #include stdio.h #define FAST_COUNT 0 #define FAST_SEARCH 1 inline int fastsearch(const char* s, int n, const char* p, int m, int mode) { long mask; int skip, count = 0; int i, j, mlast, w; w = n - m; if (w 0) return -1; /* look for special cases */ if (m = 1) { if (m = 0) return -1; /* use special case for 1-character strings */ if (mode == FAST_COUNT) { for (i = 0; i n; i++) if (s[i] == p[0]) count++; return count; } else { for (i = 0; i n; i++) if (s[i] == p[0]) return i; } return -1; } mlast = m - 1; /* create compressed boyer-moore delta 1 table */ skip = mlast - 1; /* process pattern[:-1] */ for (mask = i = 0; i mlast; i++) { mask |= (1 (p[i] 0x1F)); if (p[i] == p[mlast]) skip = mlast - i - 1; } /* process pattern[-1] outside the loop */ mask |= (1 (p[mlast] 0x1F)); for (i = 0; i = w; i++) { /* note: using mlast in the skip path slows things down on x86 */ if (s[i+m-1] == p[m-1]) { /* candidate match */ for (j = 0; j mlast; j++) if (s[i+j] != p[j]) break; if (j == mlast) { /* got a match! */ if (mode != FAST_COUNT) return i; count++; i = i + mlast; continue; } /* miss: check if next character is part of pattern */ if (!(mask (1 (s[i+m] 0x1F i = i + m; else i = i + skip; } else { /* skip: check if next character is part of pattern */ if (!(mask (1 (s[i+m] 0x1F i = i + m; } } if (mode != FAST_COUNT) return -1; return count; } int main () { char* str = foo2/**bar**/; int str_len = strlen (str); char* sub = /**bar**/; int sub_len = strlen (sub); int offset = 0; int res; res = fastsearch (str, str_len, sub, sub_len, FAST_SEARCH); printf (%d\n, res); return 0; } ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue1086] test_email failed
New submission from xyb: test test_email failed -- Traceback (most recent call last): File /home/xyb/Python-3.0a1/Lib/email/test/test_email.py, line 1445, in test_same_boundary_inner_outer msg = self._msgobj('msg_15.txt') File /home/xyb/Python-3.0a1/Lib/email/test/test_email.py, line 67, in _msgobj return email.message_from_file(fp) File /home/xyb/Python-3.0a1/Lib/email/__init__.py, line 46, in message_from_file return Parser(*args, **kws).parse(fp) File /home/xyb/Python-3.0a1/Lib/email/parser.py, line 68, in parse data = fp.read(8192) File /home/xyb/Python-3.0a1/Lib/io.py, line 1231, in read readahead, pending = self._read_chunk() File /home/xyb/Python-3.0a1/Lib/io.py, line 1127, in _read_chunk pending = self._decoder.decode(readahead, not readahead) File /home/xyb/Python-3.0a1/Lib/codecs.py, line 291, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) UnicodeDecodeError: 'utf8' codec can't decode byte 0xbe in position 86: unexpected code byte -- messages: 55583 nosy: xyb severity: normal status: open title: test_email failed versions: Python 3.0 __ Tracker [EMAIL PROTECTED] http://bugs.python.org/issue1086 __ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue1086] test_email failed
Peter van Kampen added the comment: Attached is msg_15.txt encoded in utf-8. f = codecs.open('Lib/email/test/data/msg_15.txt', 'r', encoding='iso-8859-1') s = f.read() f.close() f = open('Lib/email/test/data/msg_15.txt','w') f.write(s) f.close() $ ./python Lib/test/regrtest.py test_email test_email 1 test OK. -- nosy: +pterk __ Tracker [EMAIL PROTECTED] http://bugs.python.org/issue1086 __Return-Path: [EMAIL PROTECTED] Received: from fepD.post.tele.dk (195.41.46.149) by mail.groupcare.dk (LSMTP for Windows NT v1.1b) with SMTP id [EMAIL PROTECTED]; Mon, 30 Apr 2001 12:17:50 +0200 User-Agent: Microsoft-Outlook-Express-Macintosh-Edition/5.02.2106 Subject: XX From: [EMAIL PROTECTED] To: XX Message-ID: Mime-version: 1.0 Content-type: multipart/mixed; boundary=MS_Mac_OE_3071477847_720252_MIME_Part Denne meddelelse er i MIME-format. Da dit postl¾sningsprogram ikke forstÂr dette format, kan del af eller hele meddelelsen v¾re ul¾selig. --MS_Mac_OE_3071477847_720252_MIME_Part Content-type: multipart/alternative; boundary=MS_Mac_OE_3071477847_720252_MIME_Part --MS_Mac_OE_3071477847_720252_MIME_Part Content-type: text/plain; charset=ISO-8859-1 Content-transfer-encoding: quoted-printable Some removed test. --MS_Mac_OE_3071477847_720252_MIME_Part Content-type: text/html; charset=ISO-8859-1 Content-transfer-encoding: quoted-printable HTML HEAD TITLESome removed HTML/TITLE /HEAD BODY Some removed text. /BODY /HTML --MS_Mac_OE_3071477847_720252_MIME_Part-- --MS_Mac_OE_3071477847_720252_MIME_Part Content-type: image/gif; name=xx.gif; x-mac-creator=6F676C65; x-mac-type=47494666 Content-disposition: attachment Content-transfer-encoding: base64 Some removed base64 encoded chars. --MS_Mac_OE_3071477847_720252_MIME_Part-- ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue1673409] datetime module missing some important methods
Jon Ribbens added the comment: Almost everything you just said about time_t is wrong. time_t is signed, and always has been (otherwise the 'end of time' for 32-bit time_t would be 2106, not 2038). Also, time_t does not end at 2038 because nothing says it must be 32 bits. Also, Python has 'long integers' which do not overflow. Also, I don't understand what you mean about use cases. The use case is dealing with anything which expects standard Unix time_t, for example the Python standard library. The use case I have personally is the program I was working on when I encountered the problem described in this bug report. Also I think symmetry is a darn good argument. Why does fromtimestamp exist if, as you claim, nobody uses time_t? _ Tracker [EMAIL PROTECTED] http://bugs.python.org/issue1673409 _ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue1673409] datetime module missing some important methods
Skip Montanaro added the comment: Jon Almost everything you just said about time_t is wrong. time_t is Jon signed, and always has been (otherwise the 'end of time' for 32-bit Jon time_t would be 2106, not 2038). Also, time_t does not end at 2038 Jon because nothing says it must be 32 bits. Also, Python has 'long Jon integers' which do not overflow. My apologies about goofing up on the signedness of time_t. What are you going to do with a long integer that you can't do with a datetime object? You clearly can't pass it directly to any Unix library functions which expect time_t. Converting it can overflow. Jon Also, I don't understand what you mean about use cases. The use Jon case is dealing with anything which expects standard Unix time_t, Jon for example the Python standard library. The use case I have Jon personally is the program I was working on when I encountered the Jon problem described in this bug report. Also I think symmetry is a Jon darn good argument. Why does fromtimestamp exist if, as you claim, Jon nobody uses time_t? What should datetime.datetime(, 1, 1).totimestamp() return? How would you pass it to something which accepts a time_t? The fromtimestamp functions work simply because the range of time_t is a proper subset of the range of Python's datetime objects. Symmetry gets you little. In situations where you need Unix timestamps and you know your datetime objects are within the bounds representable by time_t, you can define a convenience function: def totimestamp(dt): return time.mktime(dt.timetuple()) + dt.microsecond/1e6 This will, of course, fail if the year is too big or too small (and will fail in platform-dependent ways if the underlying platform's range of representable dates has different bounds than Unix does). Doing it without resorting to calling time.mktime is also nontrivial. Under the covers the datetime module currently uses platform functions to get time information anyway. It doesn't do a lot of low-level time arithmethic itself. Implementing fromtimestamp would require a fair amount of effort unless you were willing to punt and just raise OverflowError for dates outside the system's range. Skip _ Tracker [EMAIL PROTECTED] http://bugs.python.org/issue1673409 _ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue1078] cachersrc.py using tuple unpacking args
Changes by Georg Brandl: -- assignee: - collinwinter nosy: +collinwinter __ Tracker [EMAIL PROTECTED] http://bugs.python.org/issue1078 __ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com