Re: Fuzzy matching of postal addresses
Andrew McLean wrote: Thanks for all the suggestions. There were some really useful pointers. A few random points: [snip] 4. You need to be careful doing an endswith search. It was actually my first approach to the house name issue. The problem is you end up matching 12 Acacia Avenue, ... with 2 Acacia Avenue, Is that really a problem? That looks like a likely typo to me. I guess it depends on your data set. In my case, the addresses were scattered all over the place, with relatively few in a given city, so the likelyhood of two addresses on the same street in the same town was very low. We /wanted/ to check for this kind of 'duplication'. Note that endswith will not deal with 'Avenue' vs. 'Ave.', but I supose a normalization phase could take care of this for you. The Monge algorithm I pointed you to takes care of this pretty nicely. -- Aaron Bingham Application Developer Cenix BioScience GmbH -- http://mail.python.org/mailman/listinfo/python-list
MDaemon Warning - virus found: Delivery reports about your e-mail
*** WARNING ** Este mensaje ha sido analizado por MDaemon AntiVirus y ha encontrado un fichero anexo(s) infectado(s). Por favor revise el reporte de abajo. AttachmentVirus name Action taken -- message.pif I-Worm.Mydoom.m Removed ** This message was undeliverable due to the following reason: Your message could not be delivered because the destination computer was unreachable within the allowed queue period. The amount of time a message is queued before it is returned depends on local configura- tion parameters. Most likely there is a network problem that prevented delivery, but it is also possible that the computer is turned off, or does not have a mail system running right now. Your message could not be delivered within 3 days: Server 127.15.40.10 is not responding. The following recipients did not receive this message: python-list@python.org Please reply to [EMAIL PROTECTED] if you feel this message to be in error. -- http://mail.python.org/mailman/listinfo/python-list
RE: Print to Windows default Printer
[Samantha] | I am new to Python and I am having considerable trouble | trying to print | (using a simple script) to the default printer rather than the screen. | Thanks for any help. | S It may be that something here will help you: http://tgolden.sc.sabren.com/python/win32_how_do_i/print.html Specifically, I think that the section print raw text is closest to what you're asking (although not necessarily to what you'll eventually want): http://tgolden.sc.sabren.com/python/win32_how_do_i/print.html#win32print TJG This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk -- http://mail.python.org/mailman/listinfo/python-list
RE: Solutions for data storage?
Leif K-Brooks wrote: My ideal solution would be an object database (or object-relational mapper, I guess) which provided total transparency in all but a few places, built-in indexing, built-in features for handling schema changes, the ability to create attributes which are required to be unique among other instances, and built-in querying with pretty syntax. Thanks; I'll add unique indexing to the feature list for Dejavu. Should be about 15 lines of code. :) Try svn://casadeamor.com/dejavu/trunk if you want a truly Pythonic query syntax. Wait a couple of days, and I'll have version 1.3 ready and online at http://www.aminus.org/rbre/python -- lots of changes from 1.2.6 which is there now, but at least you can read old docs online now without svn. Robert Brewer MIS Amor Ministries [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
problem with import pylab from a website
Hello All, I am facing a problem while importing pylab library(in a .py program file) via web browser however the same program works when I execute it from the command prompt. my configuration : Fedora Core 3 Apache 2.0 python 2.3.4 postgresql 7.3.4 mod_python-3.1.3-5 Error message we get: [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] Traceback (most recent call last):, referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] File /var/www/html/sensor_data/get_graph.py, line 15, in ?, referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] , referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] import pylab, referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] File /usr/lib/python2.3/site-packages/pylab.py, line 1, in ?, referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] , referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] from matplotlib.pylab import *, referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] File /usr/lib/python2.3/site-packages/matplotlib/pylab.py, line 184, in ?, referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] , referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] from axes import Axes, PolarAxes, referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] File /usr/lib/python2.3/site-packages/matplotlib/axes.py, line 14, in ?, referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] , referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] from axis import XAxis, YAxis, referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] File /usr/lib/python2.3/site-packages/matplotlib/axis.py, line 20, in ?, referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] , referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] from font_manager import FontProperties, referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] File /usr/lib/python2.3/site-packages/matplotlib/font_manager.py, line 942, in ?, referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] , referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] fontManager = FontManager(), referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] File /usr/lib/python2.3/site-packages/matplotlib/font_manager.py, line 786, in __init__, referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] , referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] rebuild(), referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] File /usr/lib/python2.3/site-packages/matplotlib/font_manager.py, line 780, in rebuild, referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] , referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] pickle.dump(self.ttfdict, file(ttfcache, 'w')), referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] IOError, referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] : , referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] [Errno 13] Permission denied: '/usr/share/matplotlib/.ttffont.cache', referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] , referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] Premature end of script headers: get_graph.py, referer: http://128.178.156.101/sensor_data/readings.php Thanks in advance. Regards, jean -- http://mail.python.org/mailman/listinfo/python-list
Dictionary keys (again) (was Re: lambda)
Antoon Pardon wrote: A rule of thumb is context sensitive. If circumstances change, so do the rules of thumb. Principles have a broader field of application. IMO there is nothing principally wrong with using a mutable object as a dictionary key. But avoiding doing so is a good rule of thumb if you have a python-like implementation of a dictionary. For a 'mutable key' to make sense, the following: lst = [] dct = {l: Hi!} print dct[[]] print dct[lst] lst.append(1) print dct[[1]] print dct[lst] Should print: Hi Hi Hi Hi That's completely impractical though - for any sane implementation, at least one of the above print statements will throw a KeyError. Your example of a 'safe_dict' that copies mutable keys means that the final print statement is the one that fails. My suggestion of an identity_dict means that both of the same-value based lookups would fail. Notice that both of these approaches take a mutable key and make it immutable (either by holding the sole reference to a copy, or retrieving an immutable property of the mutable object). There's also your solution of I promise not to mutate the key while it is in the dictionary. Workable, but opens the door to some entertaining bug hunts when the promise is broken. Which solution is the best default behaviour? Well, the Zen of Python states In the face of ambiguity, refuse the temptation to guess. So that's the policy the builtin dict follows - it doesn't try to guess when to make a copy, or whether or not to use identity based semantics in the face of mutability. Instead, it raises an exception at key entry time, asking the programmer to clarify their intent. The principle is *certainly* that hash tables should contain immutable keys. Your own 'safe_dict' example implicitly concedes this point by making copies 'when required'. 'When required' for what? When required to preserve immutability, perhaps? In short, sane hash tables require immutable keys, and how mutable keys acquire the requisite immutability is going to be application dependent. Provision of a safe_dict or identity_dict would merely allow a programmer to state their intent at the time the container is created, rather than having to state it whenever keys are generated or referenced. Cheers, Nick. -- Nick Coghlan | [EMAIL PROTECTED] | Brisbane, Australia --- http://boredomandlaziness.skystorm.net -- http://mail.python.org/mailman/listinfo/python-list
python iges (nurbs file format)
Is anyone aware of a module allowing you to read / write .iges data? Currently Im trying to figure a way of writing out my nurbs data generated in python, but if such a package exists, that would be great, havent been able to find anything so far Cheers, Jelle. -- http://mail.python.org/mailman/listinfo/python-list
Re: lambda
Op 2005-01-18, David Bolen schreef [EMAIL PROTECTED]: Antoon Pardon [EMAIL PROTECTED] writes: Op 2005-01-18, Simon Brunning schreef [EMAIL PROTECTED]: On 18 Jan 2005 07:51:00 GMT, Antoon Pardon [EMAIL PROTECTED] wrote: 3 mutating an item in a sorted list *does* *always* cause problems No, it doesn't. It might cause the list no longer to be sorted, but that might or might no be a problem. Than in the same vain I can say that mutating a key in a dictionary doesn't always cause problems either. Sure it may probably make a key unaccessible directly, but that might or might not be a problem. Well, I'd definitely consider an inaccessible key as constituting a problem, but I don't think that's a good analogy to the list case. With the dictionary, the change can (though I do agree it does not have to) interfere with proper operation of the dictionary, while a list that is no longer sorted still functions perfectly well as a list. I think we are talking past each other. I'm talking about the concept the programmer has in his mind. If the prgrammer has a sorted list in his mind and an element in that list gets mutated that *does* *always* cause problems. I'm not talking about a list in which the elements happen to be in a particular order, but about a list that will be given to algorithms that depend on the list being ordered. That is, I feel problems are more guaranteed with a dictionary since we have affected base object behavior, whereas sorted is not an inherent attribute of the base list type but something the application is imposing at a higher level. But if the program uses one of the buildin sorts, isn't it then obvious that this is an inherent attribute we want to impose? So is sorting a list with mutable object not also more guaranteed to cause problems. So shouldn't we limit the sort algorithms to containers with immutable elements? For example, I may choose to have an object type that is mutable (and not worthy for use as a dictionary key) but maintains a logical ordering so is sortable. I see no problem with sorting a list of such objects, and then walking that list to perform some mutation to each of the objects, even if along the way the mutation I am doing results in the items so touched no longer being in sorted order. The act of sorting was to provide me with a particular sequence of objects, Personnaly I don't see what the sorting was good for in this case. And I think such programming might be slightly dangerous if you cooperate with other people. They may not understand the particular nature of your mutation and rely on the fact that your list has been sorted to conclude that it still is sorted. but aside from that fact, the list continues to perform perfectly well as a list even after the mutations - just no longer delivering objects in sorted order. Which may be a problem for those who rely on it. -- Antoon Pardon -- http://mail.python.org/mailman/listinfo/python-list
Re: Dictionary keys (again) (was Re: lambda)
In article [EMAIL PROTECTED], Nick Coghlan [EMAIL PROTECTED] wrote: Antoon Pardon wrote: A rule of thumb is context sensitive. If circumstances change, so do the rules of thumb. Principles have a broader field of application. IMO there is nothing principally wrong with using a mutable object as a dictionary key. But avoiding doing so is a good rule of thumb if you have a python-like implementation of a dictionary. For a 'mutable key' to make sense, the following: lst = [] dct = {l: Hi!} print dct[[]] print dct[lst] lst.append(1) print dct[[1]] print dct[lst] Should print: Hi Hi Hi Hi That's completely impractical though - for any sane implementation, at least one of the above print statements will throw a KeyError. Your example of a 'safe_dict' that copies mutable keys means that the final print statement is the one that fails. My suggestion of an identity_dict means that both of the same-value based lookups would fail. Notice that both of these approaches take a mutable key and make it immutable (either by holding the sole reference to a copy, or retrieving an immutable property of the mutable object). There's also your solution of I promise not to mutate the key while it is in the dictionary. Workable, but opens the door to some entertaining bug hunts when the promise is broken. Which solution is the best default behaviour? Well, the Zen of Python states In the face of ambiguity, refuse the temptation to guess. So that's the policy the builtin dict follows - it doesn't try to guess when to make a copy, or whether or not to use identity based semantics in the face of mutability. Instead, it raises an exception at key entry time, asking the programmer to clarify their intent. The principle is *certainly* that hash tables should contain immutable keys. Your own 'safe_dict' example implicitly concedes this point by making copies 'when required'. 'When required' for what? When required to preserve immutability, perhaps? In short, sane hash tables require immutable keys, and how mutable keys acquire the requisite immutability is going to be application dependent. Provision of a safe_dict or identity_dict would merely allow a programmer to state their intent at the time the container is created, rather than having to state it whenever keys are generated or referenced. FWIW, the Cocoa framework on OSX supports mutable objects as keys. However, it makes an immutable copy. This is cheap for immutable objects -- Cocoa has both a mutable array as well as an immutable array, likewise for dicts -- since the copy will then simply be the same object. Thanks to PyObjC we can explore this from Python: Python 2.3 (#1, Sep 13 2003, 00:49:11) [GCC 3.3 20030304 (Apple Computer, Inc. build 1495)] on darwin Type help, copyright, credits or license for more information. from Foundation import * lst = [] dct = NSMutableDictionary.alloc().init() dct {} dct[lst] = Hi! dct {(1) = Hi!; } (Note that Python lists get wrapped as native Cocoa arrays. '(1)' is Cocoa's repr for the wrapped array.) dct[lst] u'Hi!' lst.append(1) dct[lst] Traceback (most recent call last): File stdin, line 1, in ? File build/lib.darwin-7.6.0-Power_Macintosh-2.3/objc/_convenience.py, line 77, in __getitem__objectForKey KeyError: [1, 1] dct.keys() ((1)) dct[[1]] u'Hi!' k = dct.keys()[0] k (1) k.append(2) Traceback (most recent call last): File stdin, line 1, in ? File build/lib.darwin-7.6.0-Power_Macintosh-2.3/objc/_convenience.py, line 205, in lambda objc.error: NSInternalInconsistencyException - *** -[NSCFArray addObject:]: mutating method sent to immutable object This is not all that different from Python actually, in that Cocoa tries very hard to make it impossible to mutate dict keys. Just -- http://mail.python.org/mailman/listinfo/python-list
Re: safest way to kill a thread
Great thank for your helping. Should the 'daemonic' flag at setDaemon() function set to 1/TRUE or 0/FALSE to do such action? limodou wrote: I think only those threads which invoked with setDaemon() method will exit, and others will not, as the main program exit. -- http://mail.python.org/mailman/listinfo/python-list
Re: lambda
Op 2005-01-18, Bengt Richter schreef [EMAIL PROTECTED]: On 18 Jan 2005 13:28:00 GMT, Antoon Pardon [EMAIL PROTECTED] wrote: I have implemented a hash table when I was a student and its implementation allowed the use of 'mutable' objects as a key without a problem. It simply always made copies when appropiate and didn't allow external access to the keys. So although the key objects were 'mutable' there was no way a user could accidently mutate a key. This is word play IMO. What you describe is effectively using the mutables to construct immutable keys for actual use, not using immutable keys. No it is not wordplay. There is a difference between inaccessible and immutable. The difference is that the user can mutate his own objects which he wants to use as a key, which wouldn't be the case if he was using immutables as keys. Having the immutable (because of access restriction) constructed keys allows you to check on their consistency with their source any time you want, but that doesn't change the fact that you have created an alternative dictionary implementation with immutable keys made immutable by copying and access restriction. If you update your dictionary when a key no longer matches its source data, you are just deleting an immutable-by-special-means key and entering the associated value in association with a new immutable-by-special-means key. The immutable vs mutable as keys IMO refers to the class the key belongs to. Not the accessibiliy of individual instances. So don't use a mutable as a dictionary key isn't so much a dictionary limitation in general but a specific limitation of the python implementation. And yes I understand, the current implenatation is the result of the fact that the same dictionaries are used internally for variables in scopes and attributes in objects and the fact that no copies are involved gives a boost to performance. But it could be argued that providing these same dictionaries with those semantics to the users was a premature optimisation. If you see a sign like +- | WILD GOOSE CHASE THIS WAY- +- || ||\|/ ||=o= ||/|\ .`.||,..__|_,. Do you feel that you must make sure? Talk to my wife. She regularly complains that I don't accept her word often enough on what she says. :-) The sign painter may only be indicating what his own experience was, after all. But if it was a core developer's experience, it may be prudent to bet on another trail -- unless you have an extremely interesting hunch. Then you should follow your passion and have your own experience, and you may wind up being able to contribute something (even if only an exclamation point on the sign ;-) When stating useful general principles, it is never, ever worth it to get into the quibbly little details about exceptions to the principle. If students ask, admit that they exist, but point out that the exceptions are rare, and not worth worrying about at that point in their learning. But don't use mutable keys is not a general principle. It is a principle introduced by the limitations of the python implementations. That is so in your mind, and it is so given certain interpretations of the words you are using, As far as I understand I using them in a standard python interpretation. but to others mutable keys may be a contradiction in terms, because they do not use the words in the same sense as you. I don't think so. I have seen defenders of only immutables as keys, use the argument that using mutables as keys would require a copy of the key. Therefore using only immutables allows for optimisations in the implementation. I saw nothing in there discourse that implied they saw this copy as immutable. If you can't see alternative conceptual constructs you are stuck, and if we can't agree on the meaning of words for a given dialog, we won't be communicating very well. The difficulty is getting people to recognize their implicit assumptions and definitions ;-) I can be wrong, but until now I have seen no indication that I was using mutable and immutable differently than other people. AFAICT we all refer to whether an object belongs to a mutable or immutable class. I don't like it when a good rule of thumb because of implementation limitations is sold as a general principle. People take short cuts in expressing themselves, just as you do. E.g., you say mutable key when you really mean a value that will remain constant while you are using it as a dictionary key. What I mean is a key that belongs to a mutable class. Whether I actually mutate it in certain circumstances or not doesn't change that. I also don't want my values to change when I have sorted a list and still need to apply a number of algorithms that rely on that. Nobody seems to have problems with the possibility that the list items are mutable (and called such). -- Antoon
Re: File objects? - under the hood question
On Tue, 18 Jan 2005 22:53:10 -0800, Eric Pederson wrote: Perhaps I've answered my question and the under-the-hood mechanics are handled on the OS side, and Python is just making requests of the OS... Almost by definition, the only correct way to read a file is to use the file system, which on current operating systems means going the the OS kernel. My brain-teaser: What I'd like to do is read the last ~2K of a large number of large files on arbitrary servers across the net, without having to read each file from the beginning (which would be slow and resource inefficient)... Across the net is not specific enough. There are generally ways to do that, subject to the support of the various relevant servers, but what protocol are you talking about using? HTTP? FTP? NFS? Generally you issue some sort of command to get the length, then some sort of seek or continuation command to get to the end, but the details are different for each protocol. (Unless someone has a convenient flattening library around? I have something almost like that in my personal collection except I have no intention of supporting seek behavior for various technical reasons.) And note that with the possible exception of that last one, there is no relationship between these two questions. (Maybe you know that, maybe you don't. :-) ) There is no argument you can pass to file() that will read an HTTP file. (Pedants may note this isn't an absolute truth but it's true enough that it's not worth sweating the details if you're still working out what file() does.) -- http://mail.python.org/mailman/listinfo/python-list
Re: python/cgi/html bug
On Tue, 18 Jan 2005 21:50:58 -0800, Dan Bishop wrote: Dfenestr8 wrote: Hi. I've written a cgi messageboard script in python, for an irc chan I happen to frequent. Bear with me, it's hard for me to describe what the bug is. So I've divided this post into two sections: HOW MY SCRIPTS WORKS, and WHAT THE BUG IS. ... The problem is when someone posts a new topic, and that topic happens to have double quotes, or any other strange character, some strange glitches occur. Use cgi.escape(topic, True) to convert HTML special characters to the equivalent ampersand escape sequences. Thanx. Seems to work now. :) -- http://mail.python.org/mailman/listinfo/python-list
Re: generator expressions: performance anomaly?
Stephen Thorne wrote: On Tue, 18 Jan 2005 23:09:57 -0700, Steven Bethard [EMAIL PROTECTED] wrote: @with_consts(i=1, deftime=time.ctime()) def foo(x, y=123, *args, **kw): return x*y, kw.get('which_time')=='now' and time.ctime() or deftime Then you don't have to mix parameter declarations with locals definitions. [1] I have no idea how implementable such a decorator would be. I'd just like to see function constants declared separate from arguments since they mean such different things. (untested) def with_constant(**constants_kwargs): def decorator(f) def closure(*arg, **kwargs): kwargs.update(constants_kwargs) return f(*arg, **kwargs) return closure return decorator This doesn't quite work because it still requires that f take the constants as parameters: py def with_constant(**constants_kwargs): ... def decorator(f): ... def closure(*arg, **kwargs): ... kwargs.update(constants_kwargs) ... return f(*arg, **kwargs) ... return closure ... return decorator ... py @with_constant(x=1) ... def f(y): ... return x + y ... py f(1) Traceback (most recent call last): File interactive input, line 1, in ? File interactive input, line 5, in closure TypeError: f() got an unexpected keyword argument 'x' I screwed around for a while with: ctypes.pythonapi.PyFrame_LocalsToFast(ctypes.py_object(frame), 0) which will let you propagate updates made to frame.f_locals, but only if you don't *add* any locals to the frame, as far as I can tell: py def f(x=1): ... frame = sys._getframe() ... frame.f_locals[x] = 2 ... print x ... py f() 1 py def f(x=1): ... frame = sys._getframe() ... frame.f_locals[x] = 2 ... ctypes.pythonapi.PyFrame_LocalsToFast( ... ctypes.py_object(frame), 0) ... print x ... py f() 2 py def f(x=1): ... frame = sys._getframe() ... frame.f_locals[y] = 2 ... ctypes.pythonapi.PyFrame_LocalsToFast( ... ctypes.py_object(frame), 0) ... print y ... py f() Traceback (most recent call last): File interactive input, line 1, in ? File interactive input, line 6, in f NameError: global name 'y' is not defined Steve -- http://mail.python.org/mailman/listinfo/python-list
IronPython, Boo and ASP.NET (web service)
Is there any way for preparing a simple web service (ASP.NET) using IronPython or Boo (http://boo.codehaus.org/)? I cannot find any example. C# uses [WebMethod] attribute for marking remote methods. I do not know how IronPython or Boo deals with it. -- JZ ICQ:6712522 http://zabiello.com -- http://mail.python.org/mailman/listinfo/python-list
Re: generator expressions: performance anomaly?
Op 2005-01-18, Jeremy Bowers schreef [EMAIL PROTECTED]: On Tue, 18 Jan 2005 14:05:15 +, Antoon Pardon wrote: I don't see how generating byte code for a = 9; when seeing the expression a = 3 + 6, would be a problem for non-functional languages. To answer nearly every post you've made to this thread, because Python doesn't have the resources to program to special cases. I was countering an argument that seemed to state doing something like that was impossible on principle in python. I was not argueing people should put any effort in this, just countering it would change python beyond recognition. Ultimately, the use is fairly limited; I can't imagine the execution time saved would reach the time of implementation for weeks after a release, even aggregating across all Python use in the world, and real time gained (i.e., time useful to a human) would probably never add up to the implementation time. So why bother? That's a horrid trade off when there are so many other real gains to be had. Well if it isn't worth the bother, so be it. I can still dream about it. -- Antoon Pardon -- http://mail.python.org/mailman/listinfo/python-list
Re: lambda
Antoon Pardon wrote: I can be wrong, but until now I have seen no indication that I was using mutable and immutable differently than other people. AFAICT we all refer to whether an object belongs to a mutable or immutable class. The difference is that when you take a copy of the key and stick it in the dictionary, such that the dictionary now holds the *sole* reference to that key, you have made that key *effectively* immutable. This is why no-one really batted an eyelid when you mentioned that mutable keys can be used safely by making a copy - doing so makes the key *effectively* immutable, and means that modifying the original key object (i.e. the application's copy, not the dict's copy), and reusing it to look up in the dictionary is likely to give a KeyError. These semantics would be understandably surprising to many users, and hence, are not supplied by default. Additionally, a dictionary's keys are accessible via its API. Accordingly, to preserve this 'effective immutability', making a copy on key input is insufficient - keys must be copied on *output* as well (that is, dict.keys, dict.items etc must return *copies* of the key objects, not the key objects themselves). Since there is no reliable way in Python to tell if an object is mutable or not (the closest equivalent is the presence of __hash__, which clearly can't be used in this example), this copying would need to be done for *every* object. Alternately, the dictionary can say to the API clients, make an immutable copy and supply that instead. It is left to API clients to decide how best to make the immutable version. The API client copies the key once (to make the immutable version), and everyone lives happily ever after. For example: Py class mylist(list): ... def __init__(self, arg): ... super(mylist, self).__init__(arg) ... self._tuple = None ... def frozen(self): ... if self._tuple is None: ... self._tuple = tuple(self) ... return self._tuple ... def unfreeze(self): ... self._tuple = None ... Py x = mylist(range(10)) Py x [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] Py x.frozen() (0, 1, 2, 3, 4, 5, 6, 7, 8, 9) Py x.append(10) Py x.frozen() (0, 1, 2, 3, 4, 5, 6, 7, 8, 9) Py x.unfreeze() Py x.frozen() (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10) This is much safer than having a list subclass that implements __hash__, and still lets you avoid redundant copy operations. Nicely, so long as you don't unfreeze the object you used to key the dictionary, reusing the same object will always get you the correct dictionary entry, and two lists that compare equal at the time they are frozen will also get you the same dictionary entry. The equivalent tuples can be used for the lookup, too. I also don't want my values to change when I have sorted a list and still need to apply a number of algorithms that rely on that. Nobody seems to have problems with the possibility that the list items are mutable (and called such). OK, to make this comparison of sorted lists and dictionaries fair: Write a sorted_list class that is like a regular Python list, but maintains as an invariant that the list contents will stay sorted. See how well you go maintaining that invariant while allowing mutable objects in the list. The only way would be to copy them in when they're supplied, and copy them out again when you're done. Otherwise, there is no way the class can keep its promise. The performance will be lousy, since __setitem__ and __getitem__ will be making copies all the time. Alternatively, the class could declare itself to work reliably only with immutable objects. Performance will improve, since copies need only be made when an object *actually* changes (and the old immutable copy is deleted and the new version inserted in its place). Cheers, Nick. -- Nick Coghlan | [EMAIL PROTECTED] | Brisbane, Australia --- http://boredomandlaziness.skystorm.net -- http://mail.python.org/mailman/listinfo/python-list
Re: generator expressions: performance anomaly?
Op 2005-01-18, Steve Holden schreef [EMAIL PROTECTED]: Antoon Pardon wrote: Op 2005-01-18, Steve Holden schreef [EMAIL PROTECTED]: Python is *designed* as a dynamic language. I wish you would embrace this aspect rather than continually trying to shoehorn it into a static straitjacket. Efficiency is good. Flexibility is better. Flexibility is better? IMO flexibilty implies more than one way to do things. But that is a big no no here in c.l.py. Become one with the language. That is difficult if I hear so many contradictionary things about it. Sometimes I have the feeling that the Zen of python is more for poet like people, not for the extreme analytical kind, like me. I also see a lot of remarks that go: Don't do this! when some of the more dynamic aspects are talked about, because there are security risks involved. One of the results was that I ended up writing a parser for some kind of game instead of just dumping the structure in textual form and doing an eval of the file when reading it in. But if I need a parser I could just as well used a static language. Wow, you mean you actually *took* some advice? :-) Perhaps this whole thing has arisen because you feel you were badly advised. It looks as though your programming skill level might have been underestimated. Your ability to wring an argument to a merciless death could never be. Again the problem is the many contradictionary arguments I get from this group. My impression is that any time I do a suggestion here or make a remark sooner or later someone will quote one of the rules of python and will consider the matter closed by that. But those rules can be used to support or reject any proposition. If someone proposes to introduce an exception, the rule quoted is: No exception is so importan to break the rule. If someone proposes to make python more consistent, the rule quoted is: practicallity beats purity. So in the end I get the feelings that the strengths of arguments doesn't matter here. If someone doesn't like a proposition, he just looks for the rule it will break (and since the rules contradict each other he will find one) and produce it as the final argument for why the proposal won't work. I'm beginning to guess the dynamic aspect of python is overrated. You shouldn't have to guess, and it isn't. Certain of its dynamic aspects do demand a certain care rather than casual usage, however, which leads to rules of thumb like don't use mutables as dictionary keys. Yes, of course you can, but to a newbie your behavior (it seems to me) is a bit like this: But I am not talking to newbees. I am talking about documentation that is in the language reference and things that I'm told. If it would just be the tutorial and like wise documents that stated to not use mutables as dictionary keys I could live with that. But if the language reference suggest the same you can no longer claim it is for the newbee's sake. Me (to newbie): ... And, of course, you want to be careful not to shoot yourself in the foot. You: :Well, actually, if you use a .22 and aim very carefully between the big toe and its neighbor there's a 96% chance that you will only suffer serious burns. So, please understand, I'm not trying to say that (most of) your utterances are untrue, or question your knowledge of the Python environment. I'm just trying to bring the day closer when you will be able to watch me write something that's only 99% true and happily walk away without writing a thousand-word essay on the remaining 1% case. Well the problem may be I don't consider the person you are talking to as a newbee. Just the fact that he asks a question that marks him as a newbee in python doesn't mean he is a newbee programmer. But you do have a point that I have a tendency to put salt on any snail. I'll try to restrain myself a bit more in the future. -- Antoon Pardon -- http://mail.python.org/mailman/listinfo/python-list
Re: rotor replacement
Robin Becker [EMAIL PROTECTED] writes: Paul Rubin wrote: .I'm also missing the rotor module and regret that something useful was warned about and now removed with no plugin replacement. Hm, yes. Here is a (rather slow) replacement: This module is derived from Modules/rotormodule.c and translated into Python. I have appended the Copyright by Lance Ellinghouse below. The rotor module has been removed from the Python 2.4 distribution because the rotor module uses an insecure algorithm and is deprecated. == Of course, this does still hold. However, I think this module might be used and adapted for demonstration purposes and might help some poor users who have encrypted (or obfuscated) some old stuff with the rotor module and have no access to older Python versions any more. Documentation can be found in Python Library Reference, Guido van Rossum, Fred L. Drake, Jr., editor, PythonLabs, Release 2.3.4 May 20, 2004 http://www.python.org/doc/2.3.4/lib/module-rotor.html # Copyright 1994 by Lance Ellinghouse, Cathedral City, California Republic, United States of America. All Rights Reserved Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of Lance Ellinghouse not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. LANCE ELLINGHOUSE DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL LANCE ELLINGHOUSE BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. # class newrotor(object): def __init__(self, key, n_rotors=6): self.n_rotors = n_rotors self.setkey(key) def setkey(self, key): self.key = key self.rotors = None self.positions = [None, None] def encrypt(self, buf): # Reset (encrypt) positions and encryptmore self.positions[0] = None return self.cryptmore(buf, 0) def encryptmore(self, buf): return self.cryptmore(buf, 0) def decrypt(self, buf): # Reset decrypt positions and decryptmore self.positions[1] = None return self.cryptmore(buf, 1) def decryptmore(self, buf): return self.cryptmore(buf, 1) def cryptmore(self, buf, do_decrypt): size, nr, rotors, pos = self.get_rotors(do_decrypt) outbuf = [] append = outbuf.append for c in map(ord, buf): if do_decrypt: # Apply decrypt rotors and xor in reverse order for i in xrange(nr-1,-1,-1): c = pos[i] ^ rotors[i][c] else: # Apply xor and ecrypt rotors for i in xrange(nr): c = rotors[i][c ^ pos[i]] append(c) # Advance rotors, i.e. add the (fixed) rotor increments to the # variable rotor positions with carry. # Note: In the C-implementation, the result of the carry addition #was stored to an unsigned char. Hence the next carry #is lost if pos[i] == size-1 and pnew = size. #Masking with 0xff simulates this behavior. # pnew = 0 # (pnew = size) works as carry bit for i in xrange(nr): pnew = ((pos[i] + (pnew = size)) 0xff) + rotors[i][size] pos[i] = pnew % size return ''.join(map(chr, outbuf)) def get_rotors(self, do_decrypt): # Return a tuple (size, nr, rotors, positions) where # - size is the rotor size (== 256, because of 8-bit bytes) # - nr is the number of rotors. # - rotors is a tuple of nr encrypt or nr decrypt rotors # for do_decrypt == 0 or do_decrypt == 1 respectively. # - postions is a list of nr rotor positions. # # The rotors represent the static aspect of the rotor machine which # is initially computed from key and fixed during en/decryption. # A rotor is a random permutation of range(size) extended # by an increment value in range(size). # # The followng statements hold for a tuple of encrypt rotors E and
delay and force in Python
Here is a question for people who are more comfortable than I am with new Python stuff like generators. I am having fun implementing things from the Wizard book (Abelson, Sussman, Structure and Interpretation of Computer Programs) in Python. In chapter 3.5 it is about streams as delayed lists. Streams are interesting because they are to lists like xrange is to range. Could save a lot on memory and computations. Below is my straight translation from Scheme code in the Wizard book to Python. It works, but now I want to rewrite the delay and force functions using Python's new stuff, generators or iterators or what-have-you. I have the feeling that that is possible, can you do it? The program below creates a stream with the numbers 1..995 and then filters the stream, keeping only the even numbers, and then prints the second number in the stream (implemented as the first number of the tail, just like in the 3.5 Section in the Wizard book). . # file: teststreams.py . . def delay(exp): return lambda: exp . . def force(o): return o() . . def cons_stream(a,b): return [a, delay(b)] . . def stream_hd(s): return s[0] . . # we use tl for cdr . def tl(x): . if len(x) == 2: return x[1] . else: return x[1:] . . def stream_tl(s): return force(tl(s)) . . def stream_enumerate_interval(low, high): . if low high: . return None . else: . return cons_stream( . low, . stream_enumerate_interval(low+1, high)) . . def stream_filter(pred, s): . if s is None: . return None . elif pred(stream_hd(s)): . return cons_stream( . stream_hd(s), . stream_filter(pred, stream_tl(s))) . else: . return stream_filter(pred, stream_tl(s)) . . def isEven(n): return n % 2 == 0 . . print stream_hd(stream_tl(stream_filter( . isEven, . stream_enumerate_interval(1,995 . # 4 Something else: this crashes with a maximum recursion reached . print stream_enumerate_interval(1,998) while this does not crash . print stream_enumerate_interval(1,900) this means Python has a maximum of something like 900 recursions? -- http://mail.python.org/mailman/listinfo/python-list
Re: delay and force in Python
Will Stuyvesant wrote: Streams are interesting because they are to lists like xrange is to range. Could save a lot on memory and computations. I think you're looking for generators. Below is my straight translation from Scheme code in the Wizard book to Python. Something else: this crashes with a maximum recursion reached . print stream_enumerate_interval(1,998) Unlike Scheme, Python isn't designed for heavily recursive algorithms. Here's a more Pythonic equivalent of your code: def count(start, stop): i = start while i stop: yield i i += 1 def even(gen): for x in gen: if x % 2 == 0: yield x numbers = even(count(1, 999)) first = numbers.next() second = numbers.next() print second -- Benji York [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: delay and force in Python
Will Stuyvesant wrote: The program below creates a stream with the numbers 1..995 and then filters the stream, keeping only the even numbers, and then prints the second number in the stream (implemented as the first number of the tail, just like in the 3.5 Section in the Wizard book). How's this: Py from itertools import islice Py print islice((x for x in xrange(1, 996) if x % 2 == 0), 1, 2).next() 4 Breaking it into pieces: Py from itertools import islice Py stream = (x for x in xrange(1, 996) if x % 2 == 0) Py second_item = islice(stream, 1, 2).next() Py print second_item 4 And most of the stream hasn't been consumed yet: Py print stream.next() 6 Py unconsumed = list(stream) Py len(unconsumed) 494 And this version has no problem with recursion limits: Py print islice((x for x in xrange(1, sys.maxint) if x % 2 == 0), 1, 2).next() 4 (xrange can't handle Python longs, unfortunately, so we *are* constrained by sys.maxint. However, since my machine only has half a gig of RAM, the above is still a damn sight quicker than the equivalent list comprehension would be!) Something else: this crashes with a maximum recursion reached . print stream_enumerate_interval(1,998) while this does not crash . print stream_enumerate_interval(1,900) this means Python has a maximum of something like 900 recursions? The CPython implementation is limited by the stack size allocated by the C runtime library. The exact recursion limit is platform dependent, but something around 1000 sounds fairly normal. Cheers, Nick. -- Nick Coghlan | [EMAIL PROTECTED] | Brisbane, Australia --- http://boredomandlaziness.skystorm.net -- http://mail.python.org/mailman/listinfo/python-list
Re: rotor replacement
Robin Becker [EMAIL PROTECTED] writes: What exactly are/were the political reasons for rotor removal? Some countries have laws about cryptography software (against some combination of export, import, or use). The Python maintainers didn't want to deal with imagined legal hassles that might develop from including good crypto functions in the distribution. Then it became obvious that the same imagined hassles could also befall the rotor module, so that was removed. I might add that the source for rotormodule is still easily obtainable and can be compiled trivially as an extension for Python-2.4. Does the Python community take a position on the sources of removed modules? Those are still free to distribute, but I'd advise against doing so with the rotor module unless you absolutely need it for some interoperability purpose. Otherwise, it's insecure and should not be used. The routine I posted was intended as a straightforward replacement for the rotor module that doesn't depend on C compilers and is reasonably secure. If you don't mind using C extensions, there's various AES modules available, plus fancier packages like mxCrypto. -- http://mail.python.org/mailman/listinfo/python-list
Re: simultaneous multiple requests to very simple database
On Tue, Jan 18, 2005 at 11:26:46AM -0500, Eric S. Johansson wrote: I have an application where I need a very simple database, effectively a very large dictionary. The very large dictionary must be accessed from multiple processes simultaneously. I need to be able to lock records within the very large dictionary when records are written to. Estimated number of records will be in the ballpark of 50,000 to 100,000 in his early phase and 10 times that in the future. Each record will run about 100 to 150 bytes. speed is not a huge concern although I must complete processing in less than 90 seconds. The longer the delay however the greater number of processes must be running parallel in order to keep the throughput up. It's the usual trade-off we have all come to know and love. it is not necessary for the dictionary to persist beyond the life of the parent process although I have another project coming up in which this would be a good idea. at this point, I know they will be some kind souls suggesting various SQL solutions. While I appreciate the idea, unfortunately I do not have time to puzzle out yet another component. Someday I will figure it out because I really liked what I see with SQL lite but unfortunately, today is not that day (unless they will give me their work, home and cell phone numbers so I can call when I am stuck. ;-) I'm sure we could agree on a fee for me to do so :) So the solutions that come to mind are some form of dictionary in shared memory with locking semaphore scoreboard or a multithreaded process containing a single database (Python native dictionary, metakit, gdbm??) and have all of my processes speak to it using xmlrpc which leaves me with the question of how to make a multithreaded server using stock xmlrpc. berkley db (at least version 3, http://pybsddb.sourceforge.net/) supports multiple readers and writers, with fine-grained locking, it looks like a dictionary, and it isn't sql. The use you have in mind is a bit more complicated than the simple create-me-a-dictionary-in-a-file, but is pretty straightforward. The documentation mostly refers you to the C API, but fortunately it (the C API) is clear and well written. HTH -- John Lenton ([EMAIL PROTECTED]) -- Random fortune: Today is National Existential Ennui Awareness Day. signature.asc Description: Digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: rotor replacement
Robin Becker [EMAIL PROTECTED] wrote: Paul Rubin wrote: Reed L. O'Brien [EMAIL PROTECTED] writes: I see rotor was removed for 2.4 and the docs say use an AES module provided separately... Is there a standard module that works alike or an AES module that works alike but with better encryption? If you mean a module in the distribution, the answer is no, for political reasons. .I'm also missing the rotor module and regret that something useful was warned about and now removed with no plugin replacement. I had understood that this was because rotor was insecure, but you mention politics. Are other useful modules to suffer from politics? What exactly are/were the political reasons for rotor removal? Presumably he is talking about crypo-export rules. In the past strong cryptography has been treated as munitions, and as such exporting it (especially from the USA) could have got you into very serious trouble. However I believe those restrictions have been lifted (the cat having been let out of the bag somewhat ;-), and its easy to do this for open source encryption software. A wade through http://www.bxa.doc.gov/Encryption/enc.htm Might be interesting. A case in point: the linux 2.6 kernel is chock full of crypo and comes with implementations of AES, ARC4, Blowfish, Cast5+6, DES, Serpent, Twofish, TEA, etc. The linux kernel+source surely goes everywhere python does so I don't think adding strong crypto modules to python is a problem now-a-days. AES in the core python library would be very useful and it would discourage people from writing their own crypto routines (looks easy but isn't!) -- Nick Craig-Wood [EMAIL PROTECTED] -- http://www.craig-wood.com/nick -- http://mail.python.org/mailman/listinfo/python-list
Re: how to find site-packages path (Michael Hoffman) - use distutils
Philippe C. Martin wrote: I actually target Unix and windows so pyexe won't cut it I'm afraid - same issue with Inno. As far as the site-package target, I don't fully understand your relunctancy. Just as my potential users might not own a compiler, they might not be computer proficient enough to easily understand how to change the sys.path. So until I have found a clean cross platform solution I'm going to have to stick to site-packages. Hi Philippe You may want to have a look at https://sourceforge.net/tracker/?func=detailatid=305470aid=793070group_id=5470 This was originally a patch to distutils which enabled removing the source (i.e. only distributing compiled files). I have now attached a file there which enables you to do the same thing, but without patching distutils - it just wraps functions etc from outside. Basically you call allow_distutils_remove_source in the module and it does the neccessary changes. Then you get a --remove-source options to most of the commands. You can also selectively override what gets removed if you want by changing the is_removable function I hope this is useful for what you're wanting to do David -- http://mail.python.org/mailman/listinfo/python-list
mod_python friendly isps in europe
Hello everybody I'm thinking about improving my web site scripts and would like to use Python instead of PHP/Perl. Does anyone know of mod_python friendly ISPs in europe? With prices around 10€ ? Thanks in advance, Paulo -- http://mail.python.org/mailman/listinfo/python-list
Automatic response to your mail (Error)
The automatic reply to this e-mail which you should have received in response to your e-mail to [EMAIL PROTECTED] has not been defined. Please contact [EMAIL PROTECTED] for assistance. -- http://mail.python.org/mailman/listinfo/python-list
Re: how to find site-packages path (Michael Hoffman) - use distutils/modified
Thanks David. Philippe Hi Philippe You may want to have a look at https://sourceforge.net/tracker/?func=detailatid=305470aid=793070group_id=5470 This was originally a patch to distutils which enabled removing the source (i.e. only distributing compiled files). I have now attached a file there which enables you to do the same thing, but without patching distutils - it just wraps functions etc from outside. Basically you call allow_distutils_remove_source in the module and it does the neccessary changes. Then you get a --remove-source options to most of the commands. You can also selectively override what gets removed if you want by changing the is_removable function I hope this is useful for what you're wanting to do David -- *** Philippe C. Martin SnakeCard LLC www.snakecard.com *** -- http://mail.python.org/mailman/listinfo/python-list
Re: generator expressions: performance anomaly?
Paul Rubin wrote: Steve Holden [EMAIL PROTECTED] writes: You probably already know that sensible compiled language systems have used constant folding since time immemorial, but Python has always eschewed it. That's what comes of being a pragmatist's language: if such optimizations really are required the programmer is expected to perform them. You mean the lack is deliberate? I just figured it was an artifact of the implementation and that PyPy had some reasonable chance of fixing it. No, it's not been deliberately omitted, it's just not a development priority. Pragmatic Python programmers are prepared to do the folding themselves in the (exceptionally rare) cases where it has a significant effect on performance. PyPy may or may not fix it. And, of course, a dynamic language has rather less ability to take advantage of more advanced optimizations since it's much harder to guarantee functional behavior for any given subexpression. Once side effects rear their ugly heads all bets are off. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 -- http://mail.python.org/mailman/listinfo/python-list
Re: lambda
Op 2005-01-19, Nick Coghlan schreef [EMAIL PROTECTED]: Antoon Pardon wrote: I can be wrong, but until now I have seen no indication that I was using mutable and immutable differently than other people. AFAICT we all refer to whether an object belongs to a mutable or immutable class. The difference is that when you take a copy of the key and stick it in the dictionary, such that the dictionary now holds the *sole* reference to that key, you have made that key *effectively* immutable. This is why no-one really batted an eyelid when you mentioned that mutable keys can be used safely by making a copy - doing so makes the key *effectively* immutable, and means that modifying the original key object (i.e. the application's copy, not the dict's copy), and reusing it to look up in the dictionary is likely to give a KeyError. These semantics would be understandably surprising to many users, and hence, are not supplied by default. This seems like circle reasoning. The reason why these semantics would be surprising is that those are not the semantics supplied. Additionally, a dictionary's keys are accessible via its API. Accordingly, to preserve this 'effective immutability', making a copy on key input is insufficient - keys must be copied on *output* as well (that is, dict.keys, dict.items etc must return *copies* of the key objects, not the key objects themselves). Yes I haven been thinking about this too. I also think not making a copy on output is less dangerous than not making a copy on input. Since there is no reliable way in Python to tell if an object is mutable or not (the closest equivalent is the presence of __hash__, which clearly can't be used in this example), this copying would need to be done for *every* object. Alternately, the dictionary can say to the API clients, make an immutable copy and supply that instead. It is left to API clients to decide how best to make the immutable version. The API client copies the key once (to make the immutable version), and everyone lives happily ever after. For example: Py class mylist(list): ... def __init__(self, arg): ... super(mylist, self).__init__(arg) ... self._tuple = None ... def frozen(self): ... if self._tuple is None: ... self._tuple = tuple(self) ... return self._tuple ... def unfreeze(self): ... self._tuple = None ... Py x = mylist(range(10)) Py x [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] Py x.frozen() (0, 1, 2, 3, 4, 5, 6, 7, 8, 9) Py x.append(10) Py x.frozen() (0, 1, 2, 3, 4, 5, 6, 7, 8, 9) Py x.unfreeze() Py x.frozen() (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10) This is much safer than having a list subclass that implements __hash__, and still lets you avoid redundant copy operations. Nicely, so long as you don't unfreeze the object you used to key the dictionary, reusing the same object will always get you the correct dictionary entry, and two lists that compare equal at the time they are frozen will also get you the same dictionary entry. The equivalent tuples can be used for the lookup, too. Interesting idea. But I think you are wrong when you say that two lists that compare equal at the time they are frozen, will get the same dictionary entry. The problem is an object must compare equal to the key in the dictionary to get at the same entry. So if you freeze a list and its copy but then mutate them differently, they no longer are equal and so wont get you at the same entry. [ Rest snipped, this is getting into a semantic debate on what 'mutable' means. This may be interesting enough on its own but I feel it detracts too much from what I consider the more important issue. ] -- Antoon Pardon -- http://mail.python.org/mailman/listinfo/python-list
Zen of Python
While I agree that the Zen of Python is an amazingly concise list of truisms, I do not see any meaning in: Flat is better than nested. I strive for balance between flat and nested. Does anyone have a good example of where this is applied? (specifically to python, or in general) -- http://mail.python.org/mailman/listinfo/python-list
Accessing MDB files on Windows
Hi, What is the best way to deal with MDB files? I was thinking on using ODBC... I'll need to read and write some information to it. The load won't be so high, but there might be a lot of data. Any advices? Will my approach work? I'm not a Windows guy... :-) -- Godoy. [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Automatic Windows printer creation?
Anyone know if there's a module which will allow me to 'create' windows printer definitions? Not from a Windows domain network, but just to add a printer that sends to a jet-direct-attached printer. Thanks! Dave -- http://mail.python.org/mailman/listinfo/python-list
ElementTree cannot parse UTF-8 Unicode?
Hello All, I am getting an error of not well-formed at the beginning of the Korean text in the second example. I am doing something wrong with how I am encoding my Korean? Do I need more of a wrapper about it than simple quotes? Is there some sort of XML syntax for indicating a Unicode string, or does the Elementree library just not support reading of Unicode? here is my test snippet: from elementtree import ElementTree vocabXML = ElementTree.parse('test2.xml').getroot() where I have two data files: this one works: ?xml version=1.0 encoding=UTF-8? Vocab Word L1='Hahha'/Word /Vocab this one fails: ?xml version=1.0 encoding=UTF-8? Vocab Word L1=!/Word /Vocab -- http://mail.python.org/mailman/listinfo/python-list
Re: Zen of Python
Bill The example that occurs to me is that import smtplib is better Bill than import stdlib.inet.services.smtp. Sure. There is a balance to be achieved however. import std.smtplib might be better than import smtplib, simply because making the standard library a package reduces the possibility of namespace collisions. Skip -- http://mail.python.org/mailman/listinfo/python-list
Re: Accessing MDB files on Windows
Larry Bates, Quarta 19 Janeiro 2005 14:01, wrote: I'm assuming the application will be run on Windows. You're right. It will be run on Windows. I discarded some other platform due to the difficulty of supporting this file format. You can use ODBC or DAO. An DAO solution that I wrote (and use) can be found at: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/303349 Thanks! I'm looking at it. For ODBC you would just use the standard library module. Thanks. I'll be trying the DAO first. -- Godoy. [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: generator expressions: performance anomaly?
Antoon Pardon wrote: Op 2005-01-18, Steve Holden schreef [EMAIL PROTECTED]: [...] But you do have a point that I have a tendency to put salt on any snail. I'll try to restrain myself a bit more in the future. Finally! :-) I find I like you much better after this reflective response. Thanks for taking the time to read my snarking and respond to it. A tendency to put salt on any snail is a nice phrase I've never come across before. Is it specifically Belgian? regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 -- http://mail.python.org/mailman/listinfo/python-list
a question
L.S., I have a long command in Unix and I have to use os.system(cmd) statement. I do the following: cmd = '%s/mos user wmarch, cd /fa/wm/%s/%s, mkdir %s, put %s, chmod 644 %s' % (mosbin, jaar, filetype, filetype) status = os.system(cmd) This is not very clear, and I have to break this long line in two segment by means of the next character '\' : cmd = '%s/mos user wmarch, cd /fa/wm/%s/%s, mkdir %s, put %s, \ chmod 644 %s' % (mosbin, jaar, filetype, filetype) But in this case I get a syntax error! I don't know how I can solve this problem. Could somebody tell me about this? With regards, Nader (this -- http://mail.python.org/mailman/listinfo/python-list
Re: Print to Windows default Printer
Thanks Tim. I didn't realize it would be so difficult. S Tim Golden [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
RuntimeError: dictionary changed size during iteration
I think, the behaviour below is misfeature: [e for e in vars()] Traceback (most recent call last): File stdin, line 1, in ? RuntimeError: dictionary changed size during iteration e = None [e for e in vars()] ['e', '__builtins__', 'rlcompleter', '__file__', '_[1]', 'atexit', '__name__', 'readline', '__doc__'] Sincerely yours, Roman Suzi -- [EMAIL PROTECTED] =\= My AI powered by GNU/Linux RedHat 7.3 -- http://mail.python.org/mailman/listinfo/python-list
Re: ElementTree cannot parse UTF-8 Unicode?
Erik Bethke wrote: I am getting an error of not well-formed at the beginning of the Korean text in the second example. I am doing something wrong with how I am encoding my Korean? Do I need more of a wrapper about it than simple quotes? Is there some sort of XML syntax for indicating a Unicode string, or does the Elementree library just not support reading of Unicode? XML is Unicode, and ElementTree supports all common encodings just fine (including UTF-8). this one fails: ?xml version=1.0 encoding=UTF-8? Vocab Word L1=?!/Word /Vocab this works just fine on my machine. what's the exact error message? what does print repr(open(test2.xml).read()) print on your machine? what happens if you attempt to parse Vocab Word L1=#50612;#45397;#54616;#49464;#50836;! / /Vocab ? /F -- http://mail.python.org/mailman/listinfo/python-list
Re: a question
Nader, You've got a couple problems. First, you need to end the string before putting a continuation in. Secondly, you have 6 variables to be substituted and only provide 4. Here's some code, edited to show how to use continutations to join strings: mosbin, jaar, filetype = (1,1,1) cmd = '%s/mos user wmarch, cd /fa/wm/%s/%s, mkdir %s, put %s'\ ... '%s' % (mosbin, jaar, filetype, filetype, filetype, filetype) cmd '1/mos user wmarch, cd /fa/wm/1/1, mkdir 1, put 1, chmod 6441' Peace Bill Mill bill.mill at gmail.com On Wed, 19 Jan 2005 16:16:32 +, Nader Emami [EMAIL PROTECTED] wrote: L.S., I have a long command in Unix and I have to use os.system(cmd) statement. I do the following: cmd = '%s/mos user wmarch, cd /fa/wm/%s/%s, mkdir %s, put %s, chmod 644 %s' % (mosbin, jaar, filetype, filetype) status = os.system(cmd) This is not very clear, and I have to break this long line in two segment by means of the next character '\' : cmd = '%s/mos user wmarch, cd /fa/wm/%s/%s, mkdir %s, put %s, \ chmod 644 %s' % (mosbin, jaar, filetype, filetype) But in this case I get a syntax error! I don't know how I can solve this problem. Could somebody tell me about this? With regards, Nader (this -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: RuntimeError: dictionary changed size during iteration
On Wed, Jan 19, 2005 at 11:45:15PM +0300, Roman Suzi wrote: I think, the behaviour below is misfeature: [e for e in vars()] Traceback (most recent call last): File stdin, line 1, in ? RuntimeError: dictionary changed size during iteration e = None [e for e in vars()] ['e', '__builtins__', 'rlcompleter', '__file__', '_[1]', 'atexit', '__name__', 'readline', '__doc__'] Chalk it up as a lesson in the slightly different behavior of genexps Python 2.4 (#2, Jan 8 2005, 20:18:03) [GCC 3.3.5 (Debian 1:3.3.5-5)] on linux2 Type help, copyright, credits or license for more information. list(e for e in vars()) ['__builtins__', '__name__', '__doc__'] [e for e in vars()] Traceback (most recent call last): File stdin, line 1, in ? RuntimeError: dictionary changed size during iteration -Jack -- http://mail.python.org/mailman/listinfo/python-list
Re: Has apparent 2.4b1 bug been fixed? flatten in Lib\compiler\ast.py overloads 'list' name
You have name clashing between Python's built in list function and the variable called list that you pass into the function. Change the passed in variable name to something else. Larry Bates Try something like (not tested): def flatten(seq): l = [] for elt in seq: if isinstance(elt, (list, tuple): for elt2 in flatten(elt): l.append(elt2) else: l.append(elt) return l Bengt Richter wrote: What am I missing? (this is from 2.4b1, so probably it has been fixed?) def flatten(list): l = [] for elt in list: --must be expecting list instance or other sequence t = type(elt) if t is tuple or t is list: --looks like it expects to refer to the type, not the arg for elt2 in flatten(elt): l.append(elt2) else: l.append(elt) return l Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list
Re: a question
You are correct, sir. Didn't know you could do that. Neato. Peace Bill Mill bill.mill at gmail.com On Wed, 19 Jan 2005 22:10:05 +0100, Fredrik Lundh [EMAIL PROTECTED] wrote: Bill Mill wrote: You've got a couple problems. First, you need to end the string before putting a continuation in. no\ ... pe 'nope' however\ File stdin, line 1 however\ ^ SyntaxError: EOL while scanning single-quoted string (in the second case, the ^ is trying to point out that I added some whitespace after the backslash) /F -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Zen of Python
Timothy Fitz wrote: While I agree that the Zen of Python is an amazingly concise list of truisms, I do not see any meaning in: Flat is better than nested. I strive for balance between flat and nested. Does anyone have a good example of where this is applied? (specifically to python, or in general) One example would be using a function instead of a class when a function does the job at the module level. Using the appropriate degree of abstraction/indirection. // m -- http://mail.python.org/mailman/listinfo/python-list
RE: Accessing MDB files on Windows
Jorge Luiz Godoy Filho wrote: What is the best way to deal with MDB files? I was thinking on using ODBC... I'll need to read and write some information to it. The load won't be so high, but there might be a lot of data. Any advices? Will my approach work? I'm not a Windows guy... :-) Use ADO unless you need to support older versions of Windows. It'll be a lot faster and cleaner than ODBC. Robert Brewer MIS Amor Ministries [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
RE: RuntimeError: dictionary changed size during iteration
Roman Suzi wrote: I think, the behaviour below is misfeature: [e for e in vars()] Traceback (most recent call last): File stdin, line 1, in ? RuntimeError: dictionary changed size during iteration e = None [e for e in vars()] ['e', '__builtins__', 'rlcompleter', '__file__', '_[1]', 'atexit', '__name__', 'readline', '__doc__'] But not unexpected, since vars() returns a dictionary, and binding 'e' changes that dictionary while you are iterating over it. Try either: [e for e in vars().keys()] or e = None [e for e in vars()] or the generator expression if you have Python 2.4. Robert Brewer MIS Amor Ministries [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: generator expressions: performance anomaly?
Op 2005-01-19, Steve Holden schreef [EMAIL PROTECTED]: Antoon Pardon wrote: Op 2005-01-18, Steve Holden schreef [EMAIL PROTECTED]: [...] But you do have a point that I have a tendency to put salt on any snail. I'll try to restrain myself a bit more in the future. Finally! :-) I find I like you much better after this reflective response. Thanks for taking the time to read my snarking and respond to it. A tendency to put salt on any snail is a nice phrase I've never come across before. Is it specifically Belgian? It is a literal translation of a dutch idiom: Op alle slakken zout leggen. Most people in Belgium speak dutch although foreigner often seem to think we all speak native French. -- http://mail.python.org/mailman/listinfo/python-list
Re: [OT] Good C++ book for a Python programmer
I suggest you google 'C++ tutorial' Regards, Philippe On Wed, 19 Jan 2005 04:08:16 -0800, [EMAIL PROTECTED] wrote: I'm picking up C++ again after years of using almost nothing but Python. I'm frankly enjoying the experience, and it's certainly deepening my appreciation of Python (which you can read however you like). I was wondering whether anyone could recommend a good C++ book, with good being defined from the perspective of a Python programmer. I realize that there isn't a book titled C++ for Python Programmers, but has anyone found one that they think goes particularly well with the Python way? I'm asking this because evidently the C++ standard has changed a bit since 1994, when I bought my books. Who knew that fstream was deprecated? Thanks in advance... -- http://mail.python.org/mailman/listinfo/python-list
Re: [OT] Good C++ book for a Python programmer
Philippe == Philippe C Martin [EMAIL PROTECTED] writes: Philippe I suggest you google 'C++ tutorial' Regards, Stroustup's The C++ Programming Language is the best C++ book I've read. It is at a fairly high level, and I already had read several C++ books before reading it, so it may be tough sledding. But I would try this first since you are an experienced programmer and know OO concepts, and if it fails to satisfy try something lighter. Unfortunately, I didn't like any of the other kinder, gentler overview books I read on C++, so can't really recommend anything along those lines, though I'm sure they are out there. JDH -- http://mail.python.org/mailman/listinfo/python-list
[ANN] XPN - X Python Newsreader 0.4.0 released
XPN is a multiplatform newsreader written in Python+GTK2. It is unicode compliant and has features like scoring/action rules, configurable attribution lines and random taglines, search facilities and filtered views, import/export newsrc ... You can find it on: http://xpn.altervista.org/index-en.html or http://sf.net/projects/xpn I'd really appreciate every type of feedback. Changes in this release: * v0.4.0: added off-line reading. Now you can download the whole bodies, or mark some article and download their bodies. * v0.4.0: added Keep Article and Watch/Ignore SubThread * v0.4.0: added actions rule, now you can !keep, !watch, !ignore (and so on) your article through rules * v0.4.0: now XPN stores the position and the size of Main Window and Edit Window * v0.4.0: now you can customize the charsets list XPN use to encode your outgoing articles * v0.4.0: improved speed when loading groups list in Groups Window. * v0.4.0: fixed a bug in the binary version that caused a crash trying to subscribe a group * v0.4.0: added Oriental Charsets support (thanks to Python2.4) * v0.4.0: added Global Search, you can search the whole groups and put the results in a virtual group * v0.4.0: added filtered views * v0.4.0: moved to GTK2.4 and Python2.4 * v0.4.0: added a TraceBack viewer and an error logger * v0.4.0: reorganized some menus * v0.4.0: now the background color is changed also on Groups Pane and Headers pane * v0.4.0: added a lot of little features/enhancements * v0.4.0: fixed a lot of bugs -- I'm not a complete idiot - several parts are missing. |\ | |HomePage : http://nem01.altervista.org | \|emesis |XPN (my nr): http://xpn.altervista.org -- http://mail.python.org/mailman/listinfo/python-list
Re: python/cgi/html bug
On Wed, 19 Jan 2005 04:32:04 -0800, Fuzzyman wrote: This looks very good. I've been looking for a python messageboard CGI for a long time. Thanx! No glaring security holes that you noticed? Other than being able to hide things in html tags? If you wanted to add user accounts/login/admin etc. you could use 'Login Tools'. This is a python module built especially to do that. It also provides a convenient way of saving user preferences etc. http://www.voidspace.org.uk/python/logintools.html If you want any help using it then feel free to ask. Regards, -- http://mail.python.org/mailman/listinfo/python-list
Re: Accessing MDB files on Windows
Steve Holden, Quarta 19 Janeiro 2005 14:38, wrote: Note that DAO is a very old library, and nowadays ADO would probably be the preferred method in the Windows environment (can DAO even *use* oledb providers?). ADO libraries are available - see http://www.markcarter.me.uk/computing/python/ado.html for example, or Google for python ado. Bottom line, there are many ways to skin this particular cat. Hmmm... I see. I'm trying to avoid having to install external modules at my client's server. Should I use, given that both DAO and ODBC are available with the win32all extensions, DAO or ODBC? Or would ADO give me so much more performance that I should really use it? -- Godoy. [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: a question
Will Stuyvesant wrote: Andrew Koenig wrote: how about writing this instead? ('this is a ' 'long string') Yes, nice. And to make that possible we have to write ('one-string-item',) instead of ('one-string-item') if we want a tuple with one string inside. Sometimes that feels like a wart to me, but now I know it, sometimes not. That has very little to do with tuples. You could just as easily write 'this is a '\ 'long string' It's the dangling comma that's required to specify a tuple: 1, (1,) regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 -- http://mail.python.org/mailman/listinfo/python-list
Re: Accessing MDB files on Windows
Jorge Luiz Godoy Filho, Quarta 19 Janeiro 2005 14:25, wrote: Thanks! I'm looking at it. Worked like a charm! And just now I noticed who's the author of the recipe ;-) Thanks! -- Godoy. [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: [OT] Good C++ book for a Python programmer
Rick Muller wrote: I was wondering whether anyone could recommend a good C++ book, with good being defined from the perspective of a Python programmer. The STL and the template feature of C++ gives the programmer some of the functionality of Python (using templates instead of duck typing, vectors instead of lists etc.), so a book that introduces these features early, such as Accelerated C++ by Koenig and Moo, could be a good start for a Pythonner. The 4th edition of the well-known C++ Primer, with Moo as a new co-author, will soon be published. It is a more comprehensive and much longer book. -- http://mail.python.org/mailman/listinfo/python-list
Re: simultaneous multiple requests to very simple database
On Tue, 18 Jan 2005 12:57:21 -0500, Eric S. Johansson [EMAIL PROTECTED] wrote: Robert Brewer wrote: Eric S. Johansson wrote: I have an application where I need a very simple database, effectively a very large dictionary. The very large dictionary must be accessed from multiple processes simultaneously. I need to be able to lock records within the very large dictionary when records are written to. Just to clarify, you want shared-read until a write, at which point you want to lock just the item being written? Or would page or table locking be acceptable at that point? just the item/record. I'm doing arrival rate calculations. each record contains a set of arrival times and I am rewriting the record every time a new entry arrives. complete page or table locking will work in the sense that it will prevent collisions but it will have an increasing impact as load and simultaneous table but not record accesses increase. ---eric Use Firebird as sql backend. Is designed as you request (readers not lock writers and writers not lock readers). Google for firebird optimistic lock. Off course, you have python driver: http://kinterbasdb.sf.net and can deploy on windows and linux with a very little footprint. -- Olaf Zetanien -- http://mail.python.org/mailman/listinfo/python-list
Re: simultaneous multiple requests to very simple database
On Tue, 18 Jan 2005 11:26:46 -0500, Eric S. Johansson wrote: So the solutions that come to mind are some form of dictionary in shared memory with locking semaphore scoreboard or a multithreaded process containing a single database (Python native dictionary, metakit, gdbm??) and have all of my processes speak to it using xmlrpc which leaves me with the question of how to make a multithreaded server using stock xmlrpc. Another solution might be to store the records as files in a directory, and use file locking to control access to the files (careful over NFS!). You might also consider berkeley db, which is a simple database to add to an application, (and which I believe supports locks), but I must admit I'm not a fan of the library. I assume that the bottleneck is processing the records, otherwise this all seems a bit academic. Jeremy -- http://mail.python.org/mailman/listinfo/python-list
Re: Dictionary keys (again) (was Re: lambda)
David Eppstein wrote: In article [EMAIL PROTECTED], Nick Coghlan [EMAIL PROTECTED] wrote: For a 'mutable key' to make sense, the following: lst = [] dct = {l: Hi!} print dct[[]] print dct[lst] lst.append(1) print dct[[1]] print dct[lst] Should print: Hi Hi Hi Hi Yes, and what should the following do? lst1 = [1] lst2 = [2] dct = {lst1: 1, lst2: 2} lst2[0]=1 lst1[0]=2 print dct[[1]] print dct[[2]] Depends on when you want the updates done. Since my implementation only rehashes when the dict is accessed, neither key gets overwritten in this case: py class sillylist(list): ... def __hash__(self): ... return hash(tuple(self)) ... py class sillydict(dict): ... def _rehash(self): ... items = self.items() ... self.clear() ... self.update(items) ... def __getitem__(self, key): ... self._rehash() ... return super(sillydict, self).__getitem__(key) ... def __setitem__(self, key, value): ... self._rehash() ... return super(sillydict, self).__setitem__(key, value) ... py lst1 = sillylist([1]) py lst2 = sillylist([2]) py dct = sillydict({lst1:1, lst2:2}) py lst2[0] = 1 py lst1[0] = 2 py print dct[sillylist([1])] 2 py print dct[sillylist([2])] 1 The nastier question is, what should the following code do: lst1 = [1] lst2 = [2] dct = {lst1: 1, lst2: 2} lst2[0]=1 print dct[[1]] print dct[[2]] My implementation does the following: py lst1 = sillylist([1]) py lst2 = sillylist([2]) py dct = sillydict({lst1:1, lst2:2}) py lst2[0] = 1 py print dct[sillylist([1])] 1 py print dct[sillylist([2])] Traceback (most recent call last): File interactive input, line 1, in ? File interactive input, line 8, in __getitem__ KeyError: [2] which is even sillier when you compare to what happens with the original code you posted. ;) Steve -- http://mail.python.org/mailman/listinfo/python-list
Re: a question
Steve Holden [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] The error you get is NOT a syntax error: cmd = '%s format %s \ ... over %d lines' % ('my', 'string', 2) cmd 'my format string over 2 lines' The interpreter is probably complaining because it needs six values to fill out the format and you only provided four. Also, I'm dubious about the idea of splitting a string literal across multiple lines, as it's impossible to indent such a literal nicely without putting stray spaces into its contents. So instead of writing 'this is a\ long string' and not making it clear how many spaces you intend between 'a' and 'long', how about writing this instead? ('this is a ' 'long string') in which the contents are not in doubt. This code takes advantage of two properties of Python: 1) Multiple string literals with only whitespace between them are automatically concatenated; 2) Ending a line inside unbalanced parentheses implicitly makes the next line part of the same statement. -- http://mail.python.org/mailman/listinfo/python-list
Re: delay and force in Python
Yes you are right, if you just want to carry an expression around then lambda does it; but delay was not intended as a top-level function. Perhaps you think that my silly stream implementation in the original post builds the whole list, but it does not: o = stream_enumerate_interval(11,121) print o [11, function lambda at 0x00BA8670] f = o[1] r = f() print r [12, function lambda at 0x00BA86B0] instead it builds a list of lambda's, and that is so desirable wink Others suggested generators indeed, and I can imagine now a usage pattern like s = stream_generator(initValue, next, stop, other_params) stream_hd(stream_tl(stream_filter(isEven,s))) where the idea is to pass a generator to a function all the time. What I don't like though is that I then, as I understand it, have to code some for-loop inside that function, I try to avoid for-loops. But a functional form defined with a for-loop does not seem all that bad. Anyway I have some reading-up to do, about things some posters use and I forgot to keep up with since I have been coding Python 1.5.2 style for ages now: properties, itertools, ...printed some stuff already, thanks! -- http://mail.python.org/mailman/listinfo/python-list
Re: [OT] Good C++ book for a Python programmer
[EMAIL PROTECTED] [EMAIL PROTECTED] writes: I was wondering whether anyone could recommend a good C++ book, with good being defined from the perspective of a Python programmer. I realize that there isn't a book titled C++ for Python Programmers, but has anyone found one that they think goes particularly well with the Python way? I think it's not possible to really grok C++ without having worked on large multi-person C projects and understood what problems C++ tried to solve. The only good book I know about C++ is by Stroustrup, The C++ Programming Language or something like that; it's not an easy book though. -- http://mail.python.org/mailman/listinfo/python-list
Re: Has apparent 2.4b1 bug been fixed? flatten in Lib\compiler\ast.py overloads 'list' name
Larry Bates wrote: You have name clashing between Python's built in list function and the variable called list that you pass into the function. Change the passed in variable name to something else. I believe Bengt was merely seeking confirmation that this was indeed a bug in a distributed library (which he then provided himself by finding a bug report). Hence his use of the phrase overloads 'list' name in the subject line! regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 -- http://mail.python.org/mailman/listinfo/python-list
Re: generator expressions: performance anomaly?
[Steve Holden] Since it doesn't yet optimize 2+5 to a constant-folded 7 you should realize that you are suggesting a large increase in the compiler's analytical powers. FWIW, limited constant folding is already in CVS for Py2.5. Raymond Hettinger -- http://mail.python.org/mailman/listinfo/python-list
Re: finding/replacing a long binary pattern in a .bin file
Thanks Francois, It worked as expected. --- source_data = open(source_data.bin, 'rb').read() search_data = open(search_data.bin, 'rb').read() replace_data = open(replace_data.bin, 'rb').read() outFile = open(mod.bin, 'wb') file_offset = source_data.find(search_data) print file_offset:, file_offset outData = source_data.replace(search_data, replace_data) outFile.write(outData) outFile.close print -- http://mail.python.org/mailman/listinfo/python-list
Re: finding/replacing a long binary pattern in a .bin file
Bengt, Thanks for the input, sorry, your diff threw me the first time I looked at it, but then I went back and tried it later. Yes it works fine and I've tucked it away for later use. For this particular Use Case String.replace seems to get the job done in short order and the tool needs to be maintained by folks not familiar /w Python so I went a head and used that. But, I image I will use this bit of code when I need a finer grained tool. Thanks again. Cheers, --Alan -- http://mail.python.org/mailman/listinfo/python-list
Re: Dictionary keys (again) (was Re: lambda)
Nick Coghlan wrote: For a 'mutable key' to make sense, the following: lst = [] dct = {l: Hi!} print dct[[]] print dct[lst] lst.append(1) print dct[[1]] print dct[lst] Should print: Hi Hi Hi Hi And here's an implementation that does so: py class sillydict(dict): ... def __getitem__(self, key): ... items = self.items() ... self.clear() ... self.update(items) ... return super(sillydict, self).__getitem__(key) ... py class sillylist(list): ... def __hash__(self): ... return hash(tuple(self)) ... py lst = sillylist([]) py dct = sillydict({lst: Hi!}) py print dct[sillylist([])] Hi! py print dct[lst] Hi! py lst.append(1) py print dct[sillylist([1])] Hi! py print dct[lst] Hi! Of course, as noted by the classes themselves, they're silly. ;) But as long as you don't mind rehashing the dict each time the dict is accessed ;) you can get sane behavior even in the presence of mutable keys. Steve -- http://mail.python.org/mailman/listinfo/python-list
Re: Zen of Python
Peter Hansen wrote: Timothy Fitz wrote: While I agree that the Zen of Python is an amazingly concise list of truisms, I do not see any meaning in: Flat is better than nested. [incrdeibly secret PSU facts blurted out] And with that out of the way, one is left with there's a balance along the flat/nested dimension which is appropriate to any given situation, so nest with moderation and only when necessary. They'd probably been talking to Antoon Pardon :-) But that didn't fit in the list so they went with the shorter version... regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 -- http://mail.python.org/mailman/listinfo/python-list
Re: Accessing MDB files on Windows
Jorge Luiz Godoy Filho, Quarta 19 Janeiro 2005 15:17, wrote: Hmmm... I see. I'm trying to avoid having to install external modules at my client's server. Should I use, given that both DAO and ODBC are available with the win32all extensions, DAO or ODBC? Or would ADO give me so much more performance that I should really use it? I've also made it work with ADO... It doesn't require me to use the 'makepy' on it, so this might be a better choice if I have to deploy for more machines. I think I'll go with ADO. Thanks Larry and Steve. -- Godoy. [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Dictionary keys (again) (was Re: lambda)
In article [EMAIL PROTECTED], Nick Coghlan [EMAIL PROTECTED] wrote: For a 'mutable key' to make sense, the following: lst = [] dct = {l: Hi!} print dct[[]] print dct[lst] lst.append(1) print dct[[1]] print dct[lst] Should print: Hi Hi Hi Hi Yes, and what should the following do? lst1 = [1] lst2 = [2] dct = {lst1: 1, lst2: 2} lst2[0]=1 lst1[0]=2 print dct[[1]] print dct[[2]] -- David Eppstein Computer Science Dept., Univ. of California, Irvine http://www.ics.uci.edu/~eppstein/ -- http://mail.python.org/mailman/listinfo/python-list
FTPLIB FTPS or SFTP?
Does the ftplib support SFTP or FTPS? Is that part of a different module? We have a handful of partners who use FTPS or SFTP and I need to pull/push files to/from them. Thank you for all of your help. -Pete Schott -- http://mail.python.org/mailman/listinfo/python-list
Re: [OT] Good C++ book for a Python programmer
John Hunter wrote: Philippe == Philippe C Martin [EMAIL PROTECTED] writes: Philippe I suggest you google 'C++ tutorial' Regards, Stroustup's The C++ Programming Language is the best C++ book I've read. It is at a fairly high level, and I already had read several C++ books before reading it, so it may be tough sledding. But I would try this first since you are an experienced programmer and know OO concepts, and if it fails to satisfy try something lighter. Unfortunately, I didn't like any of the other kinder, gentler overview books I read on C++, so can't really recommend anything along those lines, though I'm sure they are out there. JDH For a rationale as to why the language developed the way it did, you can read Stroustrup's The Design and Evolution of C++. This is no good for learning the language, but it might be a good library borrow to find out why the language is the way it is. -Scott David Daniels [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: rotor replacement
Scott David Daniels [EMAIL PROTECTED] writes: I understand this to be true. Since I am trying to address encryption in the zipfile module, and I know you actually follow a bit of the encryption stuff, can you answer a question or two for me? Sure, I can try, so go ahead. There's more crypto expertise in sci.crypt though. Zipfile encryption is totally incompatible with the rotor module, by the way, and traditionally it didn't use AES. There are a couple of replacements for the traditional method that do use AES but that I think are somewhat incompatible with each other. The Python maintainers didn't want to deal with imagined legal hassles that might develop from including good crypto functions in the distribution. Then it became obvious that the same imagined hassles could also befall the rotor module, so that was removed. Are you saying these hassles are, in fact, imaginary rather than real? Well, I didn't want to say that the hassles were real, but I wasn't trying to insinuate quite as much as it may have sounded. Like, I don't drive my car at 100 mph on Main Street because I can imagine what would happen and it's not pretty. The imagined carnage is a good enough reason not to drive that way. However, I do feel that the Python distributors are being over-cautious, see below. Is this because you feel python is over-cautious about the USA, or is this an opinion on essentially all countries? This is not a quibble or a kvetch; I would like your understanding about the world legal state of dealing with encryption (which, I assure you, I won't take as definitive). I would hate to think someone in, for example, the UAE, was busted for downloading or republishing python out-of-the-box. I think the Python maintainers were more concerned about that UAE situation. However, the most widely deployed encryption software is the SSL stack in just about every web browser (MSIE, Firefox, etc.) and I'm sure lots of people are using those browsers in the UAE. The Mozilla foundation isn't hestitating to ship the encryption as far as I can tell. See http://www.bxa.doc.gov/Encryption for the USA rules. Basically for a free encryption program on the web, you're supposed to notify the Dept. of Commerce by sending them an email when you publish it, telling them where they can get it (address is on that site). As far as anyone can tell, the DOC never does anything with those emails. The rules are more complicated for nonpublished commercial programs, crypto hardware, etc. Don't get me wrong, I'd love the answer to be sure its fine, but my current plans are to provide a way to connect a crypto package to zipfile without providing any such package myself. I'd say provide a package if you can, unless you have realistic concern about getting in trouble. -- http://mail.python.org/mailman/listinfo/python-list
shelve to DB conversion?
I'd like to hear some experiences about converting a shelf with pickles to database with pickles, particularly if someone has handy code for proxying shelve code. We're using PostgreSQL if that makes any difference. -- Aahz ([EMAIL PROTECTED]) * http://www.pythoncraft.com/ 19. A language that doesn't affect the way you think about programming, is not worth knowing. --Alan Perlis -- http://mail.python.org/mailman/listinfo/python-list
xml parsing escape characters
-BEGIN PGP SIGNED MESSAGE- Hash: SHA1 Hi, I only know a little bit of xml and I'm trying to parse a xml document in order to save its elements in a file (dictionaries inside a list). When I access a url from python 2.3.3 running in Linux with the following lines: resposta = urllib.urlopen(url) xmldoc = minidom.parse(resposta) resposta.close() I get the following result: ?xml version=1.0 encoding=utf-8? string xmlns=http://www..;lt;DataSetgt; ~ lt;Ordergt; ~lt;Customergt;439lt;/Customergt; (... others ...) ~ lt;/Ordergt; lt;/DataSetgt;/string _ In the lines below, I try to get all the child nodes from string, first by counting them, and then ignoring the /n ones: stringNode = xmldoc.childNodes[0] print stringNode.toxml() dataSetNode = stringNode.childNodes[0] numNos = len(dataSetNode.childNodes) todosNos={} for no in range(numNos): todosNos[no] = dataSetNode.childNodes[no].toxml() posicaoXml = [no for no in todosNos.keys() if len(todosNos[no])4] print posicaoXml (I'm almost sure there's a simpler way to do this...) _ I don't get any elements. But, if I access the same url via a browser, the result in the browser window is something like: string xmlns=http://www..; ~ DataSet ~Order ~ Customer439/Customer (... others ...) ~/Order ~ /DataSet /string and the lines I posted work as intended. I already browsed the web, I know it's about the escape characters, but I didn't find a simple solution for this. I tried to use LL2XML.py and unescape function with a simple replace text = text.replace(lt;, ) but I had to convert the xml document to string and then I could not (or don't know) how to convert it back to xml object. How can I solve this? Please, explain it having in mind that I'm just beggining with Xml and I'm not very experienced in Python, too. Luis -BEGIN PGP SIGNATURE- Version: GnuPG v1.2.4 (GNU/Linux) Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org iD8DBQFB7rzKHn4UHCY8rB8RAhnlAKCYA6t0gd8rRDhIvZ5sdmNJlEPSeQCgteB3 XUtZ0JoHeTavBOCYi6YYnNo= =VORM -END PGP SIGNATURE- -- http://mail.python.org/mailman/listinfo/python-list
Re: delay and force in Python
It took me a while to figure out what the translated code was trying to do. Here's a quick example that I think accomplishes the same thing: for i, n in enumerate(x for x in xrange(998) if x % 2 == 0): ... if i == 1: ... print n ... 2 -- http://mail.python.org/mailman/listinfo/python-list
Re: python/cgi/html bug
Dfenestr8 [EMAIL PROTECTED] writes: No glaring security holes that you noticed? Other than being able to hide things in html tags? Looks like you can also embed arbitrary javascript (I just tried it). I haven't looked at the script itself yet. -- http://mail.python.org/mailman/listinfo/python-list
Re: a question
Andrew Koenig wrote: how about writing this instead? ('this is a ' 'long string') Yes, nice. And to make that possible we have to write ('one-string-item',) instead of ('one-string-item') if we want a tuple with one string inside. Sometimes that feels like a wart to me, but now I know it, sometimes not. -- http://mail.python.org/mailman/listinfo/python-list
Re: Zen of Python
Skip Montanaro wrote: Bill The example that occurs to me is that import smtplib is better Bill than import stdlib.inet.services.smtp. Sure. There is a balance to be achieved however. import std.smtplib might be better than import smtplib, simply because making the standard library a package reduces the possibility of namespace collisions. Yep. Reorganize the standard library to be not as shallow is listed right there in PEP 3000. Notice, however, that it doesn't say, Reorganize the standard library into an intricate feudal hierarchy of packages, modules, and cross-references. :) The gist of Flat is better than nested is be as nested as you have to be, no more, because being too nested is just a mess. -- CARL BANKS -- http://mail.python.org/mailman/listinfo/python-list
Re: xml parsing escape characters
Luis P. Mendes wrote: I get the following result: ?xml version=1.0 encoding=utf-8? string xmlns=http://www..;lt;DataSetgt; ~ lt;Ordergt; Most likely, this result is correct, and your document really does contain lt;Ordergt; I don't get any elements. But, if I access the same url via a browser, the result in the browser window is something like: string xmlns=http://www..; ~ DataSet Most likely, your browser is incorrect (or atleast confusing), and renders lt; as , even though this is not markup. I already browsed the web, I know it's about the escape characters, but I didn't find a simple solution for this. Not sure what this is. AFAICT, everything works correctly. Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: Python and Excel
Please consider this reply as one vote for posting your python Excel interface/software on the Vaults of Pamassus Web Site. Located at http://www.vex.net/parnassus/ -- http://mail.python.org/mailman/listinfo/python-list
Re: rotor replacement
Nick Craig-Wood wrote: Robin Becker [EMAIL PROTECTED] wrote: Paul Rubin wrote: Reed L. O'Brien [EMAIL PROTECTED] writes: I see rotor was removed for 2.4 and the docs say use an AES module provided separately... Is there a standard module that works alike or an AES module that works alike but with better encryption? If you mean a module in the distribution, the answer is no, for political reasons. .I'm also missing the rotor module and regret that something useful was warned about and now removed with no plugin replacement. I had understood that this was because rotor was insecure, but you mention politics. Are other useful modules to suffer from politics? ... Presumably he is talking about crypo-export rules. In the past strong cryptography has been treated as munitions, and as such exporting it (especially from the USA) could have got you into very serious trouble. well since rotor is a german (1930's) invention it is a bit late for Amricans (Hollywood notwithstanding) to be worried about its export However I believe those restrictions have been lifted (the cat having been let out of the bag somewhat ;-), and its easy to do this for open source encryption software. A wade through -- Robin Becker -- http://mail.python.org/mailman/listinfo/python-list
Re: getting a class attribute using a keyword argument
Guy Robinson wrote: Hello, I have a list of class instances. I wish to get the appropriate class attribute in each class instance depending on a SINGLE keyword in the calling class. How do I get the calling method to correctly recognise the keyword as a keyword and not a class attribute? See example code below (which doesn't work). class tocall: def __init__(self): self.title = test self.name = name def callingmethod(self,**kw): for key in kw: if tocall.key == kw[key]: return tocall.key which should work as such(but doesn't): print callmethod(title = test) print callmethod(name = name) Regards, Guy Hi, This may be more like you want. class tocall: def __init__(self): self.title = test self.name = name def callmethod(**kw): for key in kw: if hasattr(tocall(), key): return getattr(tocall(), key) print callmethod(title = test) print callmethod(name = name) -- http://mail.python.org/mailman/listinfo/python-list
Re: rotor replacement
Robin Becker wrote: Presumably he is talking about crypo-export rules. In the past strong cryptography has been treated as munitions, and as such exporting it (especially from the USA) could have got you into very serious trouble. So Python is an American Language and must obey American Law. Luckily I seem to have escaped that fate. -- Robin Becker -- http://mail.python.org/mailman/listinfo/python-list
Re: ElementTree cannot parse UTF-8 Unicode?
Hello Fredrik, 1) The exact error is in line 1160 of self._parser.Parse(data, 0 ): xml.parsers.expat.ExpatError: not well-formed (invalid token): line 3, column 16 2) You are right in that the print of the file read works just fine. 3) You are also right in that the digitally encoded unicode also works fine. However, this solution has two new problems: 1) The xml file is now not human readable 2) After ElementTree gets done parsing it, I am feeding the text to a wx.TextCtrl via .SetValue() but that is now giving me an error message of being unable to convert that style of string So it seems to me, that ElementTree is just not expecting to run into the Korean characters for it is at column 16 that these begin. Am I formatting the XML properly? Thank you, -Erik -- http://mail.python.org/mailman/listinfo/python-list
Re: Zen of Python
On 19 Jan 2005 15:24:10 -0800, Carl Banks [EMAIL PROTECTED] wrote: The gist of Flat is better than nested is be as nested as you have to be, no more, because being too nested is just a mess. Which I agree with, and which makes sense. However your gist is a different meaning. It's not that Flat is better than nested it's that Too flat is bad and too flat is nested so be as nested (or as flat) as you have to be and no more. Perhaps Tim Peters is far too concise for my feeble mind wink -- http://mail.python.org/mailman/listinfo/python-list
Re: Zen of Python
Timothy Fitz wrote: While I agree that the Zen of Python is an amazingly concise list of truisms, I do not see any meaning in: Flat is better than nested. I strive for balance between flat and nested. Does anyone have a good example of where this is applied? (specifically to python, or in general) I think the essence of why this Zen is true is the recognition that the world isn't really organized into a nice, proper, perfect heirarchy, where every node is a perfect little subset of its parent. The fact is, some things are flat. A list is flat. Is is not better to deal with flat things flatly? And some things aren't flat, but they're not nested either. Rather, they are various overlapping sets, but not subsets. It it better to deal with such as mess by shoehorning it into a heirarchy that isn't applicable, or to make it flat and deal with the subsets individually? I shall give two examples of where Python exhibits this Zen, and doing one my favorite things in the process: slamming other languages. ITERATION There are two ways to iterate: the flat way, with a for loop or list comprehension or something like that; and the nested way, recursively. We all know that recursion is often absolutely necessary. But usually flat iteration suffices. In other languages (notoriously LISP and functional languages), there is a tendency to do it recursively anyways. For example, the following Python code illustrates a recursive way to copy a list that would be considered an example of good code in a language such as LISP: . def copylist(a): . if a: return a[:1] + copylist(a[1:]) . else: return a LISP, of course, was designed to make recursive processing like this easy and efficient. But it doesn't, IMHO, keep recursion from being much harder to figure out. Although this has a sort of coolness in that you can see the list copy operation reduced to its simplest possible form (in the same way that Game of Life is cool because you get all kinds of complexity from very simple rules), it completely misses the big picture. When I want to copy a list, I want to copy a list; I don't want to figure out the minimal rule set I could use to do it. Iteration fits the mind better. Python, IMO, wisely put the focus on iteration. POLYMORPHISM In many languages, the only way to get dynamic polymorphism is to subclass. If two classes are to share an interface, they have to both be subclasses of a common base class. If you have lots of classes that you want to share parts of their interfaces, you have to put them all into that heirarchy. The problem is, the world isn't a neatly organized tree, where every type of object must have functionality that is an exact proper subset of some other type of object. So what you end up with is this big, messy, inflexible hierarchy of classes that is difficult to make changes or add new options to. Many classes have stuff in them that ought not to be there, just to satisfy the requirements of subclassing. Oftentimes, the root class has lots of methods that many subclasses don't implement. Oftentimes, there will be subclasses with functionality that isn't polymorphic because the root class doesn't define virtual methods for them. (For an example of all this madness: in I/O hierarchies, the base class often has seek() and tell() methods, but since not all streams are seekable, it also has to have a seekable() method. Thus, polymorphic behavior and its benefits are abandoned in favor of the procedural way. Sure, for this case, you could just define a SeekableStream intermediate class, only for seekable streams. But here's the thing: there are any number of functionalities a stream may or may not have. Are you going to design a hierarchy with branches to account for all possible combinations of them?) Not so in Python. In Python, if you want to classes to have the same interface, then write two classes that have the same methods. Bam, you got polymorphism. No shoehorning into a heirarchy necessary. It's what we call duck typing. (If it looks like a duck, and floats like a duck, it's made of wood.) The flat method of polymorphism is so much better it isn't even funny. Again, Python chose wisely. -- CARL BANKS -- http://mail.python.org/mailman/listinfo/python-list
Re: Zen of Python
Timothy Fitz wrote: On 19 Jan 2005 15:24:10 -0800, Carl Banks [EMAIL PROTECTED] wrote: The gist of Flat is better than nested is be as nested as you have to be, no more, because being too nested is just a mess. Which I agree with, and which makes sense. However your gist is a different meaning. It's not that Flat is better than nested it's that Too flat is bad and too flat is nested so be as nested (or as flat) as you have to be and no more. Perhaps Tim Peters is far too concise for my feeble mind wink If it were scrutable, it wouldn't be Zen. :-) -- Robert Kern [EMAIL PROTECTED] In the fields of hell where the grass grows high Are the graves of dreams allowed to die. -- Richard Harter -- http://mail.python.org/mailman/listinfo/python-list
Re: rotor replacement
Robin Becker [EMAIL PROTECTED] writes: Presumably he is talking about crypo-export rules. In the past strong cryptography has been treated as munitions, and as such exporting it (especially from the USA) could have got you into very serious trouble. well since rotor is a german (1930's) invention it is a bit late for Amricans (Hollywood notwithstanding) to be worried about its export 1. I think the concern was not about exporting from the US, but rather importing into some countries that restrict the use of crypto. But the cat is out of the bag on that one too. Just about every web browser includes an SSL stack and those browsers are in use everywhere. 2. It's irrelevant for the purpose of export rules how old an invention is or where it was invented. I don't know where machine guns were invented, but they're at least 100 years old and you can't export those without a license either. My gripe with the crypto rules are not about the age or nationality of crypto rotor machines (rotor is not a clone of the Enigma by the way; it just operates on related principles) but rather on the control of information in general. Exporting a machine gun is much different from publishing a description of one. Software is just a precise type of description. -- http://mail.python.org/mailman/listinfo/python-list
Re: ElementTree cannot parse UTF-8 Unicode?
On Wed, 19 Jan 2005 16:35:23 -0800, Erik Bethke wrote: So it seems to me, that ElementTree is just not expecting to run into the Korean characters for it is at column 16 that these begin. Am I formatting the XML properly? You should post the file somewhere on the web. (I wouldn't expect Usenet to transmit it properly.) (Just jumping in to possibly save you a reply cycle.) -- http://mail.python.org/mailman/listinfo/python-list
Re: Zen of Python
Timothy Fitz wrote: On 19 Jan 2005 15:24:10 -0800, Carl Banks [EMAIL PROTECTED] wrote: The gist of Flat is better than nested is be as nested as you have to be, no more, because being too nested is just a mess. Which I agree with, and which makes sense. However your gist is a different meaning. It's not that Flat is better than nested it's that Too flat is bad and too flat is nested so be as nested (or as flat) as you have to be and no more. Perhaps Tim Peters is far too concise for my feeble mind wink Well, the way that the Zen is phrased, it implies a bit more than that. We all agree that there's a balance to be found between completely flat and extremely nested; the specific phrasing of the Zen conveys that (in the Python philosophy at least) the appropriate balance point is much closer to the completely flat side of things. It's not ... as nested (or as flat) as you have to be and no more, it's ... as nested as you have to be and no more, but if you need significant nesting, you might want to re-examine your design. ;) Jeff Shannon Technician/Programmer Credit International -- http://mail.python.org/mailman/listinfo/python-list
Re: Python and Excel
If it helps, I started a similar project a few years ago on SourceForge when I was just learning python called python2xlw. I haven't supported it for quite a while, however, I still use it a lot in my own work. I needed to create Excel files with scatter charts in them for a web interface so I went through the excercise of disassembling the BIFF codes of the older XLW format of excel and creating a byte stream representation of the spreadsheet that could be saved to file or sent directly to the web user as an excel application in there browser. The newer XLS format is a bit more complex and I didn't have enough documentation to create the charts I needed directly from python in the newer XLS format. (the current version of excel still understands XLW, however, so you're just a SAVE AS away from XLS.) As I think was mentioned in another post, you can create charts etc. using the COM interface for a client-type application, however, my goal was to create them on-the-fly directly from the web server without launching a server-side excel application. There is a nice Perl project called Spreadsheet::WriteExcel that John McNamara created that was very helpful to me at that time, however, it only created the worksheets, not charts. -- http://mail.python.org/mailman/listinfo/python-list
Re: Zen of Python
Jeff Shannon wrote: Timothy Fitz wrote: Which I agree with, and which makes sense. However your gist is a different meaning. It's not that Flat is better than nested it's that Too flat is bad and too flat is nested so be as nested (or as flat) as you have to be and no more. Perhaps Tim Peters is far too concise for my feeble mind wink Well, the way that the Zen is phrased, it implies a bit more than that. A Zen koan always implies more than the listener infers. -- http://mail.python.org/mailman/listinfo/python-list
Re: safest way to kill a thread
Thank for all helping and sorry that i overlooked the previous message. Peter Hansen wrote: [EMAIL PROTECTED] wrote: Should the 'daemonic' flag at setDaemon() function set to 1/TRUE or 0/FALSE to do such action? First of all, it's True and False in Python, not TRUE and FALSE. Secondly, the answer to the question was in the previous message where limodou told you about this in the first place. Go back and read it again... -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Zen of Python
On Wed, Jan 19, 2005 at 09:28:13PM -0500, Peter Hansen wrote: Jeff Shannon wrote: Timothy Fitz wrote: Which I agree with, and which makes sense. However your gist is a different meaning. It's not that Flat is better than nested it's that Too flat is bad and too flat is nested so be as nested (or as flat) as you have to be and no more. Perhaps Tim Peters is far too concise for my feeble mind wink Well, the way that the Zen is phrased, it implies a bit more than that. A Zen koan always implies more than the listener infers. I've met Zell Cohen, and you sir ... /got nothing. -Jack -- http://mail.python.org/mailman/listinfo/python-list
Pyzine #6 MIDI article
Would anyone here who has the Python and MIDI article from Pyzine #6 be willing to share it with me? -- http://mail.python.org/mailman/listinfo/python-list
Re: list item's position
Bob Smith wrote: Hi, I have a Python list. I can't figure out how to find an element's numeric value (0,1,2,3...) in the list. Here's an example of what I'm doing: Use enumerate() (new in Python 2.3, IIRC). Otherwise: for i in range(len(sequence)): item = sequence[i] ... for bar in bars: if 'str_1' in bar and 'str_2' in bar: print bar This finds the right bar, but not its list position. The reason I need to find its value is so I can remove every element in the list before it so that the bar I found somewhere in the list becomes element 0... does that make sense? Sure. You want to slice the list starting at the index of the first occurrence: index = min([i for i, item in enumerate(sequence) if 'str_1' in item and 'str_2' in item]) print sequence[index:] // m -- http://mail.python.org/mailman/listinfo/python-list
Re: list item's position
2 solutions: In [98]: bars = [str, foobaz, barbaz, foobar] In [99]: for bar in bars: : if 'bar' in bar and 'baz' in bar: : print bar : print bars.index(bar) : barbaz 2 In [100]: for i in range(len(bars)): .: if 'bar' in bars[i] and 'baz' in bars[i]: .: print bars[i] .: print i .: barbaz 2 The first one is slow and pretty, the second one is fast and (a bit) ugly. I believe that you should avoid range(len(x)) when you can, but use it when you need to know the index of something without an additional x.index() call. Peace Bill Mill bill.mill at gmail.com On Wed, 19 Jan 2005 22:04:44 -0500, Bob Smith [EMAIL PROTECTED] wrote: Hi, I have a Python list. I can't figure out how to find an element's numeric value (0,1,2,3...) in the list. Here's an example of what I'm doing: for bar in bars: if 'str_1' in bar and 'str_2' in bar: print bar This finds the right bar, but not its list position. The reason I need to find its value is so I can remove every element in the list before it so that the bar I found somewhere in the list becomes element 0... does that make sense? Thanks, Bob -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list