Re: sockets -- basic udp client
On Feb 15, 6:48 pm, Gabriel Genellina [EMAIL PROTECTED] wrote: En Fri, 15 Feb 2008 20:24:19 -0200, 7stud [EMAIL PROTECTED] escribió: My question pertains to this example: #!/usr/bin/env python import socket, sys, time host = sys.argv[1] textport = sys.argv[2] s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: port = int(textport) except ValueError: # That didn't work. Look it up instread. port = socket.getservbyname(textport, 'udp') s.connect((host, port)) print Enter data to transmit: data = sys.stdin.readline().strip() s.sendall(data) s.shutdown(1) print Looking for replies; press Ctrl-C or Ctrl-Break to stop. while 1: buf = s.recv(2048) if not len(buf): break print Received: %s % buf As far as I can tell, the if statement: if not len(buf): break does nothing. Either recv() is going to read some data or it's going to block. My understanding is that udp sockets do not have a connection, so the server can't close the connection--hich would cause a blank string to be sent to the client. So, as far as I can tell, the only way that code would make sense is if the server were programmed to send a blank string to the client after it sent data to the client. Is that correct? That example is plain wrong; looks like some TCP code but with SOCK_STREAM blindy replaced with SOCK_DGRAM. connect, sendall and recv are not used for UDP; sendto and recvfrom are used instead. There are some examples in the Demo python directory. -- Gabriel Genellina On Feb 15, 6:48 pm, Gabriel Genellina [EMAIL PROTECTED] wrote: En Fri, 15 Feb 2008 20:24:19 -0200, 7stud [EMAIL PROTECTED] escribió: My question pertains to this example: #!/usr/bin/env python import socket, sys, time host = sys.argv[1] textport = sys.argv[2] s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: port = int(textport) except ValueError: # That didn't work. Look it up instread. port = socket.getservbyname(textport, 'udp') s.connect((host, port)) print Enter data to transmit: data = sys.stdin.readline().strip() s.sendall(data) s.shutdown(1) print Looking for replies; press Ctrl-C or Ctrl-Break to stop. while 1: buf = s.recv(2048) if not len(buf): break print Received: %s % buf As far as I can tell, the if statement: if not len(buf): break does nothing. Either recv() is going to read some data or it's going to block. My understanding is that udp sockets do not have a connection, so the server can't close the connection--which would cause a blank string to be sent to the client. So, as far as I can tell, the only way that code would make sense is if the server were programmed to send a blank string to the client after it sent data to the client. Is that correct? That example is plain wrong; looks like some TCP code but with SOCK_STREAM blindy replaced with SOCK_DGRAM. connect, sendall and recv are not used for UDP; sendto and recvfrom are used instead. There are some examples in the Demo python directory. Yes, I agree it's a poor example--it's from 'Foundations of Python Network Programming'--but it does 'work'. It also doesn't appear to be a tcp client that was converted too directly into a udp client because the previously presented tcp examples are different. Here is the example above converted to a more straightforward udp client that isolates the part I am asking about: import socket, sys host = 'localhost' #sys.argv[1] port = 3300 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) data = 'hello world' num_sent = 0 while num_sent len(data): num_sent += s.sendto(data, (host, port)) print Looking for replies; press Ctrl-C or Ctrl-Break to stop. while 1: buf = s.recv(2048) #Will the following if statement do anything? if not len(buf): break print Received from server: %s % buf Another question I have pertains to the docs here: getservbyname(servicename[, protocolname]) Translate an Internet service name and protocol name to a port number for that service. The optional protocol name, if given, should be 'tcp' or 'udp', otherwise any protocol will match. What does a 'servicename' look like? -- http://mail.python.org/mailman/listinfo/python-list
Re: Help Parsing an HTML File
Stefan Behnel wrote: [EMAIL PROTECTED] wrote: I have a single unicode file that has descriptions of hundreds of objects. The file fairly resembles HTML-EXAMPLE pasted below. I need to parse the file in such a way to extract data out of the html and to come up with a tab separated file that would look like OUTPUT- FILE below. =OUTPUT-FILE= /please note that the first line of the file contains column headers/ --Tab Separated Output File Begin-- H1 H2 DIV Segment1Segment2Segment3 RoséH1-1 RoséH2-1RoséDIV-1 RoséSegmentDIV1-1 RoséSegmentDIV2-1 --Tab Separated Output File End-- =HTML-EXAMPLE= --HTML Example Begin-- html h1RoséH1-1/h1 h2RoséH2-1/h2 divRoséDIV-1/div div segment1RoséSegmentDIV1-1/divbr div segment2RoséSegmentDIV2-1/divbr div segment3RoséSegmentDIV3-1/divbr br br /html --HTML Example End-- Now, what ugly markup is that? You will never manage to get any HTML compliant parser return the segmentX stuff in there. I think your best bet is really going for pyparsing or regular expressions (and I actually recommend pyparsing here). Stefan In practice the following might be sufficient: from BeautifulSoup import BeautifulSoup def chunks(bs): chunk = [] for tag in bs.findAll([h1, h2, div]): if tag.name == h1: if chunk: yield chunk chunk = [] chunk.append(tag) if chunk: yield chunk def process(filename): bs = BeautifulSoup(open(filename)) for chunk in chunks(bs): columns = [tag.string for tag in chunk] columns += [No Value] * (6 - len(columns)) print \t.join(columns) if __name__ == __main__: process(example.html) The biggest caveat is that only columns at the end of a row may be left out. Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Inter-process communication, how? Part 2
Sunday 23 December 2007 Tarihinde 03:56:05 yazmıştı: Hello, just to recap: last time I asked how to do an interprocess communitation, between one Manager process (graphical beckend) and some Worker processes. Why just dont use dbus , and then have a drink :) -- http://mail.python.org/mailman/listinfo/python-list
any python wrapper to call .lib static library(ufmod.lib)?
I want to play .XM music using Python, now I found ufmod http://ufmod.sourceforge.net It only provide a ufmod.lib to be compiled in C/C++/BASIC, and Python as a scripting language could not handle these static libraries. What could I do to with these .lib files? Cheers -- http://mail.python.org/mailman/listinfo/python-list
mapping problem
I've now crawled the meta infor,but with multi name all means the same thing, such as MS,microsoft,microsoft corporation all means the same thing, how can I mapping words like this to the same thing? -- http://mail.python.org/mailman/listinfo/python-list
Re: ways to declare empty set variable
[EMAIL PROTECTED] wrote: ...Missing that, I think dict() and set() and tuple() and list() look better than using {} for the empty dict and {/} for the empty set and () for empty tuple (or {} for the empty dict and set() for the empty set). The problem I have with them is in no way the looks, it is that they are not strictly equivalent as they imply dictionary lookups. Which shows in performance, eg import timeit timeit.Timer('[]').timeit() 0.22358344426456436 timeit.Timer('list()').timeit() 0.54574505977715049 timeit.Timer('{}').timeit() 0.21328632549668214 timeit.Timer('dict()').timeit() 0.50557906102591232 Cheers, BB -- http://mail.python.org/mailman/listinfo/python-list
Re: Floating point bug?
On Fri, 15 Feb 2008 17:30:03 -0800, Jeff Schwab wrote: But good advice becomes a superstition when it becomes treated as a law: never test floats for equality. That's simply not true. For example, floats are exact for whole numbers, up to the limits of overflow. That's not true. Epsilon becomes large (in absolute terms) for large numbers. For 64-bit IEEE floats, eps 1 at about 10**16. Ah yes, good point. Sorry for my brain-fart, I was conflating integer floats with the comp data type, as used in the Standard Apple Numerics Environment (SANE). It used a floating point data type to store what was effectively a 64-bit integer, which was quite significant in the days when PCs used 16-bit integers! Nevertheless, I stand by my claim, and support it by quoting from Professor W Kahan of Berkley, who wrote in the forward to the Apple Numerics Manual (2nd Edition): [quote] ... because so many computers in the 1960's and 1970's possessed so many different arithmetic anomalies, computational lore has become encumbered with a vast body of superstition purporting to cope with them. One such superstitious rule is *Never* ask whether floating-point numbers are exactly equal. [end quote] In practice, you often do want to test floating point values within some tolerance. But it isn't a universal law: see also What Every Computer Scientist Should Know About Floating Point Arithmetic. [quote] Incidentally, some people think that the solution to such anomalies is never to compare floating-point numbers for equality, but instead to consider them equal if they are within some error bound E. This is hardly a cure-all because it raises as many questions as it answers. [end quote] http://docs.sun.com/source/806-3568/ncg_goldberg.html Not directly related to this issue, but to get a great overview of some of the problems with floating point, you could do a lot worse than to read the following interview with Kahan: http://www.ddj.com/184410314 and this wonderful lecture: http://www.cs.berkeley.edu/~wkahan/ieee754status/ieee754.ps where he details how optimizing compilers cause arithmetic errors, how and why the facilities provided by IEEE arithmetic are underused, and finally gives his idea of some things that could be done to turn the situation around. Sadly this lecture was given almost twelve years ago, and things have barely changed. Compilers still do the wrong thing, especially optimizing ones; computations that would be easy with NANs and infinities are needlessly difficult; and benchmarks still over-value speed and under- value getting the right answer, let alone simplicity of programming. If you know your floats are whole numbers, and still writing something like this: x = 1234.0 y = 1000.0 + 200.0 + 30.0 + 4.0 if abs(x-y) 1e-12: print x and y are equal then you are wasting your time and guilty of superstitious behaviour. In what way? It's true that you hard-coded integers for which the margin of error happens to be 1, No, in this case the error is *precisely* zero. There simply are no rounding errors in this calculation, and the error is zero. If you wrote the test as if abs(x-y) 1.0 you'd still be wasting your time. It's true that I gave a hard-coded example, but it is hardly a special case. There are many problem domains that don't require the full range of floats and the type of rounding error you give can't occur. (If your application calculates the amount of concrete needed to build a house, say, then you pretty much know the amounts aren't going to be measured in the trillions of megatonnes. If a user insists on specifying that the house has 1.73e820 stories built on a base measuring 1.82e-87 metres squared, then roundoff is the least of your problems: the algorithms you are applying will no longer be valid.) Or possible you have already rounded the numbers yourself, earlier: x = round(1.5678, 2) x == 1.57 True Why would you do this instead? abs(x - 1.57) 1e-12 True The important thing is that your numbers have appropriately similar scales. If you know that it going to be the case, then you know that addition won't cause the sort of round-off error. I'm talking about. Naturally there may be other forms of round-off, but rounding error doesn't just appear from nowhere, it is predictable and understandable. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: ways to declare empty set variable
Boris Borcic wrote: [EMAIL PROTECTED] wrote: ...Missing that, I think dict() and set() and tuple() and list() look better than using {} for the empty dict and {/} for the empty set and () for empty tuple (or {} for the empty dict and set() for the empty set). The problem I have with them is in no way the looks, it is that they are not strictly equivalent as they imply dictionary lookups. Which shows in performance, eg import timeit timeit.Timer('[]').timeit() 0.22358344426456436 timeit.Timer('list()').timeit() 0.54574505977715049 timeit.Timer('{}').timeit() 0.21328632549668214 timeit.Timer('dict()').timeit() 0.50557906102591232 But this is performance in the abstract. It's hardly going to matter if you use it once in the initialization of your program, but if it occurs deep inside a quadruply-nested loop that is executed 10^12 times it may have an impact on performance. Before you have any code is exactly the *wrong* time to be considering performance. regards Steve -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: mapping problem
On Sat, 16 Feb 2008 01:35:32 -0800, Mr Shore wrote: I've now crawled the meta infor,but with multi name all means the same thing, such as MS,microsoft,microsoft corporation all means the same thing, how can I mapping words like this to the same thing? The same way you would map anything: use a dict. You know, sometimes I'm astounded by the ability of the human brain to find semantic meaning in what is grammatically and syntactically gibberish. Most of the words are English, but putting them all together makes no sense. And yet, by interpolating between key words, I can guess that the poster wants something like this: mapping = {MS: Microsoft, Microsoft: Microsoft, Microsoft Corporation: Microsoft} If I have guessed poorly, could you please try again, more carefully? If you're not a native English speaker, please say so and we'll make allowances, and if you are a native English speaker with no cognitive disabilities, you should be ashamed of wasting our time with such poor communication. -- Steven who is unapologetic for being grumpy about the oxygen-thieves using the Internet these days, and if that makes me a curmudgeon, so be it. -- http://mail.python.org/mailman/listinfo/python-list
Re: mapping problem
Mr Shore wrote: I've now crawled the meta infor,but with multi name all means the same thing, such as MS,microsoft,microsoft corporation all means the same thing, how can I mapping words like this to the same thing? http://docs.python.org/lib/typesmapping.html regards Steve -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Where can I get the module MyUtils?
Python_Doctor schrieb: I inherited a piece of python code which imports MyUtils i.e. it has a line: import MyUtils When I execute the code I get: ImportError: No module named MyUtils I assume the code is looking for another module called MyUtils.py. Is this a standard Python module? Where can I download this module from? How large are the chances that something called MyUtils is a standard-module? And if it were - you wouldn't miss it, wouldn't you? I suggest you ask the one you inherited the code from - it's mosp probably his/hers. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: any python wrapper to call .lib static library(ufmod.lib)?
est schrieb: I want to play .XM music using Python, now I found ufmod http://ufmod.sourceforge.net It only provide a ufmod.lib to be compiled in C/C++/BASIC, and Python as a scripting language could not handle these static libraries. What could I do to with these .lib files? I'm not sure if ctypes can use static libraries, but at least you should be able to create a dynamic library from it that you then can use using ctypes. Or you use Pyrex to wrap the static lib. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: ways to declare empty set variable
On Sat, 16 Feb 2008 05:21:22 -0500, Steve Holden wrote: Before you have any code is exactly the *wrong* time to be considering performance. Well, not really. Don't we already tell people don't use repeated string concatenation, because it is slow, even *before* we know whether it is a bottleneck in their program or not? The problem occurs when people make fastest the *only* consideration, instead of just one out of many. For instance, {} and dict() are very different. Consider this: from collections import defaultdict as dict D1 = dict() D2 = {} They not only have different performance, but different semantics. If you consider it desirable to shadow such built-ins or not is open to debate, although consider this: try: ... set ... except NameError: ... from sets import Set as set ... x = set() You can't do that with syntax. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: returning regex matches as lists
On Feb 16, 8:25 am, Jonathan Lukens [EMAIL PROTECTED] wrote: What would you like to see instead? I had mostly just expected that there was some method that would return each entire match as an item on a list. I have this pattern: import re corporate_names = re.compile(u'(?u)\\b([á-ñ]{2,}\\s+)([][Á-Ñá-ñ]+)(\\s*-?[Á-Ñá-ñ]+)*([])') terms = corporate_names.findall(sourcetext) Which matches a specific way that Russian company names are formatted. I was expecting a method that would return this: terms [u'string one', u'string two', u'string three'] What is the point of having parenthesised groups in the regex if you are interested only in the whole match? Other comments: (1) raw string for improved legibility ru'(?u)\b([á-ñ]{2,}\s+)([][Á-Ñá-ñ]+)(\s*-?[Á-Ñá-ñ]+)*([])' (2) consider not including space at the end of a group ru'(?u)\b([á-ñ]{2,})\s+([][Á-Ñá-ñ]+)\s*(-?[Á-Ñá-ñ]+)*([])' (3) what appears between [] is a set of characters, so [] is the same as [] and probably isn't doing what you expect; have you tested this regex for correctness? ...mostly because I was working it this way in Java and haven't learned to do things the Python way yet. At the suggestion from someone on the list, I just used list() on all the tuples like so: detupled_terms = [list(term_tuple) for term_tuple in terms] delisted_terms = [''.join(term_list) for term_list in detupled_terms] which achieves the desired result, but I am not a programmer and so I would still be interested to know if there is a more elegant way of doing this. I can't imagine how not a programmer implies interested to know if there is a more elegant way. In any case, explore the correctness axis first. Cheers, John -- http://mail.python.org/mailman/listinfo/python-list
Re: Encrypting a short string?
On Feb 12, 2:45 am, erikcw [EMAIL PROTECTED] wrote: Hi, I'm trying to devise a scheme to encrypt/obfuscate a short string that basically contains the user's username and record number from the database. I'm using this encrypted string to identify emails from a user. (the string will be in the subject line of the email). I'm trying to figure out which approach I should use to encrypt the data. The string will be less than 20 characters long, and I'd like the encrypted version to be about the same size. I tried DES in the Crypto module, but the cipher text was to long to be usable in this case. Any suggestions? Thanks! There is a simple encryption, called ROT13 (Rotate 13). This is very unsecure for any cryptographical purpose, but enough to make uninformed user to think it's just a random piece of letters. The ROT13 is done by adding 13 to each character, so A = N, B = O, C = P, D = Q, etc the neat trick to this encryption is the algorithm is really simple and you don't need a separate decoding algorithm as text == ROT13(ROT13(text)). This algorithm also guarantees that any two different text would have two different ciphertext -- http://mail.python.org/mailman/listinfo/python-list
TRAC - Trac, Project Leads, Python, and Mr. Noah Kantrowitz (sanitizer)
Essence: * Trac is deficient, cause of proud to be an egoism driven amateur developers * Python and it's communities is excellent for learning. Not programming, but to learn from deficiency, community organization, transparency, efficiency etc.! * Do it in perl, if you need something more 'pretty', do it in ruby, if you need something more 'serious' do it in java, if you have enough brain and time, do it in C++ from bottom up. - I don't think that's a secret anymore. Anyone should know that the trac team has huge problems to bring trac forward. People who have looked at the code-base and project understand some reason: difficult to maintain 'spaghetti-code' in many places, disorganized project, missing separations of concerns etc.! I've provided an overview some time ago http://case.lazaridis.com/wiki/TracAudit At this time the developers are searching like crazy to find a mem- leak... since months. http://trac.edgewall.org/ticket/6614 But the main problem with the trac team is the processing within project resources. Believe it or not, developers can act within this project as they like, 'trimming' ticket comments in a way that a ticket gets a totally other meaning. The main specialist for this is Mr. Noah Kantrowitz. He calls it sanitizing. The team hides behind him, cowardly, without any public vote. How did everything start? I post a simple message to trac-users (note: the user resource, NOT the developer resource), in order to extend my custom version of trac 0.11 a little. The message did not appear, as my email is under moderation. I do not switch to another email, as I write always with the same identity. So i file a ticket within the ticket system (here you can see the After a quick vote, it has been decided to sanitize this ticket. ... I start to like this sanitize term, sounds really interesting) http://trac.edgewall.org/ticket/6802 Mr. Noah Kantrowitz deleted the discussion, but I've saved it here, thus you can see that the developers of trac have no idea about their own processes: http://case.lazaridis.com/ticket/48 After the developers placed the usual irrelevant comments (remember: I just asked them to stop blocking my messages to trac users), they brute force closed the ticket. I've opened a new one, directly adressed to the project lead, in order to complain about the developers which violate the project processes, and to ask for a formal vote: http://trac.edgewall.org/ticket/6844 Right! Mr. Noah Kantrowitz plays again wild west. I relly don't know who of those two is more funny: the one who plays the dictator, or the other joker who suggests to revers the process (I should find developers to veto against the censorship and send the to the team). Remember: we are talking about the trac-user group. I really cannot believe that a whole team can be in such way confused, nuts, blind, egoism-driven etc.! Possibly they have lost the password to the trac-user group, and are not able to manage it - who knows. I would not wonder, seeing thos terrible processes and the rejection to improve them. (btw: If you like to act against censorship, please post this message to trac-users, thus the get informed about the teams processing) And we are talking about censorship of a trac 0.11dev custom-version- developer. A custom version with localization support, plugin-bundles (product-plugin) which run out of the svn, an fully functional but simple side-navigation, and... everything deactivatable with a very simple way, thus the original trac is there again. http://dev.lazaridis.com/base Open Source works like this: many many small human ego's need to be fitted. There's no place for developers which could redesign the whole thing within a few months. the trac-developers need to 'fight' with tons of spaghetti. The developers plan like crazy, instead to merge with a application framework like e.g. turbogears. Did you know that trac has no support for... datetime fields? Yes, its true. You may say: do it yourself. Of course I could do it, even without touching the main sources (using dyna-patches or monkeypatches). But that's not how open-source works. You implement thing for yourself and contribute things back to the core-project - but with trac there's one problem: no one get's the core anymore (apparently the initial developer has left) Of course I'll not stay with trac, I'll leave the sinking ship, I've prepare long time ago to do so, step by step. An will migrate step by step away from trac and python - toward an own implementation based on... perl and it's libraries. Really, I don't understand the need for python. And after fighting with some indenting within html templates, I dislike the whitespace- syntax-thing of python again. Do it in perl, if you need something more 'pretty', do it in ruby, if you need something more 'serious' do it in java, if you have enough brain and time, do it in C++ from bottom up. Python and it's communities is excellent for learning. Not
Re: Encrypting a short string?
Lie wrote: There is a simple encryption, called ROT13 (Rotate 13). This is very unsecure for any cryptographical purpose, For enhanced security use TROT13 (triple ROT13). but enough to make uninformed user to think it's just a random piece of letters. Security by obscurity doesn't work. If it needs to be protected, protect it well. If it doesn't need to, you don't need to obscure it at all. Regards, Björn -- BOFH excuse #372: Forced to support NT servers; sysadmins quit. -- http://mail.python.org/mailman/listinfo/python-list
Re: returning regex matches as lists
John, (1) raw string for improved legibility ru'(?u)\b([á-ñ]{2,}\s+)([][Á-Ñá-ñ]+)(\s*-?[Á-Ñá-ñ]+)*([])' This actually escaped my notice after I had posted -- the letters with diacritics are incorrectly decoded Cyrillic letters -- I suppose I code use the Unicode escape sequences (the sets [á-ñ] and [Á-Ñá-ñ] are the Cyrillic equivalents of [a-z] and [A-Za-z]) but then suddenly the legibility goes out the window again. (3) what appears between [] is a set of characters, so [] is the same as [] and probably isn't doing what you expect; have you tested this regex for correctness? These were angled quotation marks in the original Unicode. Sorry again.The regex matches everything it is supposed to. The extra parentheses were because I had somehow missed the .group method and it had only been returning what was only in the one needed set of parentheses. I can't imagine how not a programmer implies interested to know if there is a more elegant way. More carefully stated: I am self-taught have no real training or experience as a programmer and would be interested in seeing how a programmer with training and experience would go about this. Thank you, Jonathan -- http://mail.python.org/mailman/listinfo/python-list
Re: sockets -- basic udp client
Here is the example above converted to a more straightforward udp client that isolates the part I am asking about: import socket, sys host = 'localhost' #sys.argv[1] port = 3300 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) data = 'hello world' num_sent = 0 while num_sent len(data): num_sent += s.sendto(data, (host, port)) print Looking for replies; press Ctrl-C or Ctrl-Break to stop. while 1: buf = s.recv(2048) #Will the following if statement do anything? if not len(buf): break print Received from server: %s % buf -- There is still a problem with your script. buf = s.recv(2048) should be changed to buf, addr = s.recvfrom(2048) or buf = s.recvfrom(2048)[0] or something like that since recvfrom returns a pair. But, for the specific case that you have asked about, since the default for timeout is no timeout, or block forever, your question: #Will the following if statement do anything? if not len(buf): break The answer is that you are right, it will do nothing. But, if you set a time out on the socket, and you receive no data and the timeout expires, checking for the length of zero and a break is one way to jump out of the loop if you need to. For example: import socket, sys host = 'localhost' #sys.argv[1] port = 3300 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.settimeout(1.0) buf = '' data = 'hello world' num_sent = 0 while num_sent len(data): num_sent += s.sendto(data, (host, port)) print Looking for replies; press Ctrl-C or Ctrl-Break to stop. while True: try: buf, addr = s.recvfrom(2048) except: pass #Will the following if statement do anything? # In this case it will cause the script to jump out of the loop # if it receives no data for a second. if not len(buf): break print Received from server: %s % buf For getservbyname and its complement, getservbyport, they are talking about well known protocols like http, ftp, chargen, etc. The following script is a very simple example: import socket print socket.getservbyname('http') print socket.getservbyname('ftp') print socket.getservbyname('time') print socket.getservbyport(80) - Bob -- http://mail.python.org/mailman/listinfo/python-list
Re: sockets -- basic udp client
En Sat, 16 Feb 2008 05:56:39 -0200, 7stud [EMAIL PROTECTED] escribi�: while 1: buf = s.recv(2048) if not len(buf): break print Received: %s % buf As far as I can tell, the if statement: if not len(buf): break does nothing. Either recv() is going to read some data or it's going to block. My understanding is that udp sockets do not have a connection, so the server can't close the connection--which would cause a blank string to be sent to the client. So, as far as I can tell, the only way that code would make sense is if the server were programmed to send a blank string to the client after it sent data to the client. Is that correct? Your analysis looks correct to me. If it were using TCP, an empty string signals that the other side has closed the connection, but being UDP it cannot happen (unless the server explicitely sends an empty string, as you said). That example is plain wrong; looks like some TCP code but with SOCK_STREAM blindy replaced with SOCK_DGRAM. connect, sendall and recv are not used for UDP; sendto and recvfrom are used instead. There are some examples in the Demo python directory. Yes, I agree it's a poor example--it's from 'Foundations of Python Network Programming'--but it does 'work'. It also doesn't appear to be a tcp client that was converted too directly into a udp client because the previously presented tcp examples are different. Ok, you *can* use those functions with datagrams too, but it's confusing (at least for the very first UDP example!) Another question I have pertains to the docs here: getservbyname(servicename[, protocolname]) Translate an Internet service name and protocol name to a port number for that service. The optional protocol name, if given, should be 'tcp' or 'udp', otherwise any protocol will match. What does a 'servicename' look like? py import socket py socket.getservbyname(http) 80 py socket.getservbyname(smtp) 25 On Linux the mapping ports-services is in /etc/services; on Windows see %windir%\system32\drivers\etc\services -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: TRAC - Trac, Project Leads, Python, and Mr. Noah Kantrowitz (sanitizer)
Ilias Lazaridis wrote: [...] Of course I'll not stay with trac, I'll leave the sinking ship, I've prepare long time ago to do so, step by step. An will migrate step by step away from trac and python - toward an own implementation based on... perl and it's libraries. I'm sure you will find the Perl community much more welcoming and receptive to your ideas about how open source projects should be run. Really, I don't understand the need for python. And after fighting with some indenting within html templates, I dislike the whitespace- syntax-thing of python again. Fortunately, as you have realized, you have choices and are under no compulsion to use any particular tool. Do it in perl, if you need something more 'pretty', do it in ruby, if you need something more 'serious' do it in java, if you have enough brain and time, do it in C++ from bottom up. And, apparently, do it in Python if you want to avoind running into Ilias Lazaridis. I have to say your approach to IT systems seems somewhat pedestrian, but I wish you well in whatever it is you are trying to achieve. I hope you have a good set of asbestos (i.e. flame-proof) trousers. regards Steve -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: TRAC - Trac, Project Leads, Python, and Mr. Noah Kantrowitz (sanitizer)
On 16.02.2008 13:16, Ilias Lazaridis wrote: snip/ Oh, it's him again. Please do not respond. http://dev.eclipse.org/newslists/news.eclipse.foundation/msg00167.html http://www.encyclopediadramatica.com/index.php/Ilias Cheers robert -- http://mail.python.org/mailman/listinfo/python-list
Re: ways to declare empty set variable
Steve Holden wrote: Boris Borcic wrote: [EMAIL PROTECTED] wrote: ...Missing that, I think dict() and set() and tuple() and list() look better than using {} for the empty dict and {/} for the empty set and () for empty tuple (or {} for the empty dict and set() for the empty set). The problem I have with them is in no way the looks, it is that they are not strictly equivalent as they imply dictionary lookups. Which shows in performance, eg import timeit timeit.Timer('[]').timeit() 0.22358344426456436 timeit.Timer('list()').timeit() 0.54574505977715049 timeit.Timer('{}').timeit() 0.21328632549668214 timeit.Timer('dict()').timeit() 0.50557906102591232 But this is performance in the abstract. It's hardly going to matter if you use it once in the initialization of your program, but if it occurs deep inside a quadruply-nested loop that is executed 10^12 times it may have an impact on performance. In that case about 2.89 days, to be exact. And I don't know about you, but when I write tight nested loops, I can't help opening an eye on not gratuitously wasting time in the innermost loops, well before I come to the point of measuring performance. And I find the case of [] vs list() (or {} vs dict()) to become a specific nuisance in that context. Before you have any code is exactly the *wrong* time to be considering performance. Yeah right, [] and {} are premature optimizations, one should always use list() or dict() unless one detains figures to justify the more exotic forms :) regards Steve Cheers, BB -- http://mail.python.org/mailman/listinfo/python-list
basic wxpython help
Hello, I'm brand new to wxpython, trying to implement some code to add rows in the GUI dynamically. What I want to do is when you click on the Add Row button, a new row gets added after the first row, before the button. This code adds a row in the right place, but it overlaps the button because it doesn't shift the button down. Here's what I have so far: class TestPanel(wx.Panel): def __init__(self, parent, log): self.log = log wx.Panel.__init__(self, parent, -1) fgs = self.fgs = wx.FlexGridSizer(cols=1, hgap=10, vgap=10) fgs.Add(wx.StaticText(self, -1, Label 1)) a1a = self.a1a = wx.FlexGridSizer(cols=5, hgap=10, vgap=10) fgs.Add(a1a) a1a.Add(wx.StaticText(self, -1, User:)) cc = wx.Choice(self, -1, choices=[A, B]) a1a.Add(cc) cc = FileSelectorCombo(self, size=(250, -1)) a1a.Add((10,10)) a1a.Add(wx.StaticText(self, -1, Path:)) a1a.Add(cc) b = wx.Button(self, -1, Add Row, (50,50)) self.Bind(wx.EVT_BUTTON, self.OnButtonIE7, b) fgs.Add(b) box = wx.BoxSizer() box.Add(fgs, 1, wx.EXPAND|wx.ALL, 20) self.SetSizer(box) a1 = wx.FlexGridSizer(cols=5, hgap=10, vgap=10) fgs.Add(a1) b = wx.Button(self, -1, Run Report, (50,50)) self.Bind(wx.EVT_BUTTON, self.OnButtonRun, b) a1.Add(b) b = wx.Button(self, -1, Close, (50,50)) self.Bind(wx.EVT_BUTTON, self.OnButtonClose, b) a1.Add(b) def OnButtonIE7(self, evt): self.a1a.Add(wx.StaticText(self, -1, Label 1)) self.a1a.Layout() def OnButtonRun(self, evt): wx.StaticText(self, -1, User:) def OnButtonClose(self, evt): dlg = wx.MessageDialog(self, Are you sure you want to exit?, Exit, wx.YES_NO | wx.ICON_QUESTION) if dlg.ShowModal() == wx.ID_YES: self.Destroy() # frame sys.exit(1) dlg.Destroy() Any suggestions? Thanks! -- http://mail.python.org/mailman/listinfo/python-list
Re: simple python script to zip files
On Sat, 16 Feb 2008 15:37:16 +, T_T wrote: Hi, I'm just starting to learn some Python basics and are not familiar with file handling. Looking for a python scrip that zips files. So aaa.xx bbb.yy ccc.xx should be zipped to aaa.zip bbb.zip ccc.zip I haven't been able to type more than 'import gzip'.. Just a script I need for practical use (zip didn't do the job) and not for educational purposes. btw. I need it for batch handling, so I want to place the file in a directory, run it and zip all files in the directory. Hope someone will be able to help me. -- http://mail.python.org/mailman/listinfo/python-list
Re: ways to declare empty set variable
Boris Borcic wrote: Steve Holden wrote: [...] Before you have any code is exactly the *wrong* time to be considering performance. Yeah right, [] and {} are premature optimizations, one should always use list() or dict() unless one detains figures to justify the more exotic forms :) :-) My natural inclination would be to go for the literal forms where they are available, but that would be for readability rather than speed. If just happens to be a double win. It's about four years since I wrote a program that ran for more than 24 hours. regards Steve -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: copying files through Python
Hi this is the code which I wrote till now. It is giving permission denied error for sub folders of source directory. Does anyone have any idea what is going wrong import os import shutil def copytreetosinglefolder(src, dst): names = os.listdir(src) if (os.path.isdir(dst)==False): os.mkdir(dst) for name in names: srcname = os.path.join(src, name) try: shutil.copy2(srcname, dst) except (IOError, os.error), why: print Can't copy %s to %s: %s % (`srcname`, `dst`, str(why)) copytreetosinglefolder('c:\\src','d:\\dest') Tim Chase wrote: I am new to python. Infact started yesterday and feeling out of place. I need to write a program which would transfer files under one folder structure (there are sub folders) to single folder. Can anyone give me some idea like which library files or commands would be suitable for this file transfer task. I am sure its matter of few commands. It would be even more great if I could get some sample code with The shutils.copytree() command[1] will do what you describe Depending on your source, and if you want to make the dest writeable (such as copying off a CD), you may also need to use os.walk() [2] combined with os.chmod(filepath, stat.S_IWRITE) [3] -tkc [1] http://docs.python.org/lib/module-shutil.html#l2h-2297 [2] http://docs.python.org/lib/os-file-dir.html#l2h-2707 [3] http://docs.python.org/lib/os-file-dir.html#l2h-2677 -- http://mail.python.org/mailman/listinfo/python-list
Easy PIL question
I know there is an easy way to do this, but I can't figure it out, how do I get the color of a pixel? I used the ImageGrab method and I want to get the color of a specific pixel in that image. If you know how to make it only grab that pixel, that would also be helpful. Basically I'm trying to make a: if pixel == color: do_this() else: pass And have it do this as fast as my pc can handle (that is why only grabbing 1px would be helpful) -- http://mail.python.org/mailman/listinfo/python-list
simple python script to zip files
Hi, I'm just starting to learn some Python basics and are not familiar with file handling. Looking for a python scrip that zips files. So aaa.xx bbb.yy ccc.xx should be zipped to aaa.zip bbb.zip ccc.zip I haven't been able to type more than 'import gzip'.. Just a script I need for practical use (zip didn't do the job) and not for educational purposes. -- http://mail.python.org/mailman/listinfo/python-list
SOAP strategies
What are the reasonable current day choices and best bets for the future when doing SOAP programming in Python? SOAP batteries do not appear to be in the standard Python distribution. Most of the SOAP related information I have been able to find on the web is from 2001-2002. I am not sure if some packages are still maintained. Most of this is old news. http://soapy.sourceforge.net/ http://pywebsvcs.sourceforge.net/ (SOAPpy) and what is the relation of this to ZSI http://www.intertwingly.net/stories/2002/12/20/sbe.html http://www.ibm.com/developerworks/library/ws-pyth5/ http://www.opensourcetutorials.com/tutorials/Server-Side-Coding/Python/python-soap-libraries/page1.html http://www.gossamer-threads.com/lists/python/python/619251 This is current, but is this a long term strategy or a short term tactic? -- http://mail.python.org/mailman/listinfo/python-list
Re: Easy PIL question
Adam W. wrote: I know there is an easy way to do this, but I can't figure it out, how do I get the color of a pixel? I used the ImageGrab method and I want to get the color of a specific pixel in that image. If you know how to make it only grab that pixel, that would also be helpful. Basically I'm trying to make a: if pixel == color: do_this() else: pass And have it do this as fast as my pc can handle (that is why only grabbing 1px would be helpful) Try image.getpixel((x,y)) to retrieve the pixel at (x,y). Gary Herron -- http://mail.python.org/mailman/listinfo/python-list
[OT] Re: TRAC - Trac, Project Leads, Python, and Mr. Noah Kantrowitz (sanitizer)
Ilias Lazaridis wrote: Essence: snipSpam spam spam spam.../snip I just looked at your resume. What is Abstract Project Management? -- http://mail.python.org/mailman/listinfo/python-list
Re: TRAC - Trac, Project Leads, Python, and Mr. Noah Kantrowitz (sanitizer)
Robert Klemme wrote: On 16.02.2008 13:16, Ilias Lazaridis wrote: snip/ Oh, it's him again. Please do not respond. http://dev.eclipse.org/newslists/news.eclipse.foundation/msg00167.html http://www.encyclopediadramatica.com/index.php/Ilias Thank you. I didn't recognize his name at first. -- http://mail.python.org/mailman/listinfo/python-list
Re: basic wxpython help
On Feb 16, 10:04 am, Vamp4L [EMAIL PROTECTED] wrote: Hello, I'm brand new to wxpython, trying to implement some code to add rows in the GUI dynamically. What I want to do is when you click on the Add Row button, a new row gets added after the first row, before the button. This code adds a row in the right place, but it overlaps the button because it doesn't shift the button down. Here's what I have so far: class TestPanel(wx.Panel): def __init__(self, parent, log): self.log = log wx.Panel.__init__(self, parent, -1) fgs = self.fgs = wx.FlexGridSizer(cols=1, hgap=10, vgap=10) fgs.Add(wx.StaticText(self, -1, Label 1)) a1a = self.a1a = wx.FlexGridSizer(cols=5, hgap=10, vgap=10) fgs.Add(a1a) a1a.Add(wx.StaticText(self, -1, User:)) cc = wx.Choice(self, -1, choices=[A, B]) a1a.Add(cc) cc = FileSelectorCombo(self, size=(250, -1)) a1a.Add((10,10)) a1a.Add(wx.StaticText(self, -1, Path:)) a1a.Add(cc) b = wx.Button(self, -1, Add Row, (50,50)) self.Bind(wx.EVT_BUTTON, self.OnButtonIE7, b) fgs.Add(b) box = wx.BoxSizer() box.Add(fgs, 1, wx.EXPAND|wx.ALL, 20) self.SetSizer(box) a1 = wx.FlexGridSizer(cols=5, hgap=10, vgap=10) fgs.Add(a1) b = wx.Button(self, -1, Run Report, (50,50)) self.Bind(wx.EVT_BUTTON, self.OnButtonRun, b) a1.Add(b) b = wx.Button(self, -1, Close, (50,50)) self.Bind(wx.EVT_BUTTON, self.OnButtonClose, b) a1.Add(b) def OnButtonIE7(self, evt): self.a1a.Add(wx.StaticText(self, -1, Label 1)) self.a1a.Layout() def OnButtonRun(self, evt): wx.StaticText(self, -1, User:) def OnButtonClose(self, evt): dlg = wx.MessageDialog(self, Are you sure you want to exit?, Exit, wx.YES_NO | wx.ICON_QUESTION) if dlg.ShowModal() == wx.ID_YES: self.Destroy() # frame sys.exit(1) dlg.Destroy() Any suggestions? Thanks! Welcome to wxPython. It's a lot of fun! Your problem stems from calling the Layout() method on the sizer object. You need to call it on the panel object instead. So just change self.a1a.Layout() to self.Layout() and it should work. Also, I would recommend closing your application differently. Since the parent of this application is likely to be a frame, put a property at the beginning of your __init__ that reads something this this: self.frame = parent Then change your close event handler to this: code def OnButtonClose(self, evt): dlg = wx.MessageDialog(self, Are you sure you want to exit?, Exit, wx.YES_NO | wx.ICON_QUESTION) if dlg.ShowModal() == wx.ID_YES: self.frame.Close() dlg.Destroy() /code Now you won't need to import the sys module and this is the standard way to close a frame in most cases. Finally, I recommend that you join the wxPython list as you'll learn a lot from them and receive good advice there...probably faster than here. Their list can be found here: http://wxpython.org/maillist.php HTH Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: Pop-up Menu of a Graphics Image?
On Feb 15, 2:28 pm, W. Watson [EMAIL PROTECTED] wrote: I want to allow a user who is looking at a graphic to be able to right-click on the graphic to produce a menu of choices. Does the PIL have something, a class or whatever? What in Tkinter would be useful for this purpose? GTK? Jon Fluffy Saul wrote: On Fri, Feb 15, 2008 at 9:55 AM, W. Watson [EMAIL PROTECTED] wrote: Is there a library that contains a pop-up menu class from a mouse click on a graphics image? -- Wayne Watson (Nevada City, CA) Web Page: speckledwithStars.net -- http://mail.python.org/mailman/listinfo/python-list What exactly do you mean by library that contains a pop-up menu class from a mouse click on a graphics image If I deciphered the sentence correctly, then TKinter, win32 and GTK API's can do what you want. Probably others too. -- Wayne Watson (Nevada City, CA) Web Page: speckledwithStars.net wxPython can do a right-click menu like that and I know that PIL has been integrated into it as well. They have a Demo on the wxPython.org website that shows off all the official widgets as well as some custom scripts. If you run it, there is a tree control on the left. Go to the Miscellaneous section and check out the FileHistory demo. There are also a lot of graphics demos in there too under the Using Images category. Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: simple python script to zip files
I'm just starting to learn some Python basics and are not familiar with file handling. Looking for a python scrip that zips files. So aaa.xx bbb.yy ccc.xx should be zipped to aaa.zip bbb.zip ccc.zip I haven't been able to type more than 'import gzip'.. Well, you ask for zip files, but then import gzip... ? btw. I need it for batch handling, so I want to place the file in a directory, run it and zip all files in the directory. import os, zipfile for fname in os.listdir('.'): ... basename, ext = os.path.splitext(fname) ... if ext.lower().endswith('zip'): continue ... f = zipfile.ZipFile('%s.zip' % basename, 'w') ... f.write(fname) ... f.close() ... print fname ... seems to do the trick for me. -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: QOTW: Re: dream hardware
In article [EMAIL PROTECTED], Jeff Schwab [EMAIL PROTECTED] wrote: [EMAIL PROTECTED] wrote: On Feb 14, 10:50 pm, [EMAIL PROTECTED] (Aahz) wrote: In article [EMAIL PROTECTED], Steven D'Aprano [EMAIL PROTECTED] wrote: On Tue, 12 Feb 2008 10:05:59 -0800, castironpi wrote: What is dream hardware for the Python interpreter? I'm not sure that the Python interpreter actually does dream, but if it's anything like me, it's probably a giant computer the size of a bus, made out of broccoli and oven-roasted garlic, that suddenly turns into Sylvester Stallone in a tutu just before my program returns its result. IHNTA, IJWTSA IJWTW? Anyone set up to profile CPython?... or step through? I give up. Is there a phrasebook somewhere, or do I need to hire an interpreter? http://acronyms.thefreedictionary.com/ -- Aahz ([EMAIL PROTECTED]) * http://www.pythoncraft.com/ All problems in computer science can be solved by another level of indirection. --Butler Lampson -- http://mail.python.org/mailman/listinfo/python-list
Re: copying files through Python
On Feb 16, 6:21 pm, Diez B. Roggisch [EMAIL PROTECTED] wrote: Please use a mailer/news-agent that preserves whitespace on the beginning of the line, and make sure you don't use tabs but spaces to indent. Apart from that - why don't you use shutil.copytree? Regarding the error - are you allowed to copy, can you do it using the shell? Diez OP stated requirements were to move all the files into a single folder. Copytree will preserve the directory structure from the source side of the copy operation. Lalit Krishna schrieb: Hi this is the code which I wrote till now. It is giving permission denied error for sub folders of source directory. Does anyone have any idea what is going wrong Python isn't going to let you get around operating system access controls. Check the permissions on the source directories... Pete -- http://mail.python.org/mailman/listinfo/python-list
How about adding rational fraction to Python?
Would all these problems with floating points be a rational reason to add rational numbers support in Python or Py3k? (pun not intended) I agree, there are some numbers that is rationals can't represent (like pi, phi, e) but these rounding problems also exist in floating points, and rational numbers wouldn't be so easily fooled by something like 1 / 3 * 3, and 1/10 (computer) is exactly 0.1 (human). The first problem with rational is that to get an infinite precision rational, the language would have to have an infinite length integers, which Python have given us. The second problem with rationals is to keep rationals in its most simple, trivial form. This can be solved with a good GCD algorithm, which can also be a nice addition to Python's math library. -- http://mail.python.org/mailman/listinfo/python-list
Is there a way to link a python program from several files?
IOW, is there a linker for python? I've written a program comprised of about five .py files. I'd like to find a way to combine them into a single executable. Obviously, I could hand-edit them into a single .py file, but I'm looking for a way to keep them as seperate files for development but distribute the result as a single file. If this were C, I'd compile and link them and distribute the resulting executable. I'm trying to do that, but for Python. TIA, -- -Ed Falk, [EMAIL PROTECTED] http://thespamdiaries.blogspot.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: QOTW: Re: dream hardware
Aahz wrote: In article [EMAIL PROTECTED], Jeff Schwab [EMAIL PROTECTED] wrote: [EMAIL PROTECTED] wrote: On Feb 14, 10:50 pm, [EMAIL PROTECTED] (Aahz) wrote: In article [EMAIL PROTECTED], Steven D'Aprano [EMAIL PROTECTED] wrote: On Tue, 12 Feb 2008 10:05:59 -0800, castironpi wrote: What is dream hardware for the Python interpreter? I'm not sure that the Python interpreter actually does dream, but if it's anything like me, it's probably a giant computer the size of a bus, made out of broccoli and oven-roasted garlic, that suddenly turns into Sylvester Stallone in a tutu just before my program returns its result. IHNTA, IJWTSA IJWTW? Anyone set up to profile CPython?... or step through? I give up. Is there a phrasebook somewhere, or do I need to hire an interpreter? http://acronyms.thefreedictionary.com/ Thanks, but... That defines IHNTA, but not IJWTSA or IJWTW. I just want to say...? I just want to watch? -- http://mail.python.org/mailman/listinfo/python-list
Re: TRAC - Trac, Project Leads, Python, and Mr. Noah Kantrowitz (sanitizer)
On Feb 16, 12:15 pm, Jeff Schwab [EMAIL PROTECTED] wrote: Ilias Lazaridis wrote: Essence: snipSpam spam spam spam.../snip I just looked at your resume. What is Abstract Project Management? A branch of Analysis Paralysis Vaporware. -- http://mail.python.org/mailman/listinfo/python-list
Re: copying files through Python
Lalit Krishna schrieb: Hi this is the code which I wrote till now. It is giving permission denied error for sub folders of source directory. Does anyone have any idea what is going wrong import os import shutil def copytreetosinglefolder(src, dst): names = os.listdir(src) if (os.path.isdir(dst)==False): os.mkdir(dst) for name in names: srcname = os.path.join(src, name) try: shutil.copy2(srcname, dst) except (IOError, os.error), why: print Can't copy %s to %s: %s % (`srcname`, `dst`, str(why)) copytreetosinglefolder('c:\\src','d:\\dest') Please use a mailer/news-agent that preserves whitespace on the beginning of the line, and make sure you don't use tabs but spaces to indent. Apart from that - why don't you use shutil.copytree? Regarding the error - are you allowed to copy, can you do it using the shell? Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: How about adding rational fraction to Python?
Lie wrote: Would all these problems with floating points be a rational reason to add rational numbers support in Python or Py3k? (pun not intended) I agree, there are some numbers that is rationals can't represent (like pi, phi, e) but these rounding problems also exist in floating points, and rational numbers wouldn't be so easily fooled by something like 1 / 3 * 3, and 1/10 (computer) is exactly 0.1 (human). The first problem with rational is that to get an infinite precision rational, the language would have to have an infinite length integers, which Python have given us. The second problem with rationals is to keep rationals in its most simple, trivial form. This can be solved with a good GCD algorithm, which can also be a nice addition to Python's math library. http://www.python.org/dev/peps/pep-0239/ -- http://mail.python.org/mailman/listinfo/python-list
Re: How about adding rational fraction to Python?
On Feb 16, 1:35 pm, Lie [EMAIL PROTECTED] wrote: Would all these problems with floating points be a rational reason to add rational numbers support in Python or Py3k? (pun not intended) It's already in the trunk! Python will have a rational type (called Fraction) in Python 2.6 and Python 3.0, thanks largely to the work of Jeffrey Yaskin. Mark -- http://mail.python.org/mailman/listinfo/python-list
Re: simple python script to zip files
seems to do the trick for me. -tkc Thanks! Works indeed. Strange thing is though, the files created are the exact size as the original file. So it seems like it is zipping without compression. -- http://mail.python.org/mailman/listinfo/python-list
How do I use SendInput in Python?
I'm at the last stage of my project and the only thing left to do is trigger a mouse click. I did some searching around for example code and stumped upon SendInput http://msdn2.microsoft.com/en-us/library/ms646310.aspx . However I was not able to find example code for python USING SendInput, and I have zero ability to make C work (or whatever that is written in). Can someone help me use SendInput in python, or point me to an alternative method? -- http://mail.python.org/mailman/listinfo/python-list
Re: How about adding rational fraction to Python?
On Feb 17, 1:40 am, Jeff Schwab [EMAIL PROTECTED] wrote: Lie wrote: Would all these problems with floating points be a rational reason to add rational numbers support in Python or Py3k? (pun not intended) I agree, there are some numbers that is rationals can't represent (like pi, phi, e) but these rounding problems also exist in floating points, and rational numbers wouldn't be so easily fooled by something like 1 / 3 * 3, and 1/10 (computer) is exactly 0.1 (human). The first problem with rational is that to get an infinite precision rational, the language would have to have an infinite length integers, which Python have given us. The second problem with rationals is to keep rationals in its most simple, trivial form. This can be solved with a good GCD algorithm, which can also be a nice addition to Python's math library. http://www.python.org/dev/peps/pep-0239/ Yes, I'm aware of the PEP and actually have been trying for some time to reopen the PEP. The reason that PEP is rejected is because Decimal is accepted, which I think is a completely absurd reason as Decimal doesn't actually solve the rounding problems and equality comparison problem. Some people have also pointed out that Decimal IS Inexact, while a rational number is always exact except if you have an operation with a (binary or decimal) floating point involved (this can be easilty resolved by making fraction recessive, i.e. an operation that receive a fraction and a float should return a float). -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there a way to link a python program from several files?
Edward A. Falk schrieb: IOW, is there a linker for python? I've written a program comprised of about five .py files. I'd like to find a way to combine them into a single executable. Obviously, I could hand-edit them into a single .py file, but I'm looking for a way to keep them as seperate files for development but distribute the result as a single file. If this were C, I'd compile and link them and distribute the resulting executable. I'm trying to do that, but for Python. Depending on the OS, there are several options. Ranging from distributing an .egg (setuptools) over py2exe for windows to py2app on OSX - and some more, e.g. cx_freeze. Google for one of the above. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: simple python script to zip files
Thanks! Works indeed. Strange thing is though, the files created are the exact size as the original file. So it seems like it is zipping without compression. The instantiation of the ZipFile object can take an optional parameter to control the compression. The zipfile module only supports storing (the default as you discovered) and deflation: f = zipfile.ZipFile(zipfilename, 'w', compression=zipfile.ZIP_DEFLATED) You can read more at http://docs.python.org/lib/zipfile-objects.html -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: QOTW: Re: dream hardware
[EMAIL PROTECTED] wrote: IHNTA, IJWTSA Thanks, but... That defines IHNTA, but not IJWTSA or IJWTW. I just want to say...? I just want to watch?- Hide quoted text - I just want to what? Exactly! -- http://mail.python.org/mailman/listinfo/python-list
Re: How about adding rational fraction to Python?
On Feb 16, 1:35 pm, Lie [EMAIL PROTECTED] wrote: Would all these problems with floating points be a rational reason to add rational numbers support in Python or Py3k? (pun not intended) Forgot to give the link: http://docs.python.org/dev/library/fractions.html Mark -- http://mail.python.org/mailman/listinfo/python-list
Re: How about adding rational fraction to Python?
On Feb 17, 2:26 am, Mark Dickinson [EMAIL PROTECTED] wrote: On Feb 16, 1:35 pm, Lie [EMAIL PROTECTED] wrote: Would all these problems with floating points be a rational reason to add rational numbers support in Python or Py3k? (pun not intended) It's already in the trunk! Python will have a rational type (called Fraction) in Python 2.6 and Python 3.0, thanks largely to the work of Jeffrey Yaskin. Mark Really? I didn't know that (last time I checked they frowned at me for asking that). It's going to be be great if Python supports fractional number. Although rationals have its limitations too, it is a much better choice compared to floats/Decimals for most cases. One thing though, the time I've spent on creating a rational class myself would be 'somewhat' wasted, although I don't really mind that since it was fun in any case. -- http://mail.python.org/mailman/listinfo/python-list
Re: QOTW: Re: dream hardware
IHNTA, IJWTSA Thanks, but... That defines IHNTA, but not IJWTSA or IJWTW. I just want to say...? I just want to watch?- Hide quoted text - I just want to what? -- http://mail.python.org/mailman/listinfo/python-list
Re: How about adding rational fraction to Python?
On Feb 16, 12:35�pm, Lie [EMAIL PROTECTED] wrote: Would all these problems with floating points be a rational reason to add rational numbers support in Python or Py3k? (pun not intended) I agree, there are some numbers that is rationals can't represent (like pi, phi, e) but these rounding problems also exist in floating points, and rational numbers wouldn't be so easily fooled by something like 1 / 3 * 3, and 1/10 (computer) is exactly 0.1 (human). The first problem with rational is that to get an infinite precision rational, the language would have to have an infinite length integers, which Python have given us. The second problem with rationals is to keep rationals in its most simple, trivial form. This can be solved with a good GCD algorithm, which can also be a nice addition to Python's math library. Have you looked at the gmpy madule? That's what I use whenever this comes up. Works very nice to eliminate the issues that prevent a float olution for the problems I'm working on. And some irrationals can be represented by infite sequences of rationals that, coupled with gmpy's unlimited precision floats, allows any number of accurate decimal places to be calculated. If you would like to see an example, check out http://members.aol.com/mensanator/polynomial.py -- http://mail.python.org/mailman/listinfo/python-list
Re: Easy PIL question
Gary Herron: Try image.getpixel((x,y)) to retrieve the pixel at (x,y). If the OP needs to access many pixels, then he can use the load() method on the image object, and then read/write pixels (tuples of 3 ints) using getitem [] import Image im = Image img = im.load() img[x,y] = ... ... = img[x,y] I don't know why the image object itself can't have the __getitem__/ __setitem__ Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: Solve a Debate
On Feb 15, 11:50 pm, Steve Holden [EMAIL PROTECTED] wrote: Dan Bishop wrote: On Feb 15, 10:24 am, nexes [EMAIL PROTECTED] wrote: Alright so me and my friend are having argument. Ok the problem we had been asked a while back, to do a programming exercise (in college) That would tell you how many days there are in a month given a specific month. Ok I did my like this (just pseudo): If month = 1 or 3 or etc noDays = 31 Elseif month = 4 or 6 etc noDays = 30 Else noDays = 29 (we didn't have to take into account a leap year) He declared an array and assigned the number of days in a month to its own element in an array. Now I realise that in this example it would not make a difference in terms of efficiency, but it is my belief that if there is more data that needed to be assigned(i.e. a couple megs of data) it would be simpler (and more efficient) to do a compare rather then assigning all that data to an array, since you are only going to be using 1 value and the rest of the data in the array is useless. What are everyone else's thoughts on this? days_in_month = lambda m: m - 2 and 30 + bool(1 m 5546) or 28 Elegant, but the 5546 is way too magical for readability. int( '0101010110101'[::-1], 2 ) 5546 -- http://mail.python.org/mailman/listinfo/python-list
Re: QOTW: Re: dream hardware
On Feb 16, 1:39 pm, Jeff Schwab [EMAIL PROTECTED] wrote: Aahz wrote: In article [EMAIL PROTECTED], Jeff Schwab [EMAIL PROTECTED] wrote: [EMAIL PROTECTED] wrote: On Feb 14, 10:50 pm, [EMAIL PROTECTED] (Aahz) wrote: In article [EMAIL PROTECTED], Steven D'Aprano [EMAIL PROTECTED] wrote: On Tue, 12 Feb 2008 10:05:59 -0800, castironpi wrote: What is dream hardware for the Python interpreter? I'm not sure that the Python interpreter actually does dream, but if it's anything like me, it's probably a giant computer the size of a bus, made out of broccoli and oven-roasted garlic, that suddenly turns into Sylvester Stallone in a tutu just before my program returns its result. IHNTA, IJWTSA IJWTW? Anyone set up to profile CPython?... or step through? I give up. Is there a phrasebook somewhere, or do I need to hire an interpreter? http://acronyms.thefreedictionary.com/ Thanks, but... That defines IHNTA, but not IJWTSA or IJWTW. I just want to say...? I just want to watch? I Just Wanted To See (This) Again Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: simple python script to zip files
f = zipfile.ZipFile(zipfilename, 'w', compression=zipfile.ZIP_DEFLATED) -tkc Adding the compression rule works great, thanks again! -- http://mail.python.org/mailman/listinfo/python-list
Re: simple python script to zip files
On Feb 17, 6:52 am, Tim Chase [EMAIL PROTECTED] wrote: Thanks! Works indeed. Strange thing is though, the files created are the exact size as the original file. So it seems like it is zipping without compression. The instantiation of the ZipFile object can take an optional parameter to control the compression. The zipfile module only supports storing (the default as you discovered) and deflation: f = zipfile.ZipFile(zipfilename, 'w', compression=zipfile.ZIP_DEFLATED) You can read more at http://docs.python.org/lib/zipfile-objects.html Confession: An infrequent user of the zipfile module, I've been caught twice by this strange choice of default argument. I wonder how many people actually need/want the stored (uncompressed ) format. The select few must surely document that their choice is deliberate: f = zipfile.ZipFile( zipfilename, mode='w', compression=zipfile.ZIP_STORED, # no compression # Yes the above is deliberate. # See section n.nn of project specs. ) Suggestion: for the benefit of folk who (unlike the OP and I) do read the manual, it might help if the text had one paragraph per arg, and included a warning: ... also works, and at least WinZip can read such files. /compression/ is the ZIP compression method to use when writing the archive, and should be ZIP_STORED or ZIP_DEFLATED. *WARNING:* the default is ZIP_STORED (no compression). Unrecognized values will cause RuntimeError to be raised. If ZIP_DEFLATED is specified but the zlib module is not available, RuntimeError is also raised. If /allowZip64/ is True ... Cheers, John -- http://mail.python.org/mailman/listinfo/python-list
Re: Assignment saves time?
I ran the following in the python shell: import timeit storeit=timeit.Timer('s=len(li);s==1000', 'li=range(1000)') checkit=timeit.Timer('len(li)==1000', 'li=range(1000)') listofresults=[(min(storeit.repeat(5)),min(checkit.repeat(5))) for i in xrange(20)] listofresults contained these values (0.25506401062011719, 0.25763511657714844) (0.2541499137878418, 0.25717496871948242) (0.25352811813354492, 0.25570392608642578) (0.25349903106689453, 0.25812816619873047) (0.25426197052001953, 0.25819206237792969) (0.25236606597900391, 0.25693607330322266) (0.25433588027954102, 0.25758695602416992) (0.25356602668762207, 0.25770902633666992) (0.25328993797302246, 0.25844502449035645) (0.25414395332336426, 0.25747895240783691) (0.25800919532775879, 0.25954699516296387) (0.25691604614257812, 0.25997209548950195) (0.25767397880554199, 0.25859308242797852) (0.25512409210205078, 0.26129603385925293) (0.25843596458435059, 0.25791501998901367) (0.2594301700592041, 0.2605140209197998) (0.25701212882995605, 0.25839614868164062) (0.25591516494750977, 0.26186609268188477) (0.25582718849182129, 0.25893092155456543) (0.2576749324798584, 0.25799012184143066) in only one of these pairs is the first value larger than the second value. I don't think this constitutes consistently, but I do think it counts as frequently. -- http://mail.python.org/mailman/listinfo/python-list
Re: QOTW: Re: dream hardware
Carl Banks wrote: On Feb 16, 1:39 pm, Jeff Schwab [EMAIL PROTECTED] wrote: Aahz wrote: In article [EMAIL PROTECTED], Jeff Schwab [EMAIL PROTECTED] wrote: [EMAIL PROTECTED] wrote: On Feb 14, 10:50 pm, [EMAIL PROTECTED] (Aahz) wrote: In article [EMAIL PROTECTED], Steven D'Aprano [EMAIL PROTECTED] wrote: On Tue, 12 Feb 2008 10:05:59 -0800, castironpi wrote: What is dream hardware for the Python interpreter? I'm not sure that the Python interpreter actually does dream, but if it's anything like me, it's probably a giant computer the size of a bus, made out of broccoli and oven-roasted garlic, that suddenly turns into Sylvester Stallone in a tutu just before my program returns its result. IHNTA, IJWTSA IJWTW? Anyone set up to profile CPython?... or step through? I give up. Is there a phrasebook somewhere, or do I need to hire an interpreter? http://acronyms.thefreedictionary.com/ Thanks, but... That defines IHNTA, but not IJWTSA or IJWTW. I just want to say...? I just want to watch? I Just Wanted To See (This) Again Aha. Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: basic wxpython help
Thanks Mike, Simple enough! I was wandering about the close method too, I had to hack that together from what I knew about python already. I'll be sure to join that mailing list. -- http://mail.python.org/mailman/listinfo/python-list
Re: copying files through Python
OP stated requirements were to move all the files into a single folder. Copytree will preserve the directory structure from the source side of the copy operation. well, it would be copying [not moving] files through Python, but if the desire is to flatten the tree into a single directory, that's also easy enough: import os, shutil source_dir = '/home/username/source/' dest_dir = '/home/username/dest/' for path, dirs, files in os.walk(source_dir): for fname in files: shutil.copy(os.path.join(path, fname), dest_dir) The above doesn't do any sort of collision-testing, so if more than one file in source_dir has the same name, the last one to be copied wins, and the first one gets obliterated. Caveat Coder. -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: TRAC - Trac, Project Leads, Python, and Mr. Noah Kantrowitz (sanitizer)
[Followup-To: header set to comp.lang.perl.misc.] Jeff Schwab [EMAIL PROTECTED] wrote: Robert Klemme wrote: On 16.02.2008 13:16, Ilias Lazaridis wrote: snip/ Oh, it's him again. Please do not respond. http://dev.eclipse.org/newslists/news.eclipse.foundation/msg00167.html http://www.encyclopediadramatica.com/index.php/Ilias Thank you. I didn't recognize his name at first. I had the post already pegged as bait simply by counting the number of commas in the Newsgroups header. :-) -- Tad McClellan email: perl -le print scalar reverse qq/moc.noitatibaher\100cmdat/ -- http://mail.python.org/mailman/listinfo/python-list
Re: How about adding rational fraction to Python?
On Feb 16, 3:03 pm, Lie [EMAIL PROTECTED] wrote: Although rationals have its limitations too, it is a much better choice compared to floats/Decimals for most cases. Maybe that's true for your use cases, but it's not true for most cases in general. Rationals are pretty useless for almost any extended calculations, since the denominator tends to grow in size till it's practically unusbale, which means you have to periodically do non-exact reductions to keep things running, and if you do that you might as well be using floating point. Rationals have their occasional special purpose uses, but for most cases they're at best marginally better then floats and more often incomparably worse. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: sockets -- basic udp client
On Feb 16, 6:18 am, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: Here is the example above converted to a more straightforward udp client that isolates the part I am asking about: import socket, sys host = 'localhost' #sys.argv[1] port = 3300 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) data = 'hello world' num_sent = 0 while num_sent len(data): num_sent += s.sendto(data, (host, port)) print Looking for replies; press Ctrl-C or Ctrl-Break to stop. while 1: buf = s.recv(2048) #Will the following if statement do anything? if not len(buf): break print Received from server: %s % buf -- There is still a problem with your script. buf = s.recv(2048) should be changed to buf, addr = s.recvfrom(2048) or buf = s.recvfrom(2048)[0] or something like that since recvfrom returns a pair. If you don't care about the address of the sender, e.g. you are not going to send anything back, is there an advantage to using recv()? Or, as a matter of course should you always use recvfrom() with udp sockets? But, for the specific case that you have asked about, since the default for timeout is no timeout, or block forever, your question: #Will the following if statement do anything? if not len(buf): break The answer is that you are right, it will do nothing. But, if you set a time out on the socket, and you receive no data and the timeout expires, checking for the length of zero and a break is one way to jump out of the loop if you need to. For example: import socket, sys host = 'localhost' #sys.argv[1] port = 3300 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.settimeout(1.0) buf = '' data = 'hello world' num_sent = 0 while num_sent len(data): num_sent += s.sendto(data, (host, port)) print Looking for replies; press Ctrl-C or Ctrl-Break to stop. while True: try: buf, addr = s.recvfrom(2048) except: pass #Will the following if statement do anything? # In this case it will cause the script to jump out of the loop # if it receives no data for a second. if not len(buf): break print Received from server: %s % buf For getservbyname and its complement, getservbyport, they are talking about well known protocols like http, ftp, chargen, etc. The following script is a very simple example: import socket print socket.getservbyname('http') print socket.getservbyname('ftp') print socket.getservbyname('time') print socket.getservbyport(80) - Bob Thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: sockets -- basic udp client
On Feb 16, 6:32 am, Gabriel Genellina [EMAIL PROTECTED] wrote: That example is plain wrong; looks like some TCP code but with SOCK_STREAM blindy replaced with SOCK_DGRAM. connect, sendall and recv are not used for UDP; sendto and recvfrom are used instead. There are some examples in the Demo python directory. Yes, I agree it's a poor example--it's from 'Foundations of Python Network Programming'--but it does 'work'. It also doesn't appear to be a tcp client that was converted too directly into a udp client because the previously presented tcp examples are different. Ok, you *can* use those functions with datagrams too, but it's confusing (at least for the very first UDP example!) Yes, I agree. The book is well written, but the introductory examples and a lack of explanation of the finer details is a disaster. Another question I have pertains to the docs here: getservbyname(servicename[, protocolname]) Translate an Internet service name and protocol name to a port number for that service. The optional protocol name, if given, should be 'tcp' or 'udp', otherwise any protocol will match. What does a 'servicename' look like? py import socket py socket.getservbyname(http) 80 py socket.getservbyname(smtp) 25 On Linux the mapping ports-services is in /etc/services; on Windows see %windir%\system32\drivers\etc\services -- Gabriel Genellina Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: Solve a Debate
On Feb 16, 3:48 pm, Dan Bishop [EMAIL PROTECTED] wrote: On Feb 15, 10:24 am, nexes [EMAIL PROTECTED] wrote: Alright so me and my friend are having argument. Ok the problem we had been asked a while back, to do a programming exercise (in college) That would tell you how many days there are in a month given a specific month. Ok I did my like this (just pseudo): If month = 1 or 3 or etc noDays = 31 Elseif month = 4 or 6 etc noDays = 30 Else noDays = 29 (we didn't have to take into account a leap year) He declared an array and assigned the number of days in a month to its own element in an array. Now I realise that in this example it would not make a difference in terms of efficiency, but it is my belief that if there is more data that needed to be assigned(i.e. a couple megs of data) it would be simpler (and more efficient) to do a compare rather then assigning all that data to an array, since you are only going to be using 1 value and the rest of the data in the array is useless. What are everyone else's thoughts on this? days_in_month = lambda m: m - 2 and 30 + bool(1 m 5546) or 28 Alternatively: days_in_month = lambda m: m - 2 and 31 - ((m + 9) % 12 % 5 % 2) or 28 the guts of which is slightly more elegant than the ancient writing from which it was derived: MOD(MOD(MOD(M+9,12),5),2) -- http://mail.python.org/mailman/listinfo/python-list
RE: Is there a way to link a python program from several files?
Diez B. Roggisch wrote: Edward A. Falk schrieb: IOW, is there a linker for python? I've written a program comprised of about five .py files. I'd like to find a way to combine them into a single executable. Obviously, I could hand-edit them into a single .py file, but I'm looking for a way to keep them as seperate files for development but distribute the result as a single file. Depending on the OS, there are several options. Ranging from distributing an .egg (setuptools) over py2exe for windows to py2app on OSX - and some more, e.g. cx_freeze. I would be interested in a program that can combine multiple modules into a single module, which removes all the inter-package imports and fixes other inter-module references, like Haskell All-in-One does for Haskell: http://www.cs.utah.edu/~hal/HAllInOne/index.html - Brian -- http://mail.python.org/mailman/listinfo/python-list
An idea for fast function composition
Hi all, Recently there was a thread about function composition in Python (and this was probably not the first). The fast way to create a (anonymous) composite function f1 o f2 o ... o fn in Python is via lambda x: f1(f2(...fn(x)...)), but according to some this is neither the most compact nor the most readable. Below I define a 'compose' function such that the above can be written compose(f1, f2, , fn), the resulting function being as fast as the lambda version (or maybe faster?). 'getcomposer' is a helper function (which in most cases will amount to a dictionary lookup). -- def getcomposer(nfunc, _cache={}): getcomposer(n) - lambda f1, ..., fn:(lambda x: f1(...fn(x)...)) try: return _cache[nfunc] except KeyError: fnames = ['f%s' % i for i in range(nfunc)] call = ''.join('%s(' % f for f in fnames) args = ','.join(fnames) cstr = 'lambda %s:(lambda x:%sx%s)' % (args, call, ')'*nfunc) composer = _cache[nfunc] = eval(cstr) return composer def compose(*functions): compose(f1, ..., fn) - lambda x: f1(f2(...fn(x)...)) return getcomposer(len(functions))(*functions) # Test def double(x): return 2*x def square(x): return x**2 def succ(x): return x+1 f1 = compose(double, square, succ, float) f2 = lambda x: double(square(succ(float(x def benchmark(f, n=100): from time import time from itertools import imap t0 = time() for _ in imap(f1, xrange(n)): pass t1 = time() return t1-t0 print 'compose', benchmark(f1) print 'lambda ', benchmark(f2) -- marigold:python arno$ python -i simple_compose.py compose 1.84630298615 lambda 1.86365509033 import dis dis.dis(f1) 1 0 LOAD_DEREF 0 (f0) 3 LOAD_DEREF 3 (f1) 6 LOAD_DEREF 1 (f2) 9 LOAD_DEREF 2 (f3) 12 LOAD_FAST0 (x) 15 CALL_FUNCTION1 18 CALL_FUNCTION1 21 CALL_FUNCTION1 24 CALL_FUNCTION1 27 RETURN_VALUE dis.dis(f2) 23 0 LOAD_GLOBAL 0 (double) 3 LOAD_GLOBAL 1 (square) 6 LOAD_GLOBAL 2 (succ) 9 LOAD_GLOBAL 3 (float) 12 LOAD_FAST0 (x) 15 CALL_FUNCTION1 18 CALL_FUNCTION1 21 CALL_FUNCTION1 24 CALL_FUNCTION1 27 RETURN_VALUE f1 and f2 are almost exaclty the same but array lookups (LOAD_DEREFs) in f1 replace dictionary lookups (LOAD_GLOBALs) in f2. A C version of 'compose' could easily be written that doesn't require the use of a python lambda-function (as created by 'getcomposer'). -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list
Re: How about adding rational fraction to Python?
Carl Banks [EMAIL PROTECTED] writes: Rationals are pretty useless for almost any extended calculations, since the denominator tends to grow in size till it's practically unusbale, which means you have to periodically do non-exact reductions to keep things running, and if you do that you might as well be using floating point. This only happens if you're chaining many divisions by non-constants, which in the typical business calculation does not happen. Those calculations divide by 10 a lot, and sometimes by 12 or 365, but they rarely divide a calculated quantity by another calculated quantity, especially to more than one level. I.e. they might compute the ratio of widgets sold to widgets repaired, but they wouldn't then divide that ratio by some other weird number. I did in fact implement rational arithmetic in a business app a long time ago, because management wanted it. I had the same concerns that you express, but they just weren't a problem in practice. -- http://mail.python.org/mailman/listinfo/python-list
Re: How about adding rational fraction to Python?
On Feb 17, 4:25 am, Carl Banks [EMAIL PROTECTED] wrote: On Feb 16, 3:03 pm, Lie [EMAIL PROTECTED] wrote: Although rationals have its limitations too, it is a much better choice compared to floats/Decimals for most cases. Maybe that's true for your use cases, but it's not true for most cases in general. OK, that might have been an overstatement, but as I see it, it is safer to handle something in a Fraction compared to floats (which is why I uses fractions whenever possible in non-computer maths). Rationals are pretty useless for almost any extended calculations, since the denominator tends to grow in size till it's practically unusbale, which means you have to periodically do non-exact reductions to keep things running, and if you do that you might as well be using floating point. Rationals aren't that good if the same piece of variable is to be calculated again and again because of its growth, but there are a lot of cases where the data would only require five or six or so operations done on it (and there are thousands or millions of such datas), rationals is the perfect choice for those situations because it is easier to use thanks to the comparison safety. Or in the situations where speed isn't as important and accuracy is required, Fraction may be faster than decimal and more accurate at the same time (someone need to test that though). Rationals have their occasional special purpose uses, but for most cases they're at best marginally better then floats and more often incomparably worse. -- http://mail.python.org/mailman/listinfo/python-list
Re: ways to declare empty set variable
On Sat, 16 Feb 2008 11:14:10 -0500, Steve Holden wrote: It's about four years since I wrote a program that ran for more than 24 hours. Let me guess... and then you discovered ''.join(['x', 'y']) instead of 'x'+'y'? *wink* -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Solve a Debate
[EMAIL PROTECTED] wrote: On Feb 15, 11:50 pm, Steve Holden [EMAIL PROTECTED] wrote: Dan Bishop wrote: On Feb 15, 10:24 am, nexes [EMAIL PROTECTED] wrote: [...] What are everyone else's thoughts on this? days_in_month = lambda m: m - 2 and 30 + bool(1 m 5546) or 28 Elegant, but the 5546 is way too magical for readability. int( '0101010110101'[::-1], 2 ) 5546 Yes, I'm aware of that. Adding it as a comment might help. regards Steve -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
class static variables and __dict__
If I have a class static variable it doesn't show up in the __dict__ of an instance of that class. class C: n = 4 x = C() print C.__dict__ {'__module__': '__main__', '__doc__': None, 'n': 4} print x.__dict__ {} This behavior makes sense to me as n is not encapsulated in x's namespace but what method can you use on x to find all available attributes for that class? -- Zack -- http://mail.python.org/mailman/listinfo/python-list
Re: How about adding rational fraction to Python?
Carl Banks wrote: On Feb 16, 3:03 pm, Lie [EMAIL PROTECTED] wrote: Although rationals have its limitations too, it is a much better choice compared to floats/Decimals for most cases. Maybe that's true for your use cases, but it's not true for most cases in general. Rationals are pretty useless for almost any extended calculations, since the denominator tends to grow in size till it's practically unusbale, What do you mean by practically unusable? I heard similar arguments made against big integers at one point (Primitive types are usually big enough, why risk performance?) but I fell in love with them when I first saw them in Smalltalk, and I'm glad Python supports them natively. -- http://mail.python.org/mailman/listinfo/python-list
Re: Solve a Debate
days_in_month = lambda m: m - 2 and 31 - ((m + 9) % 12 % 5 % 2) or 28 the guts of which is slightly more elegant than the ancient writing from which it was derived: Lacks citation. -- http://mail.python.org/mailman/listinfo/python-list
Re: class static variables and __dict__
Zack schrieb: If I have a class static variable it doesn't show up in the __dict__ of an instance of that class. class C: n = 4 x = C() print C.__dict__ {'__module__': '__main__', '__doc__': None, 'n': 4} print x.__dict__ {} This behavior makes sense to me as n is not encapsulated in x's namespace but what method can you use on x to find all available attributes for that class? x.__class__.__dict__ Diez -- http://mail.python.org/mailman/listinfo/python-list
Video4Linux for [EMAIL PROTECTED]
This would be Off Topic, but it is for PyCon, so there will be lots of Python side effects. I am looking for help with a Video4Linux2 driver, which is C code. I am trying to get a piece of hardware working with trascode. hardware: http://www.epiphan.com/products/product.php?pid=66 http://www.transcoding.org transcode has both v4l and v4l2 support. the vga grabber has a v4l driver, but both it and tc's v4l are iffy. The main transcode developer recommended using v4l2 I was able to capture 1 screen per second at last weeks Python user group meeting. I was able to make a 60mb avi from that. So I have a good start, but there is room for improvement. If I can get this working, I can give people who help everything that happens at PyCon - probably 50-100gig of avi files. I'll send you on DVDs so you don't have to download it all. feel free to contact me here, or off list, or on #python or #chipy. Carl K -- http://mail.python.org/mailman/listinfo/python-list
Re: An idea for fast function composition
On Feb 16, 3:47 pm, Arnaud Delobelle [EMAIL PROTECTED] wrote: Hi all, Recently there was a thread about function composition in Python (and this was probably not the first). The fast way to create a (anonymous) composite function f1 o f2 o ... o fn in Python is via lambda x: f1(f2(...fn(x)...)), but according to some this is neither the most compact nor the most readable. Below I define a 'compose' function such that the above can be written compose(f1, f2, , fn), the resulting function being as fast as the lambda version (or maybe faster?). 'getcomposer' is a helper function (which in most cases will amount to a dictionary lookup). -- def getcomposer(nfunc, _cache={}): getcomposer(n) - lambda f1, ..., fn:(lambda x: f1(...fn(x)...)) try: return _cache[nfunc] except KeyError: fnames = ['f%s' % i for i in range(nfunc)] call = ''.join('%s(' % f for f in fnames) args = ','.join(fnames) cstr = 'lambda %s:(lambda x:%sx%s)' % (args, call, ')'*nfunc) composer = _cache[nfunc] = eval(cstr) return composer def compose(*functions): compose(f1, ..., fn) - lambda x: f1(f2(...fn(x)...)) return getcomposer(len(functions))(*functions) # Test def double(x): return 2*x def square(x): return x**2 def succ(x): return x+1 f1 = compose(double, square, succ, float) f2 = lambda x: double(square(succ(float(x def benchmark(f, n=100): from time import time from itertools import imap t0 = time() for _ in imap(f1, xrange(n)): pass t1 = time() return t1-t0 print 'compose', benchmark(f1) print 'lambda ', benchmark(f2) -- marigold:python arno$ python -i simple_compose.py compose 1.84630298615 lambda 1.86365509033 import dis dis.dis(f1) 1 0 LOAD_DEREF 0 (f0) 3 LOAD_DEREF 3 (f1) 6 LOAD_DEREF 1 (f2) 9 LOAD_DEREF 2 (f3) 12 LOAD_FAST 0 (x) 15 CALL_FUNCTION 1 18 CALL_FUNCTION 1 21 CALL_FUNCTION 1 24 CALL_FUNCTION 1 27 RETURN_VALUE dis.dis(f2) 23 0 LOAD_GLOBAL 0 (double) 3 LOAD_GLOBAL 1 (square) 6 LOAD_GLOBAL 2 (succ) 9 LOAD_GLOBAL 3 (float) 12 LOAD_FAST 0 (x) 15 CALL_FUNCTION 1 18 CALL_FUNCTION 1 21 CALL_FUNCTION 1 24 CALL_FUNCTION 1 27 RETURN_VALUE f1 and f2 are almost exaclty the same but array lookups (LOAD_DEREFs) in f1 replace dictionary lookups (LOAD_GLOBALs) in f2. A C version of 'compose' could easily be written that doesn't require the use of a python lambda-function (as created by 'getcomposer'). -- Arnaud def compose( funcs ): def reccompose( *args ): return compose( funcs[:-1] )( funcs[-1]( *args ) ) if funcs else funcs[0]( *args ) return reccompose -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there a way to link a python program from several files?
Brian Smith schrieb: Diez B. Roggisch wrote: Edward A. Falk schrieb: IOW, is there a linker for python? I've written a program comprised of about five .py files. I'd like to find a way to combine them into a single executable. Obviously, I could hand-edit them into a single .py file, but I'm looking for a way to keep them as seperate files for development but distribute the result as a single file. Depending on the OS, there are several options. Ranging from distributing an .egg (setuptools) over py2exe for windows to py2app on OSX - and some more, e.g. cx_freeze. I would be interested in a program that can combine multiple modules into a single module, which removes all the inter-package imports and fixes other inter-module references, like Haskell All-in-One does for Haskell: http://www.cs.utah.edu/~hal/HAllInOne/index.html won't happen for python. python relies heavily on modules/packages being namespaces. Why would you want such a beast anyway? If it's about single-file-distribution, that is solved by some of the above mentioned tools - or even not desired anyway (say OS X bundles) Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: class static variables and __dict__
Diez B. Roggisch wrote: Zack schrieb: If I have a class static variable it doesn't show up in the __dict__ of an instance of that class. class C: n = 4 x = C() print C.__dict__ {'__module__': '__main__', '__doc__': None, 'n': 4} print x.__dict__ {} This behavior makes sense to me as n is not encapsulated in x's namespace but what method can you use on x to find all available attributes for that class? x.__class__.__dict__ Diez This would leave out any attributes of base classes. Not that I asked for that functionality in my original post but is there a way to get all attributes qualified by x. ? I see that I could walk the dict of x, x.__class__ and x.__class__.__bases__ until I exhaust the tree. But is there a built in method for doing this? -- Zack -- http://mail.python.org/mailman/listinfo/python-list
RE: Is there a way to link a python program from several files?
Diez B. Roggisch wrote: Brian Smith wrote: I would be interested in a program that can combine multiple modules into a single module, which removes all the inter-package imports and fixes other inter-module references, like Haskell All-in-One does for Haskell: http://www.cs.utah.edu/~hal/HAllInOne/index.html won't happen for python. python relies heavily on modules/packages being namespaces. So does Haskell. Haskell All-In-One handles that by renaming every top-level artifact. Why would you want such a beast anyway? If it's about single-file-distribution, that is solved by some of the above mentioned tools - or even not desired anyway (say OS X bundles) I want to package a complex WSGI application into a single CGI script, so that users can copy the script into some CGI-enabled directory and have it work without any further configuration, and so that it runs faster (especially when the file is on NFS). If it is possible to run an egg as a CGI (without modifying the web server configuration file), then that would work as well. - Brian -- http://mail.python.org/mailman/listinfo/python-list
Re: Solve a Debate
On Feb 17, 9:57 am, [EMAIL PROTECTED] wrote: days_in_month = lambda m: m - 2 and 31 - ((m + 9) % 12 % 5 % 2) or 28 the guts of which is slightly more elegant than the ancient writing from which it was derived: Lacks citation. Maxima mea culpa. Pages 294-295 (in particular formula 23.12) in MAPPING TIME\nThe Calendar and Its History, by E. G. Richards. OUP, 1998. ISBN 0-19-286205-7. -- http://mail.python.org/mailman/listinfo/python-list
Re: An idea for fast function composition
def compose( funcs ): def reccompose( *args ): return compose( funcs[:-1] )( funcs[-1]( *args ) ) if funcs else funcs[0]( *args ) return reccompose- Hide quoted text - Which was, if funcs 1, which is len( funcs ) 1. [1]0 Traceback (most recent call last): File stdin, line 1, in module TypeError: unorderable types: list() int() -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I use SendInput in Python?
En Sat, 16 Feb 2008 17:08:59 -0200, Adam W. [EMAIL PROTECTED] escribi�: I'm at the last stage of my project and the only thing left to do is trigger a mouse click. I did some searching around for example code and stumped upon SendInput http://msdn2.microsoft.com/en-us/library/ms646310.aspx . However I was not able to find example code for python USING SendInput, and I have zero ability to make C work (or whatever that is written in). Can someone help me use SendInput in python, or point me to an alternative method? Try sendkeys: http://www.rutherfurd.net/python/sendkeys/index.html PyWinAuto uses the above library and lets you automate an application in a very simple way: http://www.openqa.org/pywinauto -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: How about adding rational fraction to Python?
On Feb 16, 5:51 pm, Jeff Schwab [EMAIL PROTECTED] wrote: Carl Banks wrote: On Feb 16, 3:03 pm, Lie [EMAIL PROTECTED] wrote: Although rationals have its limitations too, it is a much better choice compared to floats/Decimals for most cases. Maybe that's true for your use cases, but it's not true for most cases in general. Rationals are pretty useless for almost any extended calculations, since the denominator tends to grow in size till it's practically unusbale, What do you mean by practically unusable? I heard similar arguments made against big integers at one point (Primitive types are usually big enough, why risk performance?) but I fell in love with them when I first saw them in Smalltalk, and I'm glad Python supports them natively. -- http://mail.python.org/mailman/listinfo/python-list
Re: class static variables and __dict__
On Feb 16, 4:40 pm, Zack [EMAIL PROTECTED] wrote: what method can you use on x to find all available attributes for that class? class Foo(object): bar = hello, world! def __init__(self, baz): self.baz = baz x = Foo(42) x.__dict__.keys() # Does not include bar ['baz'] dir(x) # Includes bar plus some methods ['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__', 'bar', 'baz'] -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there a way to link a python program from several files?
Brian Smith [EMAIL PROTECTED] writes: So does Haskell. Haskell All-In-One handles that by renaming every top-level artifact. That can't be done reliably in python because namespaces are dynamic. If it is possible to run an egg as a CGI (without modifying the web server configuration file), then that would work as well. This would be an interesting enhancement. -- http://mail.python.org/mailman/listinfo/python-list
Re: An idea for fast function composition
[EMAIL PROTECTED] wrote: On Feb 16, 3:47 pm, Arnaud Delobelle [EMAIL PROTECTED] wrote: Hi all, Recently there was a thread about function composition in Python (and this was probably not the first). The fast way to create a (anonymous) composite function f1 o f2 o ... o fn in Python is via lambda x: f1(f2(...fn(x)...)), but according to some this is neither the most compact nor the most readable. Below I define a 'compose' function such that the above can be written compose(f1, f2, , fn), the resulting function being as fast as the lambda version (or maybe faster?). 'getcomposer' is a helper function (which in most cases will amount to a dictionary lookup). -- def getcomposer(nfunc, _cache={}): getcomposer(n) - lambda f1, ..., fn:(lambda x: f1(...fn(x)...)) try: return _cache[nfunc] except KeyError: fnames = ['f%s' % i for i in range(nfunc)] call = ''.join('%s(' % f for f in fnames) args = ','.join(fnames) cstr = 'lambda %s:(lambda x:%sx%s)' % (args, call, ')'*nfunc) composer = _cache[nfunc] = eval(cstr) return composer def compose(*functions): compose(f1, ..., fn) - lambda x: f1(f2(...fn(x)...)) return getcomposer(len(functions))(*functions) # Test def double(x): return 2*x def square(x): return x**2 def succ(x): return x+1 f1 = compose(double, square, succ, float) f2 = lambda x: double(square(succ(float(x def benchmark(f, n=100): from time import time from itertools import imap t0 = time() for _ in imap(f1, xrange(n)): pass t1 = time() return t1-t0 print 'compose', benchmark(f1) print 'lambda ', benchmark(f2) -- marigold:python arno$ python -i simple_compose.py compose 1.84630298615 lambda 1.86365509033 import dis dis.dis(f1) 1 0 LOAD_DEREF 0 (f0) 3 LOAD_DEREF 3 (f1) 6 LOAD_DEREF 1 (f2) 9 LOAD_DEREF 2 (f3) 12 LOAD_FAST0 (x) 15 CALL_FUNCTION1 18 CALL_FUNCTION1 21 CALL_FUNCTION1 24 CALL_FUNCTION1 27 RETURN_VALUE dis.dis(f2) 23 0 LOAD_GLOBAL 0 (double) 3 LOAD_GLOBAL 1 (square) 6 LOAD_GLOBAL 2 (succ) 9 LOAD_GLOBAL 3 (float) 12 LOAD_FAST0 (x) 15 CALL_FUNCTION1 18 CALL_FUNCTION1 21 CALL_FUNCTION1 24 CALL_FUNCTION1 27 RETURN_VALUE f1 and f2 are almost exaclty the same but array lookups (LOAD_DEREFs) in f1 replace dictionary lookups (LOAD_GLOBALs) in f2. A C version of 'compose' could easily be written that doesn't require the use of a python lambda-function (as created by 'getcomposer'). -- Arnaud def compose( funcs ): def reccompose( *args ): return compose( funcs[:-1] )( funcs[-1]( *args ) ) if funcs else funcs[0]( *args ) return reccompose def compose( *funcs ): def reccompose( *args ): return compose( funcs[:-1] )( funcs[-1]( *args ) ) if funcs else funcs[0]( *args ) return reccompose f3 = compose(double, square, succ, float) import dis dis.dis(f3) 3 0 LOAD_DEREF 0 (funcs) 3 JUMP_IF_FALSE 33 (to 39) 6 POP_TOP 7 LOAD_GLOBAL 0 (compose) 10 LOAD_DEREF 0 (funcs) 13 LOAD_CONST 1 (-1) 16 SLICE+2 17 CALL_FUNCTION1 20 LOAD_DEREF 0 (funcs) 23 LOAD_CONST 1 (-1) 26 BINARY_SUBSCR 27 LOAD_FAST0 (args) 30 CALL_FUNCTION_VAR0 33 CALL_FUNCTION1 36 JUMP_FORWARD14 (to 53) 39 POP_TOP 40 LOAD_DEREF 0 (funcs) 43 LOAD_CONST 2 (0) 46 BINARY_SUBSCR 47 LOAD_FAST0 (args) 50 CALL_FUNCTION_VAR0 53 RETURN_VALUE Mmmhhh... -- http://mail.python.org/mailman/listinfo/python-list
Re: class static variables and __dict__
Zack wrote: Diez B. Roggisch wrote: Zack schrieb: If I have a class static variable it doesn't show up in the __dict__ of an instance of that class. class C: n = 4 x = C() print C.__dict__ {'__module__': '__main__', '__doc__': None, 'n': 4} print x.__dict__ {} This behavior makes sense to me as n is not encapsulated in x's namespace but what method can you use on x to find all available attributes for that class? x.__class__.__dict__ Diez This would leave out any attributes of base classes. Not that I asked for that functionality in my original post but is there a way to get all attributes qualified by x. ? I see that I could walk the dict of x, x.__class__ and x.__class__.__bases__ until I exhaust the tree. But is there a built in method for doing this? I believe this accomplishes what I'm looking for. I'm not positive it is correct or if there are cases I've missed. It would be nice if there is a simple python builtin for finding the fully qualified dict. def fullDict(obj): ''' Returns a dict with all attributes qualified by obj. obj is an instance of a class ''' d = obj.__dict__ # update existing items into new items to preserve inheritance tmpD = obj.__class__.__dict__ tmpD.update(d) d = tmpD supers = list(obj.__class__.__bases__) for c in supers: tmpD = c.__dict__ tmpD.update(d) d = tmpD supers.extend(c.__bases__) return d -- Zack -- http://mail.python.org/mailman/listinfo/python-list
Re: class static variables and __dict__
Dustan wrote: On Feb 16, 4:40 pm, Zack [EMAIL PROTECTED] wrote: what method can you use on x to find all available attributes for that class? class Foo(object): bar = hello, world! def __init__(self, baz): self.baz = baz x = Foo(42) x.__dict__.keys() # Does not include bar ['baz'] dir(x) # Includes bar plus some methods ['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__', 'bar', 'baz'] I knew there was something simple I was forgetting. Thanks -- Zack -- http://mail.python.org/mailman/listinfo/python-list
Re: An idea for fast function composition
On Feb 16, 5:57 pm, Boris Borcic [EMAIL PROTECTED] wrote: [EMAIL PROTECTED] wrote: On Feb 16, 3:47 pm, Arnaud Delobelle [EMAIL PROTECTED] wrote: Hi all, Recently there was a thread about function composition in Python (and this was probably not the first). The fast way to create a (anonymous) composite function f1 o f2 o ... o fn in Python is via lambda x: f1(f2(...fn(x)...)), but according to some this is neither the most compact nor the most readable. Below I define a 'compose' function such that the above can be written compose(f1, f2, , fn), the resulting function being as fast as the lambda version (or maybe faster?). 'getcomposer' is a helper function (which in most cases will amount to a dictionary lookup). -- def getcomposer(nfunc, _cache={}): getcomposer(n) - lambda f1, ..., fn:(lambda x: f1(...fn(x)...)) try: return _cache[nfunc] except KeyError: fnames = ['f%s' % i for i in range(nfunc)] call = ''.join('%s(' % f for f in fnames) args = ','.join(fnames) cstr = 'lambda %s:(lambda x:%sx%s)' % (args, call, ')'*nfunc) composer = _cache[nfunc] = eval(cstr) return composer def compose(*functions): compose(f1, ..., fn) - lambda x: f1(f2(...fn(x)...)) return getcomposer(len(functions))(*functions) # Test def double(x): return 2*x def square(x): return x**2 def succ(x): return x+1 f1 = compose(double, square, succ, float) f2 = lambda x: double(square(succ(float(x def benchmark(f, n=100): from time import time from itertools import imap t0 = time() for _ in imap(f1, xrange(n)): pass t1 = time() return t1-t0 print 'compose', benchmark(f1) print 'lambda ', benchmark(f2) -- marigold:python arno$ python -i simple_compose.py compose 1.84630298615 lambda 1.86365509033 import dis dis.dis(f1) 1 0 LOAD_DEREF 0 (f0) 3 LOAD_DEREF 3 (f1) 6 LOAD_DEREF 1 (f2) 9 LOAD_DEREF 2 (f3) 12 LOAD_FAST 0 (x) 15 CALL_FUNCTION 1 18 CALL_FUNCTION 1 21 CALL_FUNCTION 1 24 CALL_FUNCTION 1 27 RETURN_VALUE dis.dis(f2) 23 0 LOAD_GLOBAL 0 (double) 3 LOAD_GLOBAL 1 (square) 6 LOAD_GLOBAL 2 (succ) 9 LOAD_GLOBAL 3 (float) 12 LOAD_FAST 0 (x) 15 CALL_FUNCTION 1 18 CALL_FUNCTION 1 21 CALL_FUNCTION 1 24 CALL_FUNCTION 1 27 RETURN_VALUE f1 and f2 are almost exaclty the same but array lookups (LOAD_DEREFs) in f1 replace dictionary lookups (LOAD_GLOBALs) in f2. A C version of 'compose' could easily be written that doesn't require the use of a python lambda-function (as created by 'getcomposer'). -- Arnaud def compose( funcs ): def reccompose( *args ): return compose( funcs[:-1] )( funcs[-1]( *args ) ) if funcs else funcs[0]( *args ) return reccompose def compose( *funcs ): def reccompose( *args ): return compose( funcs[:-1] )( funcs[-1]( *args ) ) if funcs else funcs[0]( *args ) return reccompose f3 = compose(double, square, succ, float) import dis dis.dis(f3) 3 0 LOAD_DEREF 0 (funcs) 3 JUMP_IF_FALSE 33 (to 39) 6 POP_TOP 7 LOAD_GLOBAL 0 (compose) 10 LOAD_DEREF 0 (funcs) 13 LOAD_CONST 1 (-1) 16 SLICE+2 17 CALL_FUNCTION 1 20 LOAD_DEREF 0 (funcs) 23 LOAD_CONST 1 (-1) 26 BINARY_SUBSCR 27 LOAD_FAST 0 (args) 30 CALL_FUNCTION_VAR 0 33 CALL_FUNCTION 1 36 JUMP_FORWARD 14 (to 53) 39 POP_TOP 40 LOAD_DEREF 0 (funcs) 43 LOAD_CONST 2 (0) 46 BINARY_SUBSCR 47 LOAD_FAST 0 (args) 50 CALL_FUNCTION_VAR 0 53 RETURN_VALUE Mmmhhh...- Hide quoted text - - Show quoted text - OO! Sulks off to lick wounds. -- http://mail.python.org/mailman/listinfo/python-list
Re: Turn off ZeroDivisionError?
On Fri, 15 Feb 2008 17:31:51 -0800, Mark Dickinson wrote: On Feb 15, 7:59 pm, Steven D'Aprano [EMAIL PROTECTED] cybersource.com.au wrote: On Fri, 15 Feb 2008 14:35:34 -0500, Steve Holden wrote: I don't understand: why would +INF not be equal to itself? Having INF == INF be True seems like something that makes sense both mathematically and computationally. [...] There are an uncountable number of infinities, all different. But the IEEE standard only supports one of them, aleph(0). Technically two: plus and minus aleph(0). Not sure that alephs have anything to do with it. And unless I'm missing something, minus aleph(0) is nonsense. (How do you define the negation of a cardinal?) *shrug* How would you like to? The natural numbers (0, 1, 2, 3, ...) are cardinal numbers too. 0 is the cardinality of the empty set {}; 1 is the cardinality of the set containing only the empty set {{}}; 2 is the cardinality of the set containing a set of cardinality 0 and a set of cardinality 1 {{}, {{}}} ... and so on. Since we have generalized the natural numbers to the integers ... -3 -2 -1 0 1 2 3 ... without worrying about what set has cardinality -1, I see no reason why we shouldn't generalize negation to the alephs. The question of what set, if any, has cardinality -aleph(0) is irrelevant. Since the traditional infinity of the real number line comes in a positive and negative version, and we identify positive ∞ as aleph(0) [see below for why], I don't believe there's any thing wrong with identifying -aleph(0) as -∞. Another approach might be to treat the cardinals as ordinals. Subtraction isn't directly defined for ordinals, ordinals explicitly start counting at zero and only increase, never decrease. But one might argue that since all ordinals are surreal numbers, and subtraction *is* defined for surreals, we might identify aleph(0) as the ordinal omega ω then the negative of aleph(0) is just -ω, or {|{ ... -4, -3, -2, -1 }}. Or in English... -aleph(0) is the number more negative than every negative integer, which gratifyingly matches our intuition about negative infinity. There's lots of hand-waving there. I expect a real mathematician could make it all vigorous. But a lot of it is really missing the point, which is that the IEEE standard isn't about ordinals, or cardinals, or surreal numbers, but about floating point numbers as a discrete approximation to the reals. In the reals, there are only two infinities that we care about, a positive and negative, and apart from the sign they are equivalent to aleph(0). From the fount of all wisdom: (http://en.wikipedia.org/wiki/ Aleph_number) The aleph numbers differ from the infinity (∞) commonly found in algebra and calculus. Alephs measure the sizes of sets; infinity, on the other hand, is commonly defined as an extreme limit of the real number line (applied to a function or sequence that diverges to infinity or increases without bound), or an extreme point of the extended real number line. While some alephs are larger than others, ∞ is just ∞. That's a very informal definition of infinity. Taken literally, it's also nonsense, since the real number line has no limit, so talking about the limit of something with no limit is meaningless. So we have to take it loosely. In fact, it isn't true that ∞ is just ∞ even in the two examples they discuss. There are TWO extended real number lines: the projectively extended real numbers, and the affinely extended real numbers. In the projective extension to the reals, there is only one ∞ and it is unsigned. In the affine extension, there are +∞ and -∞. If you identify ∞ as the number of natural numbers, that is, the number of numbers in the sequence 0, 1, 2, 3, 4, ... then that's precisely what aleph(0) is. If there's a limit to the real number line in any sense at all, it is the same limit as for the integers (since the integers go all the way to the end of the real number line). (But note that there are more reals between 0 and ∞ than there are integers, even though both go to the same limit: the reals are more densely packed.) -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Solve a Debate
En Sat, 16 Feb 2008 19:43:37 -0200, John Machin [EMAIL PROTECTED] escribi�: On Feb 16, 3:48 pm, Dan Bishop [EMAIL PROTECTED] wrote: days_in_month = lambda m: m - 2 and 30 + bool(1 m 5546) or 28 Alternatively: days_in_month = lambda m: m - 2 and 31 - ((m + 9) % 12 % 5 % 2) or 28 the guts of which is slightly more elegant than the ancient writing from which it was derived: MOD(MOD(MOD(M+9,12),5),2) I wonder why one would write such arcane expressions [in Python] instead of using a small dictionary {1:31, 2:28, 3:31...} which is auto documented, obviously correct, several times faster, and provides input validation for free (days_in_month(13)?) -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Floating point bug?
On Feb 14, 8:10 pm, Zentrader [EMAIL PROTECTED] wrote: That's a misconception. The decimal-module has a different base (10 instead of 2), and higher precision. But that doesn't change the fact that it will expose the same rounding-errors as floats do - just for different numbers. import decimal as d d = d.Decimal d(1) / d(3) * d(3) Decimal(0.) Surely you jest. He's not joking at all. Your example is exact to 28 digits. Your attempted trick is to use a number that never ends (1/3=0....). It does end in base 3, 6, 9, 12, etc. You have to remember that base-ten wasn't chosen because it has mathematical advantages over other bases, but merely because people counted on their fingers. In light of this fact, why is one-fifth more deserving of an exact representation than one-third is? -- http://mail.python.org/mailman/listinfo/python-list
Re: Turn off ZeroDivisionError?
On Feb 16, 7:08 pm, Steven D'Aprano [EMAIL PROTECTED] cybersource.com.au wrote: On Fri, 15 Feb 2008 17:31:51 -0800, Mark Dickinson wrote: Not sure that alephs have anything to do with it. And unless I'm missing something, minus aleph(0) is nonsense. (How do you define the negation of a cardinal?) *shrug* How would you like to? Since we have generalized the natural numbers to the integers ... -3 -2 -1 0 1 2 3 ... without worrying about what set has cardinality -1, I see no reason why we shouldn't generalize negation to the alephs. The reason is that it doesn't give a useful result. There's a natural process for turning a commutative monoid into a group (it's the adjoint to the forgetful functor from groups to commutative monoids). Apply it to the set of cardinals, leaving aside the set-theoretic difficulties with the idea of the set of cardinals in the first place, and you get the trivial group. There's lots of hand-waving there. I expect a real mathematician could make it all vigorous. Rigorous? Yes, I expect I could. And surreal numbers are something entirely different again. That's a very informal definition of infinity. Taken literally, it's also nonsense, since the real number line has no limit, so talking about the limit of something with no limit is meaningless. So we have to take it loosely. The real line, considered as a topological space, has limit points. Two of them. Mark -- http://mail.python.org/mailman/listinfo/python-list
Re: class static variables and __dict__
On Feb 16, 5:59 pm, Zack [EMAIL PROTECTED] wrote: Zack wrote: Diez B. Roggisch wrote: Zack schrieb: If I have a class static variable it doesn't show up in the __dict__ of an instance of that class. class C: n = 4 x = C() print C.__dict__ {'__module__': '__main__', '__doc__': None, 'n': 4} print x.__dict__ {} This behavior makes sense to me as n is not encapsulated in x's namespace but what method can you use on x to find all available attributes for that class? x.__class__.__dict__ Diez This would leave out any attributes of base classes. Not that I asked for that functionality in my original post but is there a way to get all attributes qualified by x. ? I see that I could walk the dict of x, x.__class__ and x.__class__.__bases__ until I exhaust the tree. But is there a built in method for doing this? I believe this accomplishes what I'm looking for. I'm not positive it is correct or if there are cases I've missed. It would be nice if there is a simple python builtin for finding the fully qualified dict. def fullDict(obj): ''' Returns a dict with all attributes qualified by obj. obj is an instance of a class ''' d = obj.__dict__ # update existing items into new items to preserve inheritance tmpD = obj.__class__.__dict__ tmpD.update(d) d = tmpD supers = list(obj.__class__.__bases__) for c in supers: tmpD = c.__dict__ tmpD.update(d) d = tmpD supers.extend(c.__bases__) return d I know you're probably dumping this for dir(), but I should still warn you: This function modifies the class dictionary, which might not have been what you intended. -- http://mail.python.org/mailman/listinfo/python-list
Re: class static variables and __dict__
Dustan wrote: On Feb 16, 5:59 pm, Zack [EMAIL PROTECTED] wrote: Zack wrote: Diez B. Roggisch wrote: Zack schrieb: If I have a class static variable it doesn't show up in the __dict__ of an instance of that class. class C: n = 4 x = C() print C.__dict__ {'__module__': '__main__', '__doc__': None, 'n': 4} print x.__dict__ {} This behavior makes sense to me as n is not encapsulated in x's namespace but what method can you use on x to find all available attributes for that class? x.__class__.__dict__ Diez This would leave out any attributes of base classes. Not that I asked for that functionality in my original post but is there a way to get all attributes qualified by x. ? I see that I could walk the dict of x, x.__class__ and x.__class__.__bases__ until I exhaust the tree. But is there a built in method for doing this? I believe this accomplishes what I'm looking for. I'm not positive it is correct or if there are cases I've missed. It would be nice if there is a simple python builtin for finding the fully qualified dict. def fullDict(obj): ''' Returns a dict with all attributes qualified by obj. obj is an instance of a class ''' d = obj.__dict__ # update existing items into new items to preserve inheritance tmpD = obj.__class__.__dict__ tmpD.update(d) d = tmpD supers = list(obj.__class__.__bases__) for c in supers: tmpD = c.__dict__ tmpD.update(d) d = tmpD supers.extend(c.__bases__) return d I know you're probably dumping this for dir(), but I should still warn you: This function modifies the class dictionary, which might not have been what you intended. I'm not actually do anything with this, or dir, just messing around learning python (I would use dir instead of this if I had a need though). I had completely missed that I wasn't copying the dicts. Thanks for that catch. -- Zack -- http://mail.python.org/mailman/listinfo/python-list