Announce : TimeDuration 0.1a released
This is a pure python module for parsing time interval strings, normalizing, comparing and ordering time intervals. This module is still in alpha phase. It handles string like : 1 hour, 15 minutes and 23.2 seconds 01:15:23.2 1h 15min 23.2sec Output from *nix uptime or time commands : 15 days, 23:04 0m2.496s It handles comparisons and sorting of TimeDuration objects. It normalizes time interval strings, e.g. : 5 d, 27 h, 75 m 120 s will normalize to 6 D 04:17:0.00 TODO: * Catch garbled input strings that might confuse the parser. * Create an iterable class to handle slices, min, max, sums, average, mean and stddev * More testing Homepage: http://statz.com/libs-TimeDuration/ Author : Andrew Lee (fiacre.patrick - at - gmail.com) -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
DoIt 0.1.0 Released
DoIt - A task execution tool (build-tool) = This is the first public release of DoIt Website: http://python-doit.sourceforge.net/ Release: DoIt 0.1.0 License: MIT Maintainer: [EMAIL PROTECTED] About - DoIt is a build tool that focus not only on making/building things but on executing any kind of tasks in an efficient way. Designed to be easy to use and get out of your way. DoIt like most build tools is used to execute tasks defined in a configuration file. Configuration files are python modules. The tasks can be python functions (or any callable) or an external shell script. DoIt automatically keeps track of declared dependencies executing only tasks that needs to be update (based on which dependencies have changed). In DoIt, unlike most(all?) build-tools, a task doesn't need to define a target file to use the execute only if not up-to-date feature. This make DoIt specially suitable for running test suites. DoIt can be used to perform any task or build anything, though it doesn't support automatic dependency discovery for any language. Cheers, Eduardo -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
ANN: pyspread 0.0.1
pyspread 0.0.1 is now available at: http://pyspread.sourceforge.net pyspread is a spreadsheet that accepts a pure python expression in each cell. Highlights: + No non-python syntax add-ons + Access to python modules from cells + 3D grid + Numpy object array for representation of string entry into grid cell + Numpy object array for representation of eval function array + Cell access via slicing of numpy function array + X, Y, and Z yield current cell location for relative reference Requires: Python 2.5, Numpy 1.0.4, and wxPython 2.8.7.1. License: GPL Best Regards Martin Manns -- mmanns at gmx.net -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
How to set proxy for a python script to run
Hi, everyone, I am using /usr/share/system-config-language/ language_gui.py in Python. For some reason I have to bypass the firewall using a proxy. I read the urllib reference and set http_proxy=my proxy. But it didn't work. Is there anyway that we can set the proxy? -- http://mail.python.org/mailman/listinfo/python-list
Re: get quote enclosed field in a line
[EMAIL PROTECTED] wrote: is there a simple way in perl, python, or awk/shell/pipe, that gets the user agent field in a apache log? Something like: # cut -d '' -f 6 httpd-access.log ? -- mph Doesn't it feel like autosplit mode never gets any run time? perl -laF'' -ne'print $F[5]' access_log -- http://mail.python.org/mailman/listinfo/python-list
pprint module and newer standard types
Hi, When I try and use pprint on standard types I get varying 'quality of output'. Lists will wrap nicely to multiple lines as will dicts, but sets and defaultdicts give one long unreadable line. Is their a chance to get this changed so that more built-in types look pretty when printed with pprint? I just did a small trial on an early version of Python 3 and sets don't seem to obey pprint.pprints width argument, the same way that lists do: Python 3.0a1 (py3k:57844, Aug 31 2007, 16:54:27) [MSC v.1310 32 bit (Intel)] on win32 from pprint import pprint as pp pp(list(range(3)), width=4) [0, 1, 2] pp(set(range(3)), width=4) {0, 1, 2} - Paddy. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to have unittest tests to be executed in the order they appear?
Roy Smith [EMAIL PROTECTED] writes: Ben Finney [EMAIL PROTECTED] wrote: Surely, since suddenly implies you changed one small area of the code, that area of the code is the best place to look for what caused the failure. Sometimes it's the environment that's changed. Yes, I know, a good unit test doesn't depend on the environment, but in real life, that's sometimes difficult to achieve. Fair enough, I hadn't considered that case of suddenly. In that case, I would recommend a change to the test *reporter*, so that the tests are still run in an arbitrary sequence, but the failures are reported in some desired sequence. -- \ “Holy tintinnabulation, Batman!” —Robin | `\ | _o__) | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
How to set proxy for a python script to run
Hi, I am using a script written in Python. For some reasons I should pass the fireware by proxy setting. But it seems not work when I set the 'http_proxy' 'ftp_proxy' environment variable. I also expored 'HTTP_PROXY' 'FTP_PROXY', but the problem remained. How can I set proxy for it to run the script? -- http://mail.python.org/mailman/listinfo/python-list
Re: How to set proxy for a python script to run
Adam pisze: Hi, everyone, I am using /usr/share/system-config-language/ language_gui.py in Python. For some reason I have to bypass the firewall using a proxy. I read the urllib reference and set http_proxy=my proxy. But it didn't work. Is there anyway that we can set the proxy? I did sth. like this: proxy_url = http://user:[EMAIL PROTECTED]:8080 proxy_support = urllib2.ProxyHandler({'http': proxy_url}) opener = urllib2.build_opener(proxy_support) urllib2.install_opener(opener) src = urllib2.urlopen(url) now you can easily read from src. -- Soltys Free software is a matter of liberty not price -- http://mail.python.org/mailman/listinfo/python-list
Re: why function got dictionary
AlFire [EMAIL PROTECTED] wrote: Diez B. Roggisch wrote: Q: why function got dictionary? What it is used for? because it is an object, and you can do e.g. you mean an object in the following sense? isinstance(g,object) True where could I read more about that? This is a very useful feature. As just one example, the CherryPy web server framework lets you define a class to handle one directory in a web site, where each page is mapped to member functions. However, you also need to include support functions that should not be exposed as web pages. To do that, you just add an exposed attribute to the function: class MyWebPage: ... def index( self, ... ): pass index.exposed = 1 def notExposed( self, ... ): pass def request( self, ... ): pass request.exposed = 1 -- Tim Roberts, [EMAIL PROTECTED] Providenza Boekelheide, Inc. -- http://mail.python.org/mailman/listinfo/python-list
codec for html/xml entities!?
Hi friends, I've been OFF-Python now for quite a while and am glad being back. At least to some part as work permits. Q: What's a good way to encode and decode those entities like euro; or #8364; ? I need isolated functions to process lines. Looking at the xml and sgmlib stuff I didn't really get a clue as to what's the most pythonic way. Are there library functions I didn't see? FYI, here is what I hacked down and what will probably (hopefully...) do the job. Feel free to comment. # -*- coding: iso-8859-1 -*- \ entity_stuff.py, mb, 2008-03-14, 2008-03-18 import htmlentitydefs import re RE_OBJ_entity = re.compile('(.+?;)') def entity2uc(entity): Convert entity like #123; to unichr. Return (result,True) on success or (input string, False) otherwise. Example: entity2cp('euro;') - (u'\u20ac',True) entity2cp('#x20ac;') - (u'\u20ac',True) entity2cp('#8364;') - (u'\u20ac',True) entity2cp('foobar;') - ('foobar;',False) gotCodepoint = False gotUnichr = False if entity.startswith('#'): if entity[2] == 'x': base = 16 digits = entity[3:-1] else: base = 10 digits = entity[2:-1] try: v = int(digits,base) gotCodepoint = True except: pass else: v = htmlentitydefs.name2codepoint.get(entity[1:-1],None) if not v is None: gotCodepoint = True if gotCodepoint: try: v = unichr(v) gotUnichr = True except: pass if gotUnichr: return v, gotUnichr else: return entity, gotUnichr def line_entities_to_uc(line): result = [] cntProblems = 0 for e in RE_OBJ_entity.split(line): if e.startswith(''): e,success = entity2uc(e) if not success: cntProblems += 1 result.append(e) return u''.join(result), cntProblems def uc2entity(uc): cp = ord(uc) if cp 127: name = htmlentitydefs.codepoint2name.get(cp,None) if name: result = '%s;' % name else: result = '#x%x;' % cp else: result = chr(cp) return result def encode_line(line): return ''.join([uc2entity(u) for u in line]) if 1 and __name__==__main__: import codecs infile = 'temp.ascii.xml' outfile = 'temp.utf8.xml' of = codecs.open(outfile,'wb','utf-8') totalProblems = 0 totalLines = 0 for line in file(infile,'rb'): line2, cntProblems = line_entities_to_uc(line) of.write(line2) totalLines += 1 totalProblems += cntProblems of.close() print print Summary: print Infile : %s % (infile,) print Outfile: %s % (outfile,) print ' %8d %s %s' % (totalLines, ['lines','line'][totalLines==1], 'written.') print ' %8d %s %s' % (totalProblems, ['entities','entity'][totalProblems==1], 'left unconverted.') print '%s' % ('Done.',) Have a nice day and ru, Martin (read you, ;-) -- http://mail.python.org/mailman/listinfo/python-list
Re: codec for html/xml entities!?
Martin Bless wrote: What's a good way to encode and decode those entities like euro; or #8364; ? Hmm, since you provide code, I'm not quite sure what your actual question is. So I'll just comment on the code here. def entity2uc(entity): Convert entity like #123; to unichr. Return (result,True) on success or (input string, False) otherwise. Example: entity2cp('euro;') - (u'\u20ac',True) entity2cp('#x20ac;') - (u'\u20ac',True) entity2cp('#8364;') - (u'\u20ac',True) entity2cp('foobar;') - ('foobar;',False) Is there a reason why you return a tuple instead of just returning the converted result and raising an exception if the conversion fails? Stefan -- http://mail.python.org/mailman/listinfo/python-list
Re: Can't do a multiline assignment!
Michael Torrie schrieb: [EMAIL PROTECTED] wrote: You didn't really write that at the Python's interpreter, did you? It's wrong. The way that would really go at the interpreter is like I did actually run it through the interpreter, but I didn't copy and past it to the e-mail. Thought that I saw this behavior, but clearly I must not have. classvar1 and classvar2 might be class variables, but in they don't work as they would in C++ or Java (like the ones you declare with the 'static' modified). Still, it's not pythonic to define instance variables in this way, as far as I can tell. I've seen used that for quite a while. It is more clear to provide defaults that way. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Request a short code review
Hello, I would personally avoid using type as variable name, or key, because built-in class type already exists. As I understand your code, it was not your intention to override it. ++ Sam -- http://mail.python.org/mailman/listinfo/python-list
Re: Database vs Data Structure?
erikcw a écrit : Hi, I'm working on a web application where each user will be creating several projects in there account, each with 1,000-50,000 objects. Each object will consist of a unique name, an id, and some meta data. The number of objects will grow and shrink as the user works with their project. I'm trying to decided whether to store the objects in the database (each object gets it's own row) or to use some sort of data-structure (maybe nested dictionaries or a custom class) and store the pickled data-structure in a single row in the database (then unpickle the data and query in memory). Yuck. Fighting against the tool won't buy you much - except for interoperability and maintainance headeaches. Either use your relational database properly, or switch to an object db - like ZODB or Durus - if you're ok with the implications (no interoperability, no simple query langage, and possibly bad performances if your app does heavy data processing). A few requirements: -Fast/scalable (web app) -able to query objects based on name and id. -will play nicely with versioning (undo/redo) Versionning is a somewhat othogonal problem. Any input on the best way to go? My very humble opinion - based on several years of working experience with both the Zodb and many RDBMS - is quite clear : use a RDBMS and use it properly. -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie question about for...in range() structure
[EMAIL PROTECTED] a écrit : (snip - already answered) def fact(n): total = 0 n = int(n) while n 0: total *= n n -=1 return total You may be interested in a very different way to get the same result: from operator import mul def fact(n): return reduce(mul, xrange(1, n+1), 1) (snip) -- http://mail.python.org/mailman/listinfo/python-list
python server side scripting with apache2
Hi Guys, I want to do server side scripting in python for one of my applications. So after installing apache2, python lib for apache2 (libapache2), and doing some changes in default file in /etc/apache2/sites-available i was able to execute python scripts in /var/www/ directory from client side. but i want to place all of my python scripts in some other directory like /home/username/myserver, so what changes i have to make in configuration files at /etc/apache2/apache2.conf or some other place (like /etc/apache2/sites-available/default), so that my server side scripts placed in this folder (/home/username/myserver) gets executed from client side using some url like http://machine-ip/home/username/myserver/abc.py. Thanks Regards Syed -- http://mail.python.org/mailman/listinfo/python-list
testing client-server sockets
Hi, I have a client-server socket script in python. Something like this http://ubuntuforums.org/showthread.php?t=208962 Now the problem I have is that I want to try to connect the client to the server on the same machine, but it gives me a 'port already in use' error. I just want the client to connect to the server for testing purposes. Any suggestions on how I should do this? Thanks Astan -- Formulations of number theory: Complete, Consistent, Non-trivial. Choose two. Animal Logic http://www.animallogic.com Please think of the environment before printing this email. This email and any attachments may be confidential and/or privileged. If you are not the intended recipient of this email, you must not disclose or use the information contained in it. Please notify the sender immediately and delete this document if you have received it in error. We do not guarantee this email is error or virus free. -- http://mail.python.org/mailman/listinfo/python-list
Re: testing client-server sockets
Server code: import os, sys, socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) host = '' port = 5602 s.bind((host,port)) try: s.listen(1) while 1: conn, addr = s.accept() print 'client is at', addr data = conn.recv(100) data = data * 10 z = raw_input() conn.send(data) conn.close() except Exception: s.close() Client code: import sys, os, socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) host = 'hostIP' port = 5602 s.connect((host,port)) s.send(dlg.user.GetValue()) i =0 while True: data = s.recv(100) i+=1 if (i5): print data if not data: break print 'received', len(data), 'bytes' s.close() David Harrison wrote: On 18/04/2008, Astan Chee [EMAIL PROTECTED] wrote: Hi, I have a client-server socket script in python. Something like this http://ubuntuforums.org/showthread.php?t=208962 Now the problem I have is that I want to try to connect the client to the server on the same machine, but it gives me a 'port already in use' error. I just want the client to connect to the server for testing purposes. Any suggestions on how I should do this? Thanks Astan Can you post the client / server code for us ? It sounds like it's likely to be a minor bug. -- Formulations of number theory: Complete, Consistent, Non-trivial. Choose two. Animal Logic http://www.animallogic.com Please think of the environment before printing this email. This email and any attachments may be confidential and/or privileged. If you are not the intended recipient of this email, you must not disclose or use the information contained in it. Please notify the sender immediately and delete this document if you have received it in error. We do not guarantee this email is error or virus free. -- http://mail.python.org/mailman/listinfo/python-list
Re: testing client-server sockets
On 18/04/2008, Astan Chee [EMAIL PROTECTED] wrote: Server code: import os, sys, socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) host = '' port = 5602 s.bind((host,port)) try: s.listen(1) while 1: conn, addr = s.accept() print 'client is at', addr data = conn.recv(100) data = data * 10 z = raw_input() conn.send(data) conn.close() except Exception: s.close() Client code: import sys, os, socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) host = 'hostIP' port = 5602 s.connect((host,port)) s.send(dlg.user.GetValue()) i =0 while True: data = s.recv(100) i+=1 if (i5): print data if not data: break print 'received', len(data), 'bytes' s.close() I just ran the code (albeit with a tiny change to send a small string instead so I could see what was going on), and it seems to work fine ... anything else that might be different ? -- http://mail.python.org/mailman/listinfo/python-list
Re: Metaprogramming Example
andrew cooke a écrit : bruno: Ho, and yes : one day, you'll get why it's such a good thing to unite functions and methods !-) me: PS Is there anywhere that explains why Decorators (in the context of functions/methods) are so good? I've read lots of things saying they are good, but no real justification of why. in the text above i wrote Decorators rather than Descriptors. it was in response to bruno's comment, also above. sorry for the confusion. Ho, you meant Descriptors ? Well, a first point is that the support for methods is built on a combination of two general purpose constructs - callable objects and the descriptor protocol - instead of being a special-case construct by itself. IOW, this is build *with* Python itself, instead of being built *into* Python. Practically, this means that (amongst other niceties) : - you can define functions outside classes and use them as instance or class methods - you can add/replaces methods dynamically on a per-class or per-instance basis - you can access the function object of a method and use it as a function - you can define your own callable types, that - if you implement the appropriate support for the descriptor protocol - will be usable as methods too also, sorry for the inflammatory language Which one ??? by referring to the titanic i didn't mean that python was a disaster, rather that the iceberg is still there (i am not 100% sure what the iceberg is, but it's something to do with making namespaces explicit in some places and not others). I guess you're thinking of the self argument, declared in the function's signature but not explicitly passed when calling the method ? If so, the fact is you *do* pass it explicitly - by calling the function *as a method of an objet*. Given the following definitions: def func(obj, data): print obj : %s - data : %s % (obj, data) class Foo(object): meth = func f = Foo() What the difference between: func(f, 42) and f.meth(42) In both cases, f is directly and explicitly involved as one of the targets of the call. My 2 cents... -- http://mail.python.org/mailman/listinfo/python-list
Air Max 90 paypal wholesaler ( paypal accept ) ( www.gotoorder.cn )Air Mir 90 paypal wholesaler ( paypal accept ) ( www.gotoorder.cn )
We are the professional and serious wholesaler of brand products,such as shoes, clothing, handbags, sunglasses, hats, belts, and so on.We have many brands such as nike,adidas,puma,Gucci,North face.All goods are with best service,highest quality,competitive price,and safe timely deliverry If you are interested in these goods,don’t hasitate to cantact us please. our website: http://www. top-saler.cn MSN(email): [EMAIL PROTECTED] Air Max 360 paypal wholesaler ( paypal accept ) ( www.gotoorder.cn ) Air Max 90 paypal wholesaler ( paypal accept ) ( www.gotoorder.cn )Air Mir 90 paypal wholesaler ( paypal accept ) ( www.gotoorder.cn ) Air Max LTD paypal wholesaler ( paypal accept ) ( www.gotoorder.cn ) air Max LTD paypal wholesaler ( paypal accept ) ( www.gotoorder.cn ) Air Max 2003 paypal wholesaler ( paypal accept ) ( www.gotoorder.cn ) Air Max 2003 paypal wholesaler ( paypal accept ) ( www.gotoorder.cn ) Air Max 87 paypal wholesaler ( paypal accept ) ( www.gotoorder.cn ) Air Max 95 paypal wholesaler ( paypal accept ) ( www.gotoorder.cn ) Air Max 95 paypal wholesaler ( paypal accept ) ( www.gotoorder.cn ) Air Max 97 paypal wholesaler ( paypal accept ) ( www.gotoorder.cn ) Air Max 95 360 paypal wholesaler ( paypal accept ) ( www.gotoorder.cn ) Air Max 90 360 paypal wholesaler ( paypal accept ) ( www.gotoorder.cn ) Air zoom hateu paypal wholesaler ( paypal accept ) ( www.gotoorder.cn ) Air Max 91 paypal wholesaler ( paypal accept ) ( www.gotoorder.cn ) Air Max 87 paypal wholesaler ( paypal accept ) ( www.gotoorder.cn ) Air Max 89 paypal wholesaler ( paypal accept ) ( www.gotoorder.cn ) Air Max Tn paypal wholesaler ( paypal accept ) ( www.gotoorder.cn ) Tn Air Max Tn paypal wholesaler ( paypal accept ) ( www.gotoorder.cn ) Bape paypal wholesaler ( paypal accept ) ( www.gotoorder.cn ) new Bape paypal wholesaler ( paypal accept ) ( www.gotoorder.cn ) Old bape paypal wholesaler ( paypal accept ) ( www.gotoorder.cn ) Dunk paypal wholesaler ( paypal accept ) ( www.gotoorder.cn ) s Dunk paypal wholesaler ( paypal accept ) ( www.gotoorder.cn ) High Dunk paypal wholesaler ( paypal accept ) ( www.gotoorder.cn ) Dunk paypal wholesaler ( paypal accept ) ( www.gotoorder.cn ) Shox paypal wholesaler ( paypal accept ) ( www.gotoorder.cn ) Shox NZ paypal wholesaler ( paypal accept ) ( www.gotoorder.cn ) Shox R3 paypal wholesaler ( paypal accept ) ( www.gotoorder.cn ) Shox R4 paypal wholesaler ( paypal accept ) ( www.gotoorder.cn ) Shox R5 paypal wholesaler ( paypal accept ) ( www.gotoorder.cn ) Air Max 360 paypal wholesaler ( paypal accept ) ( www.gotoorder.cn ) Air Max 90 paypal wholesaler ( paypal accept ) ( www.gotoorder.cn )Air Mir 90 paypal wholesaler ( paypal accept ) ( www.gotoorder.cn ) Air Max LTD paypal wholesaler ( paypal accept ) ( www.gotoorder.cn ) air Max LTD paypal wholesaler ( paypal accept ) ( www.gotoorder.cn ) Air Max 2003 paypal wholesaler ( paypal accept ) ( www.gotoorder.cn ) Air Max 2003 paypal wholesaler ( paypal accept ) ( www.gotoorder.cn ) Air Max 87 paypal wholesaler ( paypal accept ) ( www.gotoorder.cn ) Air Max 95 paypal wholesaler ( paypal accept ) ( www.gotoorder.cn ) Air Max 95 paypal wholesaler ( paypal accept ) ( www.gotoorder.cn ) Air Max 97 paypal wholesaler ( paypal accept ) ( www.gotoorder.cn ) Air Max 95 360 paypal wholesaler ( paypal accept ) ( www.gotoorder.cn ) Air Max 90 360 paypal wholesaler ( paypal accept ) ( www.gotoorder.cn ) Air zoom hateu paypal wholesaler ( paypal accept ) ( www.gotoorder.cn ) Air Max 91 paypal wholesaler ( paypal accept ) ( www.gotoorder.cn ) Air Max 87 paypal wholesaler ( paypal accept ) ( www.gotoorder.cn ) Air Max 89 paypal wholesaler ( paypal accept ) ( www.gotoorder.cn ) Air Max Tn paypal wholesaler ( paypal accept ) ( www.gotoorder.cn ) Tn Air Max Tn paypal wholesaler ( paypal accept ) ( www.gotoorder.cn ) Bape paypal wholesaler ( paypal accept ) ( www.gotoorder.cn ) new Bape paypal wholesaler ( paypal accept ) ( www.gotoorder.cn ) Old bape paypal wholesaler ( paypal accept ) ( www.gotoorder.cn ) Dunk paypal wholesaler ( paypal accept ) ( www.gotoorder.cn ) s Dunk paypal wholesaler ( paypal accept ) ( www.gotoorder.cn ) High Dunk paypal wholesaler ( paypal accept ) ( www.gotoorder.cn ) Dunk paypal wholesaler ( paypal accept ) ( www.gotoorder.cn ) Shox paypal wholesaler ( paypal accept ) ( www.gotoorder.cn ) Shox NZ paypal wholesaler ( paypal accept ) ( www.gotoorder.cn ) Shox R3 paypal wholesaler ( paypal accept ) ( www.gotoorder.cn ) Shox R4 paypal wholesaler ( paypal accept ) ( www.gotoorder.cn ) Shox R5 paypal wholesaler ( paypal accept ) ( www.gotoorder.cn ) -- http://mail.python.org/mailman/listinfo/python-list
Re: testing client-server sockets
On 18/04/2008, Astan Chee [EMAIL PROTECTED] wrote: Hi, I have a client-server socket script in python. Something like this http://ubuntuforums.org/showthread.php?t=208962 Now the problem I have is that I want to try to connect the client to the server on the same machine, but it gives me a 'port already in use' error. I just want the client to connect to the server for testing purposes. Any suggestions on how I should do this? Thanks Astan Can you post the client / server code for us ? It sounds like it's likely to be a minor bug. -- http://mail.python.org/mailman/listinfo/python-list
Re: Can't do a multiline assignment!
[EMAIL PROTECTED] a écrit : On Apr 17, 12:34 pm, Michael Torrie [EMAIL PROTECTED] wrote: Another thing to consider is that referencing a member of a class or instance already *is* a dictionary lookup. It's how python works. Thus dictionaries are optimized to be fast. Since strings are immutable, python hashes them into a fast lookup pointer. So every time you say mydict[mykey], it already knows the lookup pointer (hash) for mykey (the string) and can find the dictionary entry very quickly, ideally in O(1) time (well maybe log(N)). Thus putting your headers in a dictionary is actually a really good idea for performance reasons. I didn't know about that, thanks. So after all the trouble I went through writing those 200 loc I actually maid it worse... That's an understatement. -- http://mail.python.org/mailman/listinfo/python-list
Re: testing client-server sockets
Wierd. It works now. I must've changed something. Oh well, thanks anyway. David Harrison wrote: On 18/04/2008, Astan Chee [EMAIL PROTECTED] wrote: Server code: import os, sys, socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) host = '' port = 5602 s.bind((host,port)) try: s.listen(1) while 1: conn, addr = s.accept() print 'client is at', addr data = conn.recv(100) data = data * 10 z = raw_input() conn.send(data) conn.close() except Exception: s.close() Client code: import sys, os, socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) host = 'hostIP' port = 5602 s.connect((host,port)) s.send(dlg.user.GetValue()) i =0 while True: data = s.recv(100) i+=1 if (i5): print data if not data: break print 'received', len(data), 'bytes' s.close() I just ran the code (albeit with a tiny change to send a small string instead so I could see what was going on), and it seems to work fine ... anything else that might be different ? -- Formulations of number theory: Complete, Consistent, Non-trivial. Choose two. Animal Logic http://www.animallogic.com Please think of the environment before printing this email. This email and any attachments may be confidential and/or privileged. If you are not the intended recipient of this email, you must not disclose or use the information contained in it. Please notify the sender immediately and delete this document if you have received it in error. We do not guarantee this email is error or virus free. -- http://mail.python.org/mailman/listinfo/python-list
Fwd: is file open in system ? - other than lsof
the idea of eg does not work for me because, what i do: get list of files, check 1st file open ? process 1st file, (this may take several seconds... ) check 2nd file open? i have to check it here, because 2nd file may be opened while i process file 1 process 2nd file, (this may take several seconds... ) and so on.. in this case, having list of open files at begining of processes is useless... anyway thanks. -- Forwarded message -- From: Nick Craig-Wood [EMAIL PROTECTED] Date: 17.Nis.2008 19:30 Subject: Re: is file open in system ? - other than lsof To: python-list@python.org Thomas Guettler [EMAIL PROTECTED] wrote: bvidinli schrieb: is there a way to find out if file open in system ? - please write if you know a way other than lsof. because lsof if slow for me. i need a faster way. i deal with thousands of files... so, i need a faster / python way for this. thanks. On Linux there are symlinks from /proc/PID/fd to the open files. You could use this: #!/usr/bin/env python import os pids=os.listdir('/proc') for pid in sorted(pids): try: int(pid) except ValueError: continue fd_dir=os.path.join('/proc', pid, 'fd') for file in os.listdir(fd_dir): try: link=os.readlink(os.path.join(fd_dir, file)) except OSError: continue print pid, link Unfortunately I think that is pretty much exactly what lsof does so is unlikely to be any faster! However if you have 1000s of files to check you only need to do the above scan once and build a dict with all open files in whereas lsof will do it once per call so that may be a useful speedup. Eg import os pids=os.listdir('/proc') open_files = {} for pid in sorted(pids): try: int(pid) except ValueError: continue fd_dir=os.path.join('/proc', pid, 'fd') try: fds = os.listdir(fd_dir) except OSError: continue for file in fds: try: link=os.readlink(os.path.join(fd_dir, file)) except OSError: continue if not os.path.exists(link): continue open_files.setdefault(link, []).append(pid) for link in sorted(open_files.keys()): print %s : %s % (link, , .join(map(str, open_files[link]))) You might want to consider http://pyinotify.sourceforge.net/ depending on exactly what you are doing... -- Nick Craig-Wood [EMAIL PROTECTED] -- http://www.craig-wood.com/nick -- http://mail.python.org/mailman/listinfo/python-list -- İ.Bahattin Vidinli Elk-Elektronik Müh. --- iletisim bilgileri (Tercih sirasina gore): skype: bvidinli (sesli gorusme icin, www.skype.com) msn: [EMAIL PROTECTED] yahoo: bvidinli +90.532.7990607 +90.505.5667711 -- http://mail.python.org/mailman/listinfo/python-list
Re: Unicode chr(150) en dash
On Thu, 17 Apr 2008 20:57:21 -0700 (PDT) hdante [EMAIL PROTECTED] wrote: Don't use old 8-bit encodings. Use UTF-8. Yes, I'll try. But is a problem when I only want to read, not that I'm trying to write or create the content. To blame I suppose is Microsoft's commercial success. They won't adhere to standars if that doesn't make sense for their business. I'll change the approach trying to filter the contents with htmllib and mapping on my own those troubling characters. Anyway this has been a very instructive dive into unicode for me, I've got things cleared up now. Thanks to everyone for the great help. -- http://mail.python.org/mailman/listinfo/python-list
Re: MySQL hardcoding?
On Thu, 17 Apr 2008 22:00:21 GMT John Machin [EMAIL PROTECTED] wrote: The empirical evidence from other recent postings is that you are mucking about with Spanish-language newspaper articulos on the web ... so why charset = Windows-1251, which is Cyrillic (i.e. Russian etc)?? Perhaps you mean 1252 which is Microsoft's latin1 with extras. HTH, John -- http://mail.python.org/mailman/listinfo/python-list Yes John, thanks. The only problem is MySQL doesn't include a cp1252 or Windows-1252 or ansi. I'm trying to find my way with different approaches. But there is certainly a problem if an application goes to the wrong folder to get data as MySQL seems to be doing. Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: py3k s***s
Diez B. Roggisch schrieb: And I have been benefiting from Python in general, so far. Thanks, community. But now... I'll probably stop posting here for now, I may stop other things too. Just my 2c. You know what I was just wondering about? All these C-written cross-platform libraries (which Python users benefit from, most probably including evven you) that run on different unixes windows, which are a much greater diversity to handle than the not-even-yet-settled differences between Py3K 2.x. How the heck do they do that? Oh, and these dreaded 64 bit processors, possibly with multi-cores, which need changes in code as well, to be utilized to their power. But then, these guys most probably don't whine about diversity and constant change, and cry out useless threats to people who probably can't care less. Fare well, if you must. But getting mad over something which impact you can't even judge right now is childish. Nothing else. Diez 1+ -- http://mail.python.org/mailman/listinfo/python-list
Re: What can we do about all the spam that the list is getting?
On Thu, 17 Apr 2008 13:30:18 -0500, Grant Edwards wrote: When using Google Groups can one kill all posts made via Google Groups? Presuming he has no burning need to see his own posts (something that can't be said for everybody in the history of Usenet), it might still be a viable approach. The problem is, if we had followed that advice, none of us would have seen his post. -- http://mail.python.org/mailman/listinfo/python-list
Re: I just killed GIL!!!
Rhamphoryncus [EMAIL PROTECTED] wrote: On Apr 17, 7:40 am, Steve Holden [EMAIL PROTECTED] wrote: I'd love to be wrong about that, but the GIL *has* been the subject of extensive efforts to kill it over the last five years, and it has survived despite the best efforts of the developers. Yo. http://code.google.com/p/python-safethread/ Sounds very interesting. I particularly liked this bit from the web page - an excellent solution to fine grained locking. Sending only immutable objects between threads is very like the functional approach used by Erlang which is extremely good at concurrency. Which objects can be shared between threads You probably know how to append to a list or modify a dict. When confronted with threading though you may start to wonder, what happens if two threads modify a list or a dict simultaneously? There's two common answers to this: * 1. Corruption. This is the default in C, and to a lesser degree Java. It doesn't limit you much and can be faster, but it requires some deep voodoo to know when you're using it right. * 2. Locks. All the operations internally lock the object. This makes them individually correct, but they'll be wrong again if you try to compose them into larger operations. It also adds a significant performance penalty. My priority is making it easy to write correct programs, and neither of those options are good enough. Instead, I take a third option as my default: * 3. Make sharing impossible, avoiding the question. list and dict cannot be shared between threads. Any attempt to pass a list or dict into something like a Queue will raise a TypeError. This ensures any thread interaction is explicit, rather than implicit. See also: The Zen of Python Of course if you couldn't share any objects then you'd just have processes, which are quite awkward to use. Instead, I only make mutable objects like list and dict unshareable, while immutable int and str objects can still be shared. Further, mutable objects that provide an explicit API for use between threads are also shareable. -- Nick Craig-Wood [EMAIL PROTECTED] -- http://www.craig-wood.com/nick -- http://mail.python.org/mailman/listinfo/python-list
Brand Watches CITIZEN Eco Drive Women's Black Dial 2-Hand Watch SY2030-54E Discount, Replica, Fake
Brand Watches CITIZEN Eco Drive Women's Black Dial 2-Hand Watch SY2030-54E Discount, Replica, Fake Browse our CITIZEN Eco Drive Women's Black Dial 2-Hand Watch SY2030-54E replica watches, which is sure the watch you are looking for at low price. There are more high quality designer watch replicas for selection CITIZEN Eco Drive Women's Black Dial 2-Hand Watch SY2030-54E Link : http://www.watches-brand.com/Replica-Citizen-6180.html Brand : Citizen ( http://www.watches-brand.com/Citizen-Replica.html ) Model : CITIZEN Eco Drive Women's Black Dial 2-Hand Watch SY2030-54E Description : pWatch with Stainless Steel band. Stainless Steel Rectangular Case with diamonds. Scratch Resistant Mineral Crystal. Quartz Movement. Water resistant up to 30 meters./p Sale Price : $ 210.00 CITIZEN Eco Drive Women's Black Dial 2-Hand Watch SY2030-54E Details : ul liBrand: Citizen/li liBand material: stainless-steel/li liCase material: Stainless-Steel/li liDial color: Black/li liDial window material: Scratch Resistant Mineral Crystal/li liWater-resistant to 30 meters/li /ul CITIZEN Eco Drive Women's Black Dial 2-Hand Watch SY2030-54E is new brand replica, join thousands of satisfied customers and buy your Citizen with total satisfaction. A watches-brand.COM 30 Day Money Back Guarantee is included with every Citizen Replica Series for secure, risk-free online shopping. watches-brand.COM does not charge sales tax for the Fake CITIZEN Eco Drive Women's Black Dial 2-Hand Watch SY2030-54E. All of our replica watches are shipped via EMS to worldwide. Normally it takes 3days to prepare the fake watch you ordered and 5-10days to transmit depending on the different destination.We pay for the free shipping cost for total quantity over 20 pcs. The EMS tracking NO. will be sent by email when an order is shipped from our warehouse. No more other charges from watches-brand.com such as the tax. If you have any other questions please check our other pages or feel free to email us by [EMAIL PROTECTED] The Same Replica Citizen Watches Series : Citizen Eco-Drive Alarm (Women's Watch) : http://www.watches-brand.com/Replica-Citizen-6181.html Citizen Eco-Drive Black Dial (Women's Watch) : http://www.watches-brand.com/Replica-Citizen-6182.html Citizen Eco-Drive Black dial (Women's Watch) : http://www.watches-brand.com/Replica-Citizen-6183.html Citizen Eco-Drive Black dial (Women's Watch) : http://www.watches-brand.com/Replica-Citizen-6184.html Citizen Eco-Drive Black dial (Women's Watch) : http://www.watches-brand.com/Replica-Citizen-6185.html Citizen Eco-Drive Black dial (Women's Watch) : http://www.watches-brand.com/Replica-Citizen-6186.html Citizen Eco-Drive Black dial (Women's Watch) : http://www.watches-brand.com/Replica-Citizen-6187.html Citizen Eco-Drive Black dial (Women's Watch) : http://www.watches-brand.com/Replica-Citizen-6188.html Citizen Eco-Drive Blue dial (Women's Watch) : http://www.watches-brand.com/Replica-Citizen-6189.html Citizen Eco-Drive Blue dial (Women's Watch) : http://www.watches-brand.com/Replica-Citizen-6190.html Brand Watches CITIZEN Eco Drive Women's Black Dial 2-Hand Watch SY2030-54E Discount, Replica, Fake -- http://mail.python.org/mailman/listinfo/python-list
Re: Fwd: is file open in system ? - other than lsof
On 2008-04-17, bvidinli [EMAIL PROTECTED] wrote: is there another way, any python command sequence that i can check if a file is open at the time of before i process file i am not interested in the file may be written after i access it.. the important point is the time at i first access it. my routine is something like: for i in listoffiles: checkfileopen(i) processfile() This code does not give you what you are after; in between 'checkfileopen()' and 'processfile()' somebody may open the file and mess with it. I quite doubt that you can get what you want, at OS level. Even if you get exclusive open(), you are not safe imho. After you opened the file for access (and before you perform the read() call), another process may also open it, and alter the data while you are reading. The same may happen between 2 read() calls. Note that a read() at OS level is not the same as a read() at Python (or C fread()) level. Python pretends to read an entire file in one call, but the OS is using disk-blocks of the underlying file system as unit of read/write. In other words, even if nobody messes with the file at the moment you open it, you don't necessarily get an uncorrupted file afaik. Sincerely, Albert -- http://mail.python.org/mailman/listinfo/python-list
Re: Database vs Data Structure?
On Apr 18, 12:23 am, I V [EMAIL PROTECTED] wrote: On Thu, 17 Apr 2008 19:30:33 -0700, erikcw wrote: use some sort of data-structure (maybe nested dictionaries or a custom class) and store the pickled data-structure in a single row in the database (then unpickle the data and query in memory). Why would you want to do this? I don't see what you would hope to gain by doing this, over just using a database. Are databases truly another language from Python, fundamentally? -- http://mail.python.org/mailman/listinfo/python-list
Re: Database vs Data Structure?
On 2008-04-18 05:37, erikcw wrote: Hi, I'm working on a web application where each user will be creating several projects in there account, each with 1,000-50,000 objects. Each object will consist of a unique name, an id, and some meta data. The number of objects will grow and shrink as the user works with their project. I'm trying to decided whether to store the objects in the database (each object gets it's own row) or to use some sort of data-structure (maybe nested dictionaries or a custom class) and store the pickled data-structure in a single row in the database (then unpickle the data and query in memory). A few requirements: -Fast/scalable (web app) -able to query objects based on name and id. -will play nicely with versioning (undo/redo) Any input on the best way to go? Relational databases offer the best scalability and reliability, so I'd go for those as backend. If your data is mostly read-only and usually only touches a small part of your database (e.g. the data for a day or two), then you can increase query performance by keeping that part in an in-memory database (e.g. use sqlite or Oracle TimesTen) and only update the copy in case something changes in the backend. Regards, -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Apr 18 2008) Python/Zope Consulting and Support ...http://www.egenix.com/ mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ mxODBC, mxDateTime, mxTextTools ...http://python.egenix.com/ Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 -- http://mail.python.org/mailman/listinfo/python-list
Re: Unicode chr(150) en dash
On Fri, 2008-04-18 at 10:28 +0100, [EMAIL PROTECTED] wrote: On Thu, 17 Apr 2008 20:57:21 -0700 (PDT) hdante [EMAIL PROTECTED] wrote: Don't use old 8-bit encodings. Use UTF-8. Yes, I'll try. But is a problem when I only want to read, not that I'm trying to write or create the content. To blame I suppose is Microsoft's commercial success. They won't adhere to standars if that doesn't make sense for their business. I'll change the approach trying to filter the contents with htmllib and mapping on my own those troubling characters. Anyway this has been a very instructive dive into unicode for me, I've got things cleared up now. Thanks to everyone for the great help. There are a number of code points (150 being one of them) that are used in cp1252, which are reserved for control characters in ISO-8859-1. Those characters will pretty much never be used in ISO-8859-1 documents. If you're expecting documents of both types coming in, test for the presence of those characters, and assume cp1252 for those documents. Something like: for c in control_chars: if c in encoded_text: unicode_text = encoded_text.decode('cp1252') break else: unicode_text = encoded_text.decode('latin-1') Note that the else matches the for, not the if. You can figure out the characters to match on by looking at the wikipedia pages for the encodings. Cheers, Cliff -- http://mail.python.org/mailman/listinfo/python-list
Re: Unicode chr(150) en dash
On Fri, 2008-04-18 at 07:27 -0400, J. Clifford Dyer wrote: On Fri, 2008-04-18 at 10:28 +0100, [EMAIL PROTECTED] wrote: On Thu, 17 Apr 2008 20:57:21 -0700 (PDT) hdante [EMAIL PROTECTED] wrote: Don't use old 8-bit encodings. Use UTF-8. Yes, I'll try. But is a problem when I only want to read, not that I'm trying to write or create the content. To blame I suppose is Microsoft's commercial success. They won't adhere to standars if that doesn't make sense for their business. I'll change the approach trying to filter the contents with htmllib and mapping on my own those troubling characters. Anyway this has been a very instructive dive into unicode for me, I've got things cleared up now. Thanks to everyone for the great help. There are a number of code points (150 being one of them) that are used in cp1252, which are reserved for control characters in ISO-8859-1. Those characters will pretty much never be used in ISO-8859-1 documents. If you're expecting documents of both types coming in, test for the presence of those characters, and assume cp1252 for those documents. Something like: for c in control_chars: if c in encoded_text: unicode_text = encoded_text.decode('cp1252') break else: unicode_text = encoded_text.decode('latin-1') Note that the else matches the for, not the if. You can figure out the characters to match on by looking at the wikipedia pages for the encodings. One warning: This works if you know all your documents are in one of those two encodings, but you could break other encodings, like UTF-8 this way. Fortunately UTF-8 is a pretty fragile encoding, so it's easy to break. You can usually test if a document is decent UTF-8 just by wrapping it in a try except block: try: unicode_text = encoded.text.decode('utf-8') except UnicodeEncodeError: # I think that's the proper exception # do the stuff above None of these are perfect methods, but then again, if text encoding detection were a perfect science, python could just handle it on its own. If in doubt, prompt the user for confirmation. Maybe others can share better best practices. Cheers, Cliff -- http://mail.python.org/mailman/listinfo/python-list
Ableton live 4.1.4 crack
Ableton live 4.1.4 crack -- http://mail.python.org/mailman/listinfo/python-list
Re: Unicode chr(150) en dash
hdante wrote: The character code in question (which is present in the page), 150, doesn't exist in ISO-8859-1. Are you sure? Consider (re-)reading all of the Wikipedia article. 150 aka \x96 doesn't exist in ISO 8859-1. ISO-8859-1 (two hyphens) is a superset of ISO 8859-1 (one hyphen) and adds the not-very-useful-AFAICT control codes \x80 to \x9F. See http://en.wikipedia.org/wiki/ISO/IEC_8859-1 (the entry for 150 is blank) You must have been looking at the table of the lite ISO 8859-1 (one hyphen). Reading further you will see \x96 described as SPA or Start of Guarded Area. Then there is the ISO-8859-1 (two hyphens) table, including \x96. HTH, John -- http://mail.python.org/mailman/listinfo/python-list
Re: index of list of lists
On Thu, 17 Apr 2008 12:25:51 +1000, Daniel Fetchinson [EMAIL PROTECTED] wrote: yes, there's a thread with the same title, but I believe mine is more appropriate title. so, as much as I search on the web, read manuals, tutorials, mail-lists (including this one) I cannot figure it out how to search a string in a list of lists. like this one: someList = [['somestring', 1, 2], ['oneother', 2, 4]] I want to search somestring in someList which is in practice a list of aprox. 200 lists. (hey, I'm a newbie python programmer, don't judge me). is the list.index the wrong approach? should I use numpy, numarray, something else? can anyone, be kind and help me with this? someList = [['somestring', 1, 2], ['oneother', 2, 4]] for alist in someList: if alist[0] == 'somestring': print Found it at index %d % someList.index( alist ) # if you know it will only occur once you might say: break HTH, Daniel See also Section 4.5. Filtering Lists. List comprehension: [x for x in someList if x[0] == 'somestring'] Use filter() function: filter(lambda x: x[0] == 'somestring', someList) -- Kam-Hung Soh a href=http://kamhungsoh.com/blog;Software Salariman/a -- http://mail.python.org/mailman/listinfo/python-list
Re: py3k s***s
Diez B. Roggisch wrote: . You know what I was just wondering about? All these C-written cross-platform libraries (which Python users benefit from, most probably including evven you) that run on different unixes windows, which are a much greater diversity to handle than the not-even-yet-settled differences between Py3K 2.x. How the heck do they do that? . I'm in the process of attempting a straightforward port of a relatively simple package which does most of its work by writing out files with a more or less complicated set of possible encodings. So far I have used all the 2to3 tools and a lot of effort, but still don't have a working version. This must be the worst way to convert people to unicode. When tcl went through this they chose the eminently sensible route of not choosing a separate unicode type (they used utf8 byte strings instead). Not only has python chosen to burden itself with two string types, but with 3 they've swapped roles. This is certainly the first time I've had to decide on an encoding before writing simple text to a file. Of course we may end up with a better language, but it will be a worse(more complex) tool for many simple tasks. Using a complex writing with many glyphs costs effort no matter how you do it, but I just use ascii :( and it's still an effort. I find the differences in C/OS less hard to understand than why I need bytes(x,'encoding') everywhere I just used to use str(x). -old fart-ly yrs- Robin Becker -- http://mail.python.org/mailman/listinfo/python-list
Re: py3k s***s
Robin Becker schrieb: I'm in the process of attempting a straightforward port of a relatively simple package which does most of its work by writing out files with a more or less complicated set of possible encodings. So far I have used all the 2to3 tools and a lot of effort, but still don't have a working version. This must be the worst way to convert people to unicode. When tcl went through this they chose the eminently sensible route of not choosing a separate unicode type (they used utf8 byte strings instead). Not only has python chosen to burden itself with two string types, but with 3 they've swapped roles. This is certainly the first time I've had to decide on an encoding before writing simple text to a file. Which is the EXACT RIGHT THING TO DO! see below. Of course we may end up with a better language, but it will be a worse(more complex) tool for many simple tasks. Using a complex writing with many glyphs costs effort no matter how you do it, but I just use ascii :( and it's still an effort. I find the differences in C/OS less hard to understand than why I need bytes(x,'encoding') everywhere I just used to use str(x). If you google my name + unicode, you see that I'm often answering questions regarding unicode. I wouldn't say I'm a recognized expert on the subject, but I certainly do know enough to deal with it whenever I encounter it. And from my experience with the problems in general, and specificly in python, as well as trying to help others I can say that: - 95% of the times, the problem is in front of the keyboard. - programmers stubbornly refuse to *learn* what unicode is, and what an encoding is, and what role utf-8 plays. Instead, the resort to a voodoo-approach of throwing in various encode/decode-calls + a good deal of cat's feces in hope of wriggling themselves out of the problem. - it is NOT sensible to use utf8 as unicode-type - that is as bad as it can get because you don't see the errors, but instead mangle your data and end up with a byte-string-mess. If that is your road to heaven, by all means chose it - and don't use unicode at all. and be prepared for damnation :) If your programs worked for now, but don't do anymore because of Py3K introducing mandatory unicode-objects for string-literals it pretty much follows that they *seem* to work, but very, very probably fail in the face of actual i18nized data. The *only* sensible thing to do is follow these simple rules - and these apply with python 2.x, and will be enforced by 3k which is a good thing IMHO: - when you read data from somewhere, make sure you know which encoding it has, and *immediatly* convert it to unicode - when you write data, make sure you know which encoding you want it to have (in doubt, chose utf-8 to prevent loss of data) and apply it. - XML-parsers take byte-strings spit out unicode. Period. I neither want to imply that you are an Idiot nor that unicode doesn't have it's complexities. And I'd love to say that Python wouldn't add to these by having two string-types. But the *real* problem is that it used to have only bytestrings, and finally Py3K will solve that issue. Diez -- http://mail.python.org/mailman/listinfo/python-list
SWIG (Python) - no constructor defined for concrete class
Yet another SWIG question (YASQ!). I'm having a problem with using an abstract base class. When generating the Python bindings, SWIG thinks that all the concrete classes that derive from this abstract class are abstract too and won't create the correct constructor. Abstract class: [source lang=cpp]class CORE_API Shape { public: virtual ~Shape() { nshapes--; }; double x, y; virtual void move(double dx, double dy); virtual double area(void) = 0; virtual double perimeter(void) = 0; static int nshapes; protected: Shape() { nshapes++; } }; [/source] Derived classes: [source lang=cpp]class CORE_API Circle : public Shape { private: double radius; public: Circle(double r): Shape(), radius(r) { }; virtual double area(void); virtual double perimeter(void); }; class CORE_API Square : public Shape { private: double width; public: Square(double r): Shape(), width(r) { }; virtual double area(void); virtual double perimeter(void); }; [/source] SWIG file: [source lang=cpp]class Shape { virtual void move(double dx, double dy); virtual double area(void) = 0; virtual double perimeter(void) = 0; }; class Circle: public Shape { Circle(double r); virtual double area(void); virtual double perimeter(void); }; class Square: public Shape { Square(double r); virtual double area(void); virtual double perimeter(void); }; [/source] C++ COde: [source lang=cpp] Circle c(1.02); std::cout (c++)\t\tCircle\t c.area() std::endl; Square s(9.20); std::cout (c++)\t\tSquare\t s.area() std::endl; [/source] For some reason SWIG thinks that Circle and Square are abstract. Any ideas why? I'm rather confused by this. Thanks as always -- http://mail.python.org/mailman/listinfo/python-list
Re: py3k s***s
On Apr 18, 1:39 am, Sverker Nilsson [EMAIL PROTECTED] wrote: Some whine. Some just don't care. Why not whine? Whining and ranting is actually good for the psyche. It is better to get it out of your system. As for your original post, no doubt there are substantial downsides to introducing Py3K, but as Guido put it every language must change or die. Of course we could end up with change and die as well. I for one am an optimist, I think there are several substantial improvements to the language that today may not be apparent for a casual observer, yet will allow it to evolve into an even more powerful and fun language i. -- http://mail.python.org/mailman/listinfo/python-list
Re: sampling without replacement
AlexyBut in Python it's very slow... I'm the first one to say that CPython is slow, but almost any language is slow if you use such wrong algorithms like you do. There are many ways to solve your problem efficiently, one of such ways, among the simpler ones is to to not modify the original list: from random import shuffle, seed items = list(abcdefghijklm) seed(10) shuffle(items) it_items = iter(items) it_items.next() 'i' it_items.next() 'd' it_items.next() 'l' it_items.next() 'b' it_items.next() 'j' it_items.next() 'a' it_items.next() 'e' If you don't want to extract the same element twice across different runs of the program, then you may create a class like this: from random import shuffle, seed class Sampler(object): def __init__(self, items, init_seed=1): self.items = list(items) self.last = len(self.items) - 1 self.init_seed = init_seed seed(init_seed) shuffle(self.items) def __repr__(self): return repr(self.items[:self.last+1]) def next(self): if self.last 0: raise StopIteration self.last -= 1 return self.items[self.last+1] def save(self, filename): pass # saves self.last and self.init_seed on disk samp = Sampler(abcdefghijklm) print samp print samp.next() print samp.next() print samp.next() That class code is raw, you may want to improve it in some ways. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: Data structure recommendation?
Jochen Schulz: Could you please send me an email with an existing From: address? I tried to reply to you but apparently your From: is forged. Sorry for the delay, I'll send you an email. In the meantime I have created a fast BK-tree implementation for Psyco, on my PC it's about 26+ times faster than mspace (that uses psyco still), but it's less complete. You can find it here: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/572156 (I have created a D version too, that's about 4.5 times faster than my Python version, so it's about 126 times faster than the mspace with Psyco). Enjoy, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: py3k s***s
On Apr 17, 12:27 pm, Michael Torrie [EMAIL PROTECTED] wrote: What's the big deal? The big deal is that I would love to see Django become the standard platform for web development, for example. That will be much less likely if 60% of the contributed tools for Django don't work for Python 3000 and 20% don't work for Python 2.6. Expecting volunteer contributors to support both is not realistic. It's hard enough to support one adequately. Even if you could hope to support both with the same code, just testing in both environments would be onerous. It would be another matter entirely if py3k offered major new functionality like full stackless microthreads but it doesn't (afaik -- correct me please). From my perspective it's just a pain in the @$$. By the way, full stackless microthreads don't seem to require breaking most (or any) existing code. I really like developing in Python -- but it's hard to keep doing it when the growth curve is so slow and a so many people have deep reservations about it, inspired in part, justifiably, by nonsense like this. In fact, I basically stopped. Then I came back. Now I'm wondering if it was such a good idea... -- Aaron Watters http://www.xfeedme.com/nucular/pydistro.py/go?FREETEXT=stupid+bug -- http://mail.python.org/mailman/listinfo/python-list
Re: Database vs Data Structure?
My very humble opinion - based on several years of working experience with both the Zodb and many RDBMS - is quite clear : use a RDBMS and use it properly. Yes, somewhere down the line you will want to get a report of all the customers in Ohio, ordered by county and zip code, who have a rabbit cage project -- and if you just pickle everything you will end up traversing the entire database, possibly multiple times to find it. A little old fashioned database design up front can save you a lot of pain. -- Aaron Watters === http://www.xfeedme.com/nucular/pydistro.py/go?FREETEXT=ouch -- http://mail.python.org/mailman/listinfo/python-list
Another MySQL Images Question
Hi; If I grab an image in the database thus: sql = select pic1 from products where id=' + str(id) + '; cursor.execute(sql) pic1 = cursor.fetchall()[0][0].tostring() # pic1 = cursor.fetchall()[0][0] // either this or the above line and try and re-insert it thus: cursor.execute('update products set pic1=%s where id=%s, ;', (pic1, id)) it tells me I have an error in my MySQL syntax. What is the error? TIA, Victor -- http://mail.python.org/mailman/listinfo/python-list
Making Windows Larger in Tkinter
Thanks to some help I received on list the other day, I now have a very nice windows-based application that implements multiple programs. This is a very powerful tool. Now I am working to make this window pretty. One problem I cannot find help on is how to make the windows a certain size. For example, I have added in a root.title() with a lot of text in the file example.py below. Is it possible to make the window box a specific size, or by default, always be large enough to show the entire text in root.title? example.py from Tkinter import * import tkMessageBox def callback(): print called the callback! def message(): if tkMessageBox.askokcancel(Quit, Do you really wish to quit?): root.destroy() def about(): tkMessageBox.showinfo(About, Foo?) root = Tk() root.title('Hello World: How Can we see the entire title?') # create a menu menu = Menu(root) root.config(menu=menu) filemenu = Menu(menu) menu.add_cascade(label=File, menu=filemenu) filemenu.add_command(label=New, command=message) filemenu.add_command(label=Open..., command=callback) filemenu.add_separator() filemenu.add_command(label=Exit, command=message) helpmenu = Menu(menu) menu.add_cascade(label=Help, menu=helpmenu) helpmenu.add_command(label=About..., command=about) mainloop() -- http://mail.python.org/mailman/listinfo/python-list
Checking for unique fields: performance.
I'm looping through a tab-delimited file to gather statistics on fill rates, lengths, and uniqueness. For the uniqueness, I made a dictionary with keys which correspond to the field names. The values were originally lists, where I would store values found in that field. Once I detected a duplicate, I deleted the entire element from the dictionary. Any which remained by the end are considered unique. Also, if the value was empty, the dictionary element was deleted and that field considered not unique. A friend of mine suggested changing that dictionary of lists into a dictionary of dictionaries, for performance reasons. As it turns out, the speed increase was ridiculous -- a file which took 42 minutes to run dropped down to six seconds. Here is the excerpt of the bit of code which checks for uniqueness. It's fully functional, so I'm just looking for any suggestions for improving it or any comments. Note that fieldNames is a list containing all column headers. #check for unique values #if we are still tracking that field (we haven't yet #found a duplicate value). if fieldUnique.has_key(fieldNames[index]): #if the current value is a duplicate if fieldUnique[fieldNames[index]].has_key(value): #sys.stderr.write(Field %s is not unique. Found a duplicate value after checking %d values.\n % (fieldNames[index], lineNum)) #drop the whole hash element fieldUnique.__delitem__(fieldNames[index]) else: #add the new value to the list fieldUnique[fieldNames[index]][value] = 1 -- http://mail.python.org/mailman/listinfo/python-list
Excel Manipulation using Python
I was trying to delete rows in an existing .xls file using python. How do I do that? I was using the following code, it seem to work if I type in python window, but if I save it in text editor and drage and drop the .py file, it doesnt work. What am I doing wrong here? Thanks for your help! import win32com.client from time import sleep excel = win32com.client.Dispatch(Excel.Application) def Extract(): excel.Visible = 0 workbook=excel.Workbooks.Open('C:\Trial.xls') i=1 for n in range(1,10): excel.Rows(i).Select excel.Selection.Delete excel.Selection.Delete i=i+2 workbook.Save() print saved excel.Quit() -- http://mail.python.org/mailman/listinfo/python-list
Re: python persistence
On Apr 1, 3:21 pm, [EMAIL PROTECTED] wrote: On Apr 1, 11:34 am, Gabriel Genellina [EMAIL PROTECTED] En Tue, 01 Apr 2008 08:47:33 -0300, [EMAIL PROTECTED] escribió: c['0']= type('None',(),{}) Traceback (most recent call last): pickle.PicklingError: Can't pickle class '__main__.None': it's not found as __main__.None Don't do that then. Or use the available pickle hooks to customize how such classes may be pickled. All persistence mechanisms have limitations. I don't see a problem with that; except that binaries come from disks. You could have a Python session that runs entirely on disks + the ALU. (ALU? Do you mean CPU?) I don't understand this. Most programs are read from disk. Most data is read from disk. I want to know if any, and correct me here, simple modification can store live objects. I call a.append(it) and the memory update takes place on disk instead. Using ZODB, a.append(it) would mark `a` as dirty. When you latter commit the transaction, it is stored back on disk. If you require that all objects referenced by on-disk objects be on- disk, that's an easy workaround. ZODB already does that. It's pretty close, but the database connection can get bulky. If you had: ___ | __ |File | PyOb1 | PyOb2 | .. | | |___|___|__| |___ on disk, updating the reference counts and attributes would take a long time, but it's just right for some core applications. Strictly, I'm not in the real programming world [snip]. My intentions may be pedagogical but I can guarantee good. I am following the cases where databases are way-out-of-proportion techniques, and you only need small numbers persistent. I am looking for a step-by-step of everything that happens in line one of the following program: #!/windows a= [ ] What c-l-py says is that the compilation flags vary widely enough to make my destination worthless. Accepting concern, please only reply in readers' free time. I expect I wish to override routines and macros which are buried pretty deep and used pretty pervasively throughout Python and inner user extension modules, so I'll reemphasize that I'm only interested in pass-time hobbyage. Consultants need not reply (but of course may). I foresee that writing my own disk-based-heap may be in order, which would be why Bruno keeps directing us to relationals. I would want an arena file/pool file. Zoom out to the big picture: Session 1: managingfolder= '/live/Python/' manager['a']= [ 0 ] Session 2: managingfolder= '/live/Python/' manager['a'] [ 0 ] manager['a'].append( 0 ) Session 3: managingfolder= '/live/Python/' manager['a'] [ 0, 0 ] I would kind of expect a file per the diagram in obmalloc.c, and I expect to specialize in CPython. Object-specific allocators _ __ __ [ int ] [ dict ] [ list ] ... [ string ] Python core | +3 | - Object-specific memory - | -- Non-object memory -- | struct pool_header and struct arena_object would probably appear, and to explify priorities, performance would be a low priority, and it's a high priority to stay all in Python. (Aside, I certainly would maintain Python is yes, still Python.) -- http://mail.python.org/mailman/listinfo/python-list
Which event to use for out of focus window?
I think I've found a bug in the wx Library. I've created an event : EVT_IDLE that does something when the event is triggered, however, if your mouse pointer is out-of-focus on the window, the EVT_IDLE doesn't get called. It's only when the window is put into focus that the IDLE event is called. I basically want the IDLE function to be called whether the window is in focus or not. Is there a way to do this? Thanks, -M _ Get in touch in an instant. Get Windows Live Messenger now. http://www.windowslive.com/messenger/overview.html?ocid=TXT_TAGLM_WL_Refresh_getintouch_042008-- http://mail.python.org/mailman/listinfo/python-list
Re: Excel Manipulation using Python
Krishna wrote: I was trying to delete rows in an existing .xls file using python. How do I do that? I was using the following code, it seem to work if I type in python window, but if I save it in text editor and drage and drop the .py file, it doesnt work. What am I doing wrong here? Thanks for your help! import win32com.client from time import sleep excel = win32com.client.Dispatch(Excel.Application) def Extract(): excel.Visible = 0 workbook=excel.Workbooks.Open('C:\Trial.xls') i=1 for n in range(1,10): excel.Rows(i).Select excel.Selection.Delete excel.Selection.Delete i=i+2 workbook.Save() print saved excel.Quit() Several points worthy of note: 1) When you're dealing with Windows filenames, either make the strings raw -- Open (rc:\trial.txt) -- or use the other slashes =-- Open (c:/trial.xls). 2) You're not actually calling the Select and Delete methods, merely referencing them. Try .Delete () etc. 3) You're saving the workbook every time round the loop, but perhaps you knew that. Might prompt you everytime as you're overwriting, but again, maybe you knew... TJG -- http://mail.python.org/mailman/listinfo/python-list
installing MySQLdb module
I've installed the developer tools package, but when running python setup.py build I get the following error: python setup.py build running build running build_py copying MySQLdb/release.py - build/lib.macosx-10.3-fat-2.5/MySQLdb running build_ext building '_mysql' extension gcc -isysroot /Developer/SDKs/MacOSX10.4u.sdk -fno-strict-aliasing - Wno-long-double -no-cpp-precomp -mno-fused-madd -fno-common -dynamic - DNDEBUG -g -O3 -Dversion_info=(1,2,2,'final',0) -D__version__=1.2.2 -I/ Applications/xampp/xamppfiles/include/mysql -I/Library/Frameworks/ Python.framework/Versions/2.5/include/python2.5 -c _mysql.c -o build/ temp.macosx-10.3-fat-2.5/_mysql.o -arch i386 -arch ppc _mysql.c:35:23:_mysql.c:35:23: error: my_config.h: No such file or directoryerror: my_config.h: No such file or directory ... I googled around and people say you need the -dev package of mysql in order to have the C headers...where can you download this for mac os? Thanks, Rafael PS I am running XAMPP (http://www.keitr.com/tutorials/xampp) if that changes anything -- http://mail.python.org/mailman/listinfo/python-list
Re: str class inheritance prob?
[EMAIL PROTECTED] a écrit : so I’m trying to create a class that inherits from str, but I want to run some code on the value on object init. this is what I have: Others already gave you the technical solution (use __new__, not __init__). A couple remarks still: 1/ class Path(str): def __init__( self, path ): clean = str(path).replace('\\','/') while clean.find('//') != -1: clean = clean.replace('//','/') print 'cleaned on init:\t',clean self = clean Assigning to self - or to any other local name - only impact the local namespace, it won't affect the object previously bound to that name. 2/ you may be interested in the existing path module: http://www.jorendorff.com/articles/python/path/ HTH -- http://mail.python.org/mailman/listinfo/python-list
Re: Python-list Digest, Vol 55, Issue 296
On Fri, 2008-04-18 at 17:25 +0200, [EMAIL PROTECTED] wrote: I really like developing in Python -- but it's hard to keep doing it when the growth curve is so slow and a so many people have deep reservations about it, inspired in part, justifiably, by nonsense like this. In fact, I basically stopped. Then I came back. Now I'm wondering if it was such a good idea... -- Aaron Watters From what I've read, the slowness of the growth curve was actually one of the major issues that prompted the Py3K push in the first place. The accumulated cruft had gotten heavy, and was slowing python down. Py3K is deliberately conservative, so that the transition will be as painless as possible, but strips away the warts that were slowing things down. Having print as a statement meant it was difficult to add functionality there. Supporting both new and old style classes meant that you couldn't count on expected functionality in external libraries. The string/unicode dichotomy caused innumerable headaches for everybody. The big changes you are hoping for to justify py3k won't come in python 3.0. They'll come in python 3.2 and python 3.3. Of course, I'm well aware that I'm talking about vaporware, but making the architectural changes now to make that advancement possible in the future is the point of python 3.0. In the meantime, your code will always work on Python 2.5. If you're worried about wild code, bundle it with its own interpreter when you distribute it. It'll survive. Cheers, Cliff -- http://mail.python.org/mailman/listinfo/python-list
Re: Another MySQL Images Question
There are several problems with your SQL, but not all of them would be caught by the computer. Your SELECT statement is not parameterized. This is a security problem. *Always* parameterize your variables. Your UPDATE statement has an extraneous comma at the end, and it also has quotes around the %ses that you don't need, because you already parameterized that query. Your dbapi interface will provide appropriate quoting for whatever type of data you pass it. Cheers, Cliff On Fri, 2008-04-18 at 10:13 -0500, Victor Subervi wrote: Hi; If I grab an image in the database thus: sql = select pic1 from products where id=' + str(id) + '; cursor.execute(sql) pic1 = cursor.fetchall()[0][0].tostring() # pic1 = cursor.fetchall()[0][0] // either this or the above line and try and re-insert it thus: cursor.execute('update products set pic1=%s where id=%s, ;', (pic1, id)) it tells me I have an error in my MySQL syntax. What is the error? TIA, Victor -- Oook, J. Cliff Dyer Carolina Digital Library and Archives UNC Chapel Hill -- http://mail.python.org/mailman/listinfo/python-list
Installing BeautifulSoup with easy_install (broken?)
Info: Python version: ActivePython 2.5.1.1 Platform: Windows I wanted to install BeautifulSoup today for a small project and decided to use easy_install. I can install other packages just fine. Unfortunately I get the following error from BeautifulSoup installation attempt: C:\Python25\Lib\SITE-P~1easy_install BeautifulSoup Searching for BeautifulSoup Reading http://pypi.python.org/simple/BeautifulSoup/ Reading http://www.crummy.com/software/BeautifulSoup/ Reading http://www.crummy.com/software/BeautifulSoup/download/ Best match: BeautifulSoup 3.0.5 Downloading http://www.crummy.com/software/BeautifulSoup/download/BeautifulSoup- 3.0.5.tar.gz Processing BeautifulSoup-3.0.5.tar.gz Running BeautifulSoup-3.0.5\setup.py -q bdist_egg --dist-dir c:\docume~1\larry\l ocals~1\temp\easy_install-cfdxna\BeautifulSoup-3.0.5\egg-dist-tmp-gbrpp5 Traceback (most recent call last): File C:\Python25\Scripts\easy_install-script.py, line 8, in module load_entry_point('setuptools==0.6c8', 'console_scripts', 'easy_install')() File C:\Python25\lib\site-packages\setuptools-0.6c8-py2.5.egg\setuptools\comm and\easy_install.py, line 1671, in main File C:\Python25\lib\site-packages\setuptools-0.6c8-py2.5.egg\setuptools\comm and\easy_install.py, line 1659, in with_ei_usage File C:\Python25\lib\site-packages\setuptools-0.6c8-py2.5.egg\setuptools\comm and\easy_install.py, line 1675, in lambda File C:\Python25\lib\distutils\core.py, line 151, in setup dist.run_commands() File C:\Python25\lib\distutils\dist.py, line 974, in run_commands self.run_command(cmd) File C:\Python25\lib\distutils\dist.py, line 994, in run_command cmd_obj.run() File C:\Python25\lib\site-packages\setuptools-0.6c8-py2.5.egg\setuptools\comm and\easy_install.py, line 211, in run File C:\Python25\lib\site-packages\setuptools-0.6c8-py2.5.egg\setuptools\comm and\easy_install.py, line 446, in easy_install File C:\Python25\lib\site-packages\setuptools-0.6c8-py2.5.egg\setuptools\comm and\easy_install.py, line 476, in install_item File C:\Python25\lib\site-packages\setuptools-0.6c8-py2.5.egg\setuptools\comm and\easy_install.py, line 655, in install_eggs File C:\Python25\lib\site-packages\setuptools-0.6c8-py2.5.egg\setuptools\comm and\easy_install.py, line 930, in build_and_install File C:\Python25\lib\site-packages\setuptools-0.6c8-py2.5.egg\setuptools\comm and\easy_install.py, line 919, in run_setup File C:\Python25\lib\site-packages\setuptools-0.6c8-py2.5.egg\setuptools\sand box.py, line 27, in run_setup File C:\Python25\lib\site-packages\setuptools-0.6c8-py2.5.egg\setuptools\sand box.py, line 63, in run File C:\Python25\lib\site-packages\setuptools-0.6c8-py2.5.egg\setuptools\sand box.py, line 29, in lambda File C:\VOL1\Larry\Websafe\Python\wstools\setup.py, line 2, in module import py2exe File C:\VOL1\Larry\Websafe\Python\wstools\unittest.py, line 3, in module class TextCtrlTest(unittest.TestCase): AttributeError: 'module' object has no attribute 'TestCase' Thanks in advance for any clues. -Larry -- http://mail.python.org/mailman/listinfo/python-list
Delete rows using xlrd?
I want to delete some rows (by creating a loop may be) using xlrd. Is this possible, if not how do I do that with python? Please help Thanks Krishna -- http://mail.python.org/mailman/listinfo/python-list
Re: What can we do about all the spam that the list is getting?
On 16 abr, 14:01, [EMAIL PROTECTED] wrote: What can we do about all the spam that comp.lang.python is getting? Things are getting pretty bad. I'm reporting most spam, but I don't have high hopes Google cares. We could start a new group (non-usenet Google Groups allow message removal), but I guess most people would rather simply plonk GG posts. Perhaps we could find a way to tag spam threads that would auto-plonk those threads in our preferred reader (email, newsreader and Greasemonkey killfile)? This has the drawback that spam posted to ham threads would be hard to block... Regards, Daniel P.S.: I prefer posting from Google Groups, I'd rather avoid posting at all than having to use a different client... -- http://mail.python.org/mailman/listinfo/python-list
Pickle problem
Hello everybody: I'd like to use the pickle module to save the state of an object so to be able to restore it later. The problem is that it holds a list of other objects, say numbers, and if I modify the list and restore the object, the list itself is not reverted to the saved one, but stays with one element deleted. An example session is the following: Data is A [1, 2, 3, 4] saving a with pickle Deleting an object: del a[3] Now data is A [1, 2, 3] Oops! That was an error: can you please recover to the last saved data? A [1, 2, 3] I'd like to have here A[1,2,3,4]!! Is it the intended behavior for pickle? if so, are there any way to save the state of my object? Code follows --- class A(object): objects = [] --- then I run the code: --- import pickle from core import A a = A() for i in [1,2,3,4]: a.objects.append(i) savedData = pickle.dumps(a) print Saved data is ,a print Deleting an object del a.objects[3] print a print Oops! This was an error: can you please recover the last saved data? print pickle.loads(savedData) Thank you for any help! Mario -- http://mail.python.org/mailman/listinfo/python-list
py3k concerns. An example
Why is the migration to py3k a concern? For example I have libraries which use string%dictionary substitution where the dictionary is actually an object which emulates a dictionary. The __getitem__ for the object can be very expensive and is only called when needed by the string substitution. In py3k string%dictionary is going away. Why? I have no idea. The replacement is a string.format(...) method which supports dictionary calling. string.format(**dictionary) But dictionary calling doesn't support dictionary emulation. So in the example below the substitution works but the call fails. === code class fdict(dict): def __getitem__(self, item): return got(+item+) def fn(**d): print d[boogie] if __name__==__main__: fd = fdict() print attempting string substitution with fake dictionary print print hello there %(boogie)s % fd # -- works print print now attempting function call with fake dictionary print fn(**fd) # -- fails === output % python2.6 dtest.py attempting string substitution with fake dictionary hello there got(boogie) now attempting function call with fake dictionary Traceback (most recent call last): File dtest.py, line 17, in module fn(**fd) File dtest.py, line 7, in fn print d[boogie] KeyError: 'boogie' end of output Consequently there is no simple way to translate my code, I think. I suspect you will find this kind of subtle issue in many places. Or worse, you won't find it until after your program has been installed in production. It's a damn shame because if string%dict was just left in it wouldn't be an issue. Also, if making f(**d) support dict emulation has any negative performance implications then I don't want it please. sigh. -- Aaron Watters === http://www.xfeedme.com/nucular/pydistro.py/go?FREETEXT=crack+open -- http://mail.python.org/mailman/listinfo/python-list
Re: tkinter, canvas, get color of image?
On 16 Apr, 00:46, Bryan Oakley [EMAIL PROTECTED] wrote: [EMAIL PROTECTED] wrote: On 13 Apr, 19:19, Bryan Oakley [EMAIL PROTECTED] wrote: [EMAIL PROTECTED] wrote: mapq = PhotoImage(file = 'C:\Users\saftarn\Desktop\elmapovic.gif') w.create_image(10, 10, image = mapq, anchor = NW) after doing this is there any possibility of getting the characteristics of the GIF-picture(or bitmap if i use that)? it would be very helpfull if i for example could do something like canvas.getcolor(image, mouseclick.x,mouseclick.y) if u get the point. get the color of the image where i clicked. The image isn't painted on the canvas, so to answer your specific question, no, you can't get the color of a pixel on the canvas in the way that you ask. However, when you click on the canvas you can get the item that was clicked on and the x/y of the click. From that you can figure out which pixel of the image is under the cursor. And from that you can query the image for the color of a specific pixel. how do i get the item? http://effbot.org/tkinterbook/canvas.htm#Tkinter.Canvas.create_image-... with any of those methods? when i click the mouse i can get event.object u mean? You can use find_closest to find the object closest to the x,y of the event. You can also do find_withtag(tk.CURRENT) which returns the item under the mouse pointer. Exception in Tkinter callback Traceback (most recent call last): File C:\Python25\lib\lib-tk\Tkinter.py, line 1403, in __call__ return self.func(*args) File C:\Users\saftarn\Desktop\pythonkod\mapexperiments \mapgetobject.py, line 17, in callback undermouse=find_closest(master.CURRENT) NameError: global name 'find_closest' is not defined from Tkinter import * master = Tk() w = Canvas(master, width=400, height=625) w.pack(expand = YES, fill = BOTH) mapq = PhotoImage(file = 'C:\Users\saftarn\Desktop\images \something.gif') w.create_image(30, 30, image = mapq, anchor = NW) def key(event): print pressed, repr(event.char) def callback(event): clobj=event.widget ##undermouse=find_withtag(master.CURRENT) undermouse=find_closest(master.CURRENT) print repr(undermouse) w.bind(Key, key) w.bind(Button-1, callback) w.pack() mainloop() -- http://mail.python.org/mailman/listinfo/python-list
Re: Installing BeautifulSoup with easy_install (broken?)
Larry Bates schrieb: Info: Python version: ActivePython 2.5.1.1 Platform: Windows I wanted to install BeautifulSoup today for a small project and decided to use easy_install. I can install other packages just fine. Unfortunately I get the following error from BeautifulSoup installation attempt: C:\Python25\Lib\SITE-P~1easy_install BeautifulSoup Searching for BeautifulSoup Reading http://pypi.python.org/simple/BeautifulSoup/ Reading http://www.crummy.com/software/BeautifulSoup/ Reading http://www.crummy.com/software/BeautifulSoup/download/ Best match: BeautifulSoup 3.0.5 Downloading http://www.crummy.com/software/BeautifulSoup/download/BeautifulSoup- 3.0.5.tar.gz Processing BeautifulSoup-3.0.5.tar.gz Running BeautifulSoup-3.0.5\setup.py -q bdist_egg --dist-dir c:\docume~1\larry\l ocals~1\temp\easy_install-cfdxna\BeautifulSoup-3.0.5\egg-dist-tmp-gbrpp5 Traceback (most recent call last): File C:\Python25\Scripts\easy_install-script.py, line 8, in module load_entry_point('setuptools==0.6c8', 'console_scripts', 'easy_install')() File C:\Python25\lib\site-packages\setuptools-0.6c8-py2.5.egg\setuptools\comm and\easy_install.py, line 1671, in main File C:\Python25\lib\site-packages\setuptools-0.6c8-py2.5.egg\setuptools\comm and\easy_install.py, line 1659, in with_ei_usage File C:\Python25\lib\site-packages\setuptools-0.6c8-py2.5.egg\setuptools\comm and\easy_install.py, line 1675, in lambda File C:\Python25\lib\distutils\core.py, line 151, in setup dist.run_commands() File C:\Python25\lib\distutils\dist.py, line 974, in run_commands self.run_command(cmd) File C:\Python25\lib\distutils\dist.py, line 994, in run_command cmd_obj.run() File C:\Python25\lib\site-packages\setuptools-0.6c8-py2.5.egg\setuptools\comm and\easy_install.py, line 211, in run File C:\Python25\lib\site-packages\setuptools-0.6c8-py2.5.egg\setuptools\comm and\easy_install.py, line 446, in easy_install File C:\Python25\lib\site-packages\setuptools-0.6c8-py2.5.egg\setuptools\comm and\easy_install.py, line 476, in install_item File C:\Python25\lib\site-packages\setuptools-0.6c8-py2.5.egg\setuptools\comm and\easy_install.py, line 655, in install_eggs File C:\Python25\lib\site-packages\setuptools-0.6c8-py2.5.egg\setuptools\comm and\easy_install.py, line 930, in build_and_install File C:\Python25\lib\site-packages\setuptools-0.6c8-py2.5.egg\setuptools\comm and\easy_install.py, line 919, in run_setup File C:\Python25\lib\site-packages\setuptools-0.6c8-py2.5.egg\setuptools\sand box.py, line 27, in run_setup File C:\Python25\lib\site-packages\setuptools-0.6c8-py2.5.egg\setuptools\sand box.py, line 63, in run File C:\Python25\lib\site-packages\setuptools-0.6c8-py2.5.egg\setuptools\sand box.py, line 29, in lambda File C:\VOL1\Larry\Websafe\Python\wstools\setup.py, line 2, in module import py2exe File C:\VOL1\Larry\Websafe\Python\wstools\unittest.py, line 3, in module class TextCtrlTest(unittest.TestCase): AttributeError: 'module' object has no attribute 'TestCase' Thanks in advance for any clues. I'm not sure what happens - but I think it is suspicious that these wstools get into the way. And it looks as if wstools.unittest imports itself, instead of the python-unittest - which must be solved with getting the sys.path fixed. Diez -- http://mail.python.org/mailman/listinfo/python-list
Tkinter, getting canvas-object, how?
so i load a gif onto a canvas and when i click the canvs i want to get the color of the pixel that is clicked. so i need to ge the object im clicking. i was told in another thread to use find_withtag or find_closest but it is not working, maybe im using the method on the wrong object. how do i do this? and how do i then get specifics about that object, ie the pixel-color? Exception in Tkinter callback Traceback (most recent call last): File C:\Python25\lib\lib-tk\Tkinter.py, line 1403, in __call__ return self.func(*args) File C:\Users\saftarn\Desktop\pythonkod\mapexperiments \mapgetobject.py, line 17, in callback undermouse=find_closest(master.CURRENT) NameError: global name 'find_closest' is not defined from Tkinter import * master = Tk() w = Canvas(master, width=400, height=625) w.pack(expand = YES, fill = BOTH) mapq = PhotoImage(file = 'C:\Users\saftarn\Desktop\Maps\provinces-of- sweden.gif') w.create_image(30, 30, image = mapq, anchor = NW) def key(event): print pressed, repr(event.char) def callback(event): clobj=event.widget ##undermouse=find_withtag(master.CURRENT) undermouse=find_closest(master.CURRENT) print repr(undermouse) w.bind(Key, key) w.bind(Button-1, callback) w.pack() mainloop() -- http://mail.python.org/mailman/listinfo/python-list
Re: How to set proxy for a python script to run
On Apr 18, 12:31 pm, Adam [EMAIL PROTECTED] wrote: Hi, everyone, I am using /usr/share/system-config-language/ language_gui.py in Python. For some reason I have to bypass the firewall using a proxy. I read the urllib reference and set http_proxy=my proxy. But it didn't work. Is there anyway that we can set the proxy? Check the link: http://love-python.blogspot.com/2008/03/use-proxy-in-your-spider.html -- http://mail.python.org/mailman/listinfo/python-list
Re: Installing BeautifulSoup with easy_install (broken?)
Diez B. Roggisch wrote: Larry Bates schrieb: Info: Python version: ActivePython 2.5.1.1 Platform: Windows I wanted to install BeautifulSoup today for a small project and decided to use easy_install. I can install other packages just fine. Unfortunately I get the following error from BeautifulSoup installation attempt: C:\Python25\Lib\SITE-P~1easy_install BeautifulSoup Searching for BeautifulSoup Reading http://pypi.python.org/simple/BeautifulSoup/ Reading http://www.crummy.com/software/BeautifulSoup/ Reading http://www.crummy.com/software/BeautifulSoup/download/ Best match: BeautifulSoup 3.0.5 Downloading http://www.crummy.com/software/BeautifulSoup/download/BeautifulSoup- 3.0.5.tar.gz Processing BeautifulSoup-3.0.5.tar.gz Running BeautifulSoup-3.0.5\setup.py -q bdist_egg --dist-dir c:\docume~1\larry\l ocals~1\temp\easy_install-cfdxna\BeautifulSoup-3.0.5\egg-dist-tmp-gbrpp5 Traceback (most recent call last): File C:\Python25\Scripts\easy_install-script.py, line 8, in module load_entry_point('setuptools==0.6c8', 'console_scripts', 'easy_install')() File C:\Python25\lib\site-packages\setuptools-0.6c8-py2.5.egg\setuptools\comm and\easy_install.py, line 1671, in main File C:\Python25\lib\site-packages\setuptools-0.6c8-py2.5.egg\setuptools\comm and\easy_install.py, line 1659, in with_ei_usage File C:\Python25\lib\site-packages\setuptools-0.6c8-py2.5.egg\setuptools\comm and\easy_install.py, line 1675, in lambda File C:\Python25\lib\distutils\core.py, line 151, in setup dist.run_commands() File C:\Python25\lib\distutils\dist.py, line 974, in run_commands self.run_command(cmd) File C:\Python25\lib\distutils\dist.py, line 994, in run_command cmd_obj.run() File C:\Python25\lib\site-packages\setuptools-0.6c8-py2.5.egg\setuptools\comm and\easy_install.py, line 211, in run File C:\Python25\lib\site-packages\setuptools-0.6c8-py2.5.egg\setuptools\comm and\easy_install.py, line 446, in easy_install File C:\Python25\lib\site-packages\setuptools-0.6c8-py2.5.egg\setuptools\comm and\easy_install.py, line 476, in install_item File C:\Python25\lib\site-packages\setuptools-0.6c8-py2.5.egg\setuptools\comm and\easy_install.py, line 655, in install_eggs File C:\Python25\lib\site-packages\setuptools-0.6c8-py2.5.egg\setuptools\comm and\easy_install.py, line 930, in build_and_install File C:\Python25\lib\site-packages\setuptools-0.6c8-py2.5.egg\setuptools\comm and\easy_install.py, line 919, in run_setup File C:\Python25\lib\site-packages\setuptools-0.6c8-py2.5.egg\setuptools\sand box.py, line 27, in run_setup File C:\Python25\lib\site-packages\setuptools-0.6c8-py2.5.egg\setuptools\sand box.py, line 63, in run File C:\Python25\lib\site-packages\setuptools-0.6c8-py2.5.egg\setuptools\sand box.py, line 29, in lambda File C:\VOL1\Larry\Websafe\Python\wstools\setup.py, line 2, in module import py2exe File C:\VOL1\Larry\Websafe\Python\wstools\unittest.py, line 3, in module class TextCtrlTest(unittest.TestCase): AttributeError: 'module' object has no attribute 'TestCase' Thanks in advance for any clues. I'm not sure what happens - but I think it is suspicious that these wstools get into the way. And it looks as if wstools.unittest imports itself, instead of the python-unittest - which must be solved with getting the sys.path fixed. Diez Sharp eyes Diez, I overlooked that. This is a path that I search for some tools I've written. It is set in PYTHONPATH environment variable. I cleared PYTHONPATH and easy_install BeautifulSoup worked. Still not quite clear why. Thanks loads. -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: Installing BeautifulSoup with easy_install (broken?)
Larry Bates schrieb: Diez B. Roggisch wrote: Larry Bates schrieb: Info: Python version: ActivePython 2.5.1.1 Platform: Windows I wanted to install BeautifulSoup today for a small project and decided to use easy_install. I can install other packages just fine. Unfortunately I get the following error from BeautifulSoup installation attempt: C:\Python25\Lib\SITE-P~1easy_install BeautifulSoup Searching for BeautifulSoup Reading http://pypi.python.org/simple/BeautifulSoup/ Reading http://www.crummy.com/software/BeautifulSoup/ Reading http://www.crummy.com/software/BeautifulSoup/download/ Best match: BeautifulSoup 3.0.5 Downloading http://www.crummy.com/software/BeautifulSoup/download/BeautifulSoup- 3.0.5.tar.gz Processing BeautifulSoup-3.0.5.tar.gz Running BeautifulSoup-3.0.5\setup.py -q bdist_egg --dist-dir c:\docume~1\larry\l ocals~1\temp\easy_install-cfdxna\BeautifulSoup-3.0.5\egg-dist-tmp-gbrpp5 Traceback (most recent call last): File C:\Python25\Scripts\easy_install-script.py, line 8, in module load_entry_point('setuptools==0.6c8', 'console_scripts', 'easy_install')() File C:\Python25\lib\site-packages\setuptools-0.6c8-py2.5.egg\setuptools\comm and\easy_install.py, line 1671, in main File C:\Python25\lib\site-packages\setuptools-0.6c8-py2.5.egg\setuptools\comm and\easy_install.py, line 1659, in with_ei_usage File C:\Python25\lib\site-packages\setuptools-0.6c8-py2.5.egg\setuptools\comm and\easy_install.py, line 1675, in lambda File C:\Python25\lib\distutils\core.py, line 151, in setup dist.run_commands() File C:\Python25\lib\distutils\dist.py, line 974, in run_commands self.run_command(cmd) File C:\Python25\lib\distutils\dist.py, line 994, in run_command cmd_obj.run() File C:\Python25\lib\site-packages\setuptools-0.6c8-py2.5.egg\setuptools\comm and\easy_install.py, line 211, in run File C:\Python25\lib\site-packages\setuptools-0.6c8-py2.5.egg\setuptools\comm and\easy_install.py, line 446, in easy_install File C:\Python25\lib\site-packages\setuptools-0.6c8-py2.5.egg\setuptools\comm and\easy_install.py, line 476, in install_item File C:\Python25\lib\site-packages\setuptools-0.6c8-py2.5.egg\setuptools\comm and\easy_install.py, line 655, in install_eggs File C:\Python25\lib\site-packages\setuptools-0.6c8-py2.5.egg\setuptools\comm and\easy_install.py, line 930, in build_and_install File C:\Python25\lib\site-packages\setuptools-0.6c8-py2.5.egg\setuptools\comm and\easy_install.py, line 919, in run_setup File C:\Python25\lib\site-packages\setuptools-0.6c8-py2.5.egg\setuptools\sand box.py, line 27, in run_setup File C:\Python25\lib\site-packages\setuptools-0.6c8-py2.5.egg\setuptools\sand box.py, line 63, in run File C:\Python25\lib\site-packages\setuptools-0.6c8-py2.5.egg\setuptools\sand box.py, line 29, in lambda File C:\VOL1\Larry\Websafe\Python\wstools\setup.py, line 2, in module import py2exe File C:\VOL1\Larry\Websafe\Python\wstools\unittest.py, line 3, in module class TextCtrlTest(unittest.TestCase): AttributeError: 'module' object has no attribute 'TestCase' Thanks in advance for any clues. I'm not sure what happens - but I think it is suspicious that these wstools get into the way. And it looks as if wstools.unittest imports itself, instead of the python-unittest - which must be solved with getting the sys.path fixed. Diez Sharp eyes Diez, I overlooked that. This is a path that I search for some tools I've written. It is set in PYTHONPATH environment variable. I cleared PYTHONPATH and easy_install BeautifulSoup worked. Still not quite clear why. Mayb setuptools imports setup.py - but because of you having another one on the PYTHONPATH, it gets that instead of the one actually needed by setuptools? Only thing that helps is looking at sandbox.py, line 29. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Installing BeautifulSoup with easy_install (broken?)
Larry Bates wrote: Info: Python version: ActivePython 2.5.1.1 Platform: Windows I wanted to install BeautifulSoup today for a small project and decided to use easy_install. I can install other packages just fine. Unfortunately I get the following error from BeautifulSoup installation attempt: easy_install usually seems to make things harder. BeautifulSoup is one single .py file. That's all you need. Everything else is excess baggage. John Nagle SiteTruth -- http://mail.python.org/mailman/listinfo/python-list
Re: I just killed GIL!!!
On Apr 18, 4:30 am, Nick Craig-Wood [EMAIL PROTECTED] wrote: Rhamphoryncus [EMAIL PROTECTED] wrote: On Apr 17, 7:40 am, Steve Holden [EMAIL PROTECTED] wrote: I'd love to be wrong about that, but the GIL *has* been the subject of extensive efforts to kill it over the last five years, and it has survived despite the best efforts of the developers. Yo. http://code.google.com/p/python-safethread/ Sounds very interesting. I particularly liked this bit from the web page - an excellent solution to fine grained locking. Sending only immutable objects between threads is very like the functional approach used by Erlang which is extremely good at concurrency. Although superficially similar, the details of Erlang are actually pretty different. It copies all objects passed between threads - it was originally designed for fault tolerance (entire nodes going down), not concurrency. If you want a shared mutable object you need to use a process as one, treating it as an actor. Hopefully you can do most of it in a one-way, message driven style, as otherwise you're going to be transforming your synchronous calls into a series of callbacks. If you have a node farm, you want to upgrade it incrementally, and you want it to be fault tolerant (nodes go down at random without kill the whole thing), Erlang is much better than safethread. That's at a significant cost though, as it's only good at the one style. Safethread is much better at a style useful on a single desktop. -- http://mail.python.org/mailman/listinfo/python-list
Re: py3k s***s
On Fri, 18 Apr 2008 07:16:35 -0700, Aaron Watters wrote: The big deal is that I would love to see Django become the standard platform for web development, for example. That will be much less likely if 60% of the contributed tools for Django don't work for Python 3000 and 20% don't work for Python 2.6. Expecting volunteer contributors to support both is not realistic. It's hard enough to support one adequately. Even if you could hope to support both with the same code, just testing in both environments would be onerous. You shouldn't worry about Django. Python 3000 port has already started [1]. And the assumption that to support both is not realistic may be wrong [2] in this case. [1] http://wiki.python.org/moin/PortingDjangoTo3k [2] http://groups.google.com/group/django-developers/msg/91f399820ee07ce5 -- Ivan -- http://mail.python.org/mailman/listinfo/python-list
Re: Another MySQL Images Question
Thank you. That worked. Victor On Fri, Apr 18, 2008 at 10:48 AM, J. Cliff Dyer [EMAIL PROTECTED] wrote: There are several problems with your SQL, but not all of them would be caught by the computer. Your SELECT statement is not parameterized. This is a security problem. *Always* parameterize your variables. Your UPDATE statement has an extraneous comma at the end, and it also has quotes around the %ses that you don't need, because you already parameterized that query. Your dbapi interface will provide appropriate quoting for whatever type of data you pass it. Cheers, Cliff On Fri, 2008-04-18 at 10:13 -0500, Victor Subervi wrote: Hi; If I grab an image in the database thus: sql = select pic1 from products where id=' + str(id) + '; cursor.execute(sql) pic1 = cursor.fetchall()[0][0].tostring() # pic1 = cursor.fetchall()[0][0] // either this or the above line and try and re-insert it thus: cursor.execute('update products set pic1=%s where id=%s, ;', (pic1, id)) it tells me I have an error in my MySQL syntax. What is the error? TIA, Victor -- Oook, J. Cliff Dyer Carolina Digital Library and Archives UNC Chapel Hill -- http://mail.python.org/mailman/listinfo/python-list
Re: Pickle problem
On Fri, Apr 18, 2008 at 11:55 AM, Mario Ceresa [EMAIL PROTECTED] wrote: Hello everybody: I'd like to use the pickle module to save the state of an object so to be able to restore it later. The problem is that it holds a list of other objects, say numbers, and if I modify the list and restore the object, the list itself is not reverted to the saved one, but stays with one element deleted. ... --- class A(object): objects = [] --- Your problem is in the class definition of A. You declare objects as a class variable, so it is shared between every instance of the class. When you pickle the instance a, then restore it, it continues to reference the same list, which is help by the class. You probably want the objects list to be an instance variable, like this: class A(object): def __init__(self): self.objects = [] If you make that change, pickling and unpickling works the way you expect. -- Jerry -- http://mail.python.org/mailman/listinfo/python-list
Re: get quote enclosed field in a line
[EMAIL PROTECTED] wrote: is there a simple way in perl, python, or awk/shell/pipe, that gets the user agent field in a apache log? e.g. the typical line is like this: 189.139.109.235 - - [07/Apr/2008:00:00:16 -0400] GET / Periodic_dosage_dir/lacru/manara.html HTTP/1.1 200 1933 xahlee.org http://xahlee.org/Periodic_dosage_dir/lacru/manara2.html; Mozilla/ 5.0 (Windows; U; Windows NT 5.1; es-ES; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13 - I want the part: Mozilla/5.0 (Windows; U; Windows NT 5.1; es-ES; rv: 1.8.1.13) Gecko/20080311 Firefox/2.0.0.13. Thanks. Xah [EMAIL PROTECTED] ∑ http://xahlee.org/ ☄ awk -F\ '{print $6}' httpd-access.log awk -F\ 'NF6{print $6}' httpd-access.log -- Michael Tosch @ hp : com -- http://mail.python.org/mailman/listinfo/python-list
Re: py3k concerns. An example
On Fri, 2008-04-18 at 08:58 -0700, Aaron Watters wrote: Why is the migration to py3k a concern? For example I have libraries which use string%dictionary substitution where the dictionary is actually an object which emulates a dictionary. The __getitem__ for the object can be very expensive and is only called when needed by the string substitution. In py3k string%dictionary is going away. Why? I have no idea. The replacement is a string.format(...) method which supports dictionary calling. string.format(**dictionary) But dictionary calling doesn't support dictionary emulation. So in the example below the substitution works but the call fails. === code class fdict(dict): def __getitem__(self, item): return got(+item+) def fn(**d): print d[boogie] if __name__==__main__: fd = fdict() print attempting string substitution with fake dictionary print print hello there %(boogie)s % fd # -- works print print now attempting function call with fake dictionary print fn(**fd) # -- fails === output % python2.6 dtest.py attempting string substitution with fake dictionary hello there got(boogie) now attempting function call with fake dictionary Traceback (most recent call last): File dtest.py, line 17, in module fn(**fd) File dtest.py, line 7, in fn print d[boogie] KeyError: 'boogie' end of output Consequently there is no simple way to translate my code, I think. I suspect you will find this kind of subtle issue in many places. Or worse, you won't find it until after your program has been installed in production. It's a damn shame because if string%dict was just left in it wouldn't be an issue. Also, if making f(**d) support dict emulation has any negative performance implications then I don't want it please. sigh. -- Aaron Watters === http://www.xfeedme.com/nucular/pydistro.py/go?FREETEXT=crack+open I was with you on this issue right up until that last paragraph. You want it, but only if its free. That's ridiculous. Every thing a computer does requires processor cycles. Do you really mean to tell me that string interpolation has been a major bottleneck for you? Now I think you're just whining because you like to hear yourself whine. Try coming up with a real standard for evaluation. How much of a performance hit will actually cause you trouble? 1% extra on string interpolation? 10%? 50%? 200%? You do provide a link to a website called xfeedme.com. And I just fed you. IHBT. HAND. :-/ -- Oook, J. Cliff Dyer Carolina Digital Library and Archives UNC Chapel Hill -- http://mail.python.org/mailman/listinfo/python-list
Re: Unicode chr(150) en dash
On Apr 18, 8:36 am, John Machin [EMAIL PROTECTED] wrote: hdante wrote: The character code in question (which is present in the page), 150, doesn't exist in ISO-8859-1. Are you sure? Consider (re-)reading all of the Wikipedia article. 150 aka \x96 doesn't exist in ISO 8859-1. ISO-8859-1 (two hyphens) is a superset of ISO 8859-1 (one hyphen) and adds the not-very-useful-AFAICT control codes \x80 to \x9F. See http://en.wikipedia.org/wiki/ISO/IEC_8859-1(the entry for 150 is blank) You must have been looking at the table of the lite ISO 8859-1 (one hyphen). Reading further you will see \x96 described as SPA or Start of Guarded Area. Then there is the ISO-8859-1 (two hyphens) table, including \x96. HTH, John Sorry, that's right, I should have been referring to the second table. -- http://mail.python.org/mailman/listinfo/python-list
Re: Excel Manipulation using Python
On Apr 18, 11:36 am, Tim Golden [EMAIL PROTECTED] wrote: Krishna wrote: I was trying to delete rows in an existing .xls file using python. How do I do that? I was using the following code, it seem to work if I type in python window, but if I save it in text editor and drage and drop the .py file, it doesnt work. What am I doing wrong here? Thanks for your help! import win32com.client from time import sleep excel = win32com.client.Dispatch(Excel.Application) def Extract(): excel.Visible = 0 workbook=excel.Workbooks.Open('C:\Trial.xls') i=1 for n in range(1,10): excel.Rows(i).Select excel.Selection.Delete excel.Selection.Delete i=i+2 workbook.Save() print saved excel.Quit() Several points worthy of note: 1) When you're dealing with Windows filenames, either make the strings raw -- Open (rc:\trial.txt) -- or use the other slashes =-- Open (c:/trial.xls). 2) You're not actually calling the Select and Delete methods, merely referencing them. Try .Delete () etc. 3) You're saving the workbook every time round the loop, but perhaps you knew that. Might prompt you everytime as you're overwriting, but again, maybe you knew... TJG- Hide quoted text - - Show quoted text - Cool, That worked! Thanks for your help TJG! -- http://mail.python.org/mailman/listinfo/python-list
Re: Pickle problem
On Apr 18, 11:55 am, Mario Ceresa [EMAIL PROTECTED] wrote: Hello everybody: I'd like to use the pickle module to save the state of an object so to be able to restore it later. The problem is that it holds a list of other objects, say numbers, and if I modify the list and restore the object, the list itself is not reverted to the saved one, but stays with one element deleted. An example session is the following: Data is A [1, 2, 3, 4] saving a with pickle Deleting an object: del a[3] Now data is A [1, 2, 3] Oops! That was an error: can you please recover to the last saved data? A [1, 2, 3] I'd like to have here A[1,2,3,4]!! Is it the intended behavior for pickle? if so, are there any way to save the state of my object? Code follows --- class A(object): objects = [] --- then I run the code: --- import pickle from core import A a = A() for i in [1,2,3,4]: a.objects.append(i) savedData = pickle.dumps(a) print Saved data is ,a print Deleting an object del a.objects[3] print a print Oops! This was an error: can you please recover the last saved data? print pickle.loads(savedData) Thank you for any help! Mario The problem is that the way you define 'objects', it is an attribute of the A *class*, not the instance you create. Change the A class to: class A(object): def __init__(self): self.objects = [] and rerun it; it should now work as you intended. HTH, George -- http://mail.python.org/mailman/listinfo/python-list
Re: py3k concerns. An example
Try coming up with a real standard for evaluation. How much of a performance hit will actually cause you trouble? 1% extra on string interpolation? 10%? 50%? 200%? You misread my comment. I don't want function calls to support dictionary emulation if there is a speed penalty because this is such a special case and function calls are so important. I don't really know, but I think fixing the above issue for string.format(...) might involve changing the representation of every python stack frame... not worth it in this case if there is any penalty (afaik there isn't). An alternative is to provide an alternate interface to string.format so that you could pass in an object which might emulate a dictionary, like string.formatDict(D) -- or you could even adopt a shortcut notation like string % D -- hey there's an idea! -- Aaron Watters === http://www.xfeedme.com/nucular/pydistro.py/go?FREETEXT=ignore+warnings -- http://mail.python.org/mailman/listinfo/python-list
Python 2.5 adoption
How widely adopted is python 2.5? We are doing some development, and have a choice to make: a) Use all the 2.5 features we want. b) Maintain backwards compatability with 2.4. So I guess the question is, does anyone have a sense of what percent of python users don't have 2.5? Thanks, Joseph -- http://mail.python.org/mailman/listinfo/python-list
Re: Request a short code review
Thank you all for posting insightful and useful comments. Here is what I have based on your input: def output_random_lesson_of_type(self, lesson_type=None): Output a lesson of a specific type. If no type is passed in then output all types. lessons = self.lesson_data[lessons] if lesson_type: lessons = [x for x in lessons if x[type] == lesson_type] rand_lesson = choice(lessons) inputs = self.create_lesson_inputs(rand_lesson) print rand_lesson[output] % inputs return rand_lesson, inputs Changes: - generator expression instead of filter - removed keyword 'type' in favor of lesson_type - wrap to 78 columns - remove error-check -- allow it to fail in the choice statement. I've decided to make a valid lesson_type an invariant anyway so the appropriate thing would be an assert - but I'll settle for a throw from choice if it receives an empty list - moved self.output_random logic into this function The lesson data is loaded from YAML which explains why it is inside a dictionary instead of a class. I am currently exploring ways to allow me to easily switch my data providers between SQLAlchemy and YAML. Cheers again. This is very valuable for me. I am a true believer that if one takes care in the smallest of methods then the larger code- base will be all the better. James. -- http://mail.python.org/mailman/listinfo/python-list
Re: py3k s***s
On Mon, Apr 14, 2008 at 04:10:48PM -0700, Sverker Nilsson wrote: do i dare to open a thread about this? come on you braver men we are at least not bought by g***le but why? others have said it so many times i think :- but why? a few syntactic 'cleanups' for the cost of a huge rewrite of all the code that have been builtup from all the beginning when the once great Python came along and people began to use it and write code for it. Like all that code would have to be rewritten. blaah. and i have perhaps been drinking but i have been p**d all week since i began look into this:-( -- http://mail.python.org/mailman/listinfo/python-list Yo, no one here is a child so don't litter your title and text with hard to read bullshit. -- Nick Stinemates ([EMAIL PROTECTED]) http://nick.stinemates.org -- http://mail.python.org/mailman/listinfo/python-list
Re: Python 2.5 adoption
On Apr 18, 1:08 pm, Joseph Turian [EMAIL PROTECTED] wrote: How widely adopted is python 2.5? We are doing some development, and have a choice to make: a) Use all the 2.5 features we want. b) Maintain backwards compatability with 2.4. So I guess the question is, does anyone have a sense of what percent of python users don't have 2.5? Thanks, Joseph I think it depends more on what you want to do. If you're distributing the software, you can just freeze it and make binaries and then it doesn't matter. Or if you use Python at your business, you can do what we do at my workplace: Put Python on the network and run all the scripts from there. Currently, we have 2.4 on our network, but I think we can upgrade it to 2.5 without breaking anything. I develop in 2.5 and just put the finished products on our network and they usually just work. But I have yet to find good use cases for some of the cool whizz-bang extras of 2.5, so I haven't pushed for the network upgrade. I hope to figure out when, where and how to use generators and decorators at some point, but I just haven't gotten that far a long yet, I guess. Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: Brand New!
On Tue, Apr 15, 2008 at 04:37:40PM -0700, agent E 10 wrote: On Apr 14, 8:37 pm, Benjamin [EMAIL PROTECTED] wrote: On Apr 14, 9:00 pm, agent E 10 [EMAIL PROTECTED] wrote: Hi, I'm brand new to programming. Have any suggestions? I'm young. Was it a good idea to start with python? I was planning on creating a very simple program that asked yes/no questions for a school project. IMHO, Python is an excellent language to start with. Have you read the tutorial?http://docs.python.org/tut/tut.html -Thanks!- Hide quoted text - - Show quoted text - No, I haven't. I have been reading off of this site http://www.freenetpages.co.uk/hp/alan.gauld/ is this a good site to learn off of? About how long will it take me to learn the basics of the language? -Thanks 4 all ur help! Agent E 10 -- http://mail.python.org/mailman/listinfo/python-list Windows or Unix/Linux? I find python is easier to learn in Linux environments, since it assumes some familiarty with the shell. -- Nick Stinemates ([EMAIL PROTECTED]) http://nick.stinemates.org -- http://mail.python.org/mailman/listinfo/python-list
Re: Brand New!
On Wed, Apr 16, 2008 at 02:35:54AM -0300, Gabriel Genellina wrote: En Tue, 15 Apr 2008 20:37:40 -0300, agent E 10 [EMAIL PROTECTED] escribió: On Apr 14, 8:37 pm, Benjamin [EMAIL PROTECTED] wrote: On Apr 14, 9:00 pm, agent E 10 [EMAIL PROTECTED] wrote: Hi, I'm brand new to programming. Have any suggestions? I'm young. Was it a good idea to start with python? I was planning on creating a very simple program that asked yes/no questions for a school project. IMHO, Python is an excellent language to start with. Have you read the tutorial?http://docs.python.org/tut/tut.html No, I haven't. I have been reading off of this site http://www.freenetpages.co.uk/hp/alan.gauld/ is this a good site to learn off of? About how long will it take me to learn the basics of the language? I'm unsure if teaching Javascript, VBScript and Python at the same time is a good thing, I'd think one would get a language soup and mix all the concepts, but if it works for you, go ahead. For other resources, see the beginners section in the Python wiki: http://wiki.python.org/moin/BeginnersGuide I agree and disagree! As long as the student understands how the different parts play together, and the Web medium is what gets him interested in python, I don't see any harm! That's a pretty big assumption though! -- Nick Stinemates ([EMAIL PROTECTED]) http://nick.stinemates.org -- http://mail.python.org/mailman/listinfo/python-list
Re: Brand New!
On Wed, Apr 16, 2008 at 07:48:37AM +0200, Paul Scott wrote: On Wed, 2008-04-16 at 02:35 -0300, Gabriel Genellina wrote: I'm unsure if teaching Javascript, VBScript and Python at the same time is a good thing, I'd think one would get a language soup and mix all the concepts, but if it works for you, go ahead. For other resources, see the beginners section in the Python wiki: http://wiki.python.org/moin/BeginnersGuide Well, as an example, I learnt Python to a decent level of competency in 2 days. I looked through the Dive into Python tuts, and then had a look at the Python GUI FAQ (Which didn't really help much, as I started with a GTK based GUI app). A little bit of Googling and a couple of questions to this list gave me everything that I needed to roll out a pretty decent application in 5 days. Oh, and just by the way, I am _not_ a Computer Scientist or anything, I am a botanist, which means that if I can do that, just about anyone that can read can do it. Python has been long on my list of TODO's, and now, finally, it is there. I have immensely enjoyed it so far, and will continue to tinker well into the future. --Paul I think that's wonderful! I think problem solving language independent. As long as you can break down what you need to do and conceptualize. You must have learned to do with with botany, so programming came natural :) -- Nick Stinemates ([EMAIL PROTECTED]) http://nick.stinemates.org -- http://mail.python.org/mailman/listinfo/python-list
Re: py3k s***s
On Fri, 18 Apr 2008 11:32:15 -0700, Nick Stinemates [EMAIL PROTECTED] wrote: [snip] Yo, no one here is a child Hi Nick, Actually, there are a number of young people on the list. So let's keep things civil and try to avoid using harsh language. Thanks! Jean-Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Installing BeautifulSoup with easy_install (broken?)
John Nagle wrote: easy_install usually seems to make things harder. BeautifulSoup is one single .py file. That's all you need. Everything else is excess baggage. I wouldn't call the installation of a single module Python package a good example for the usual case. Stefan -- http://mail.python.org/mailman/listinfo/python-list
ANN: pyspread 0.0.1
pyspread 0.0.1 is now available at: http://pyspread.sourceforge.net pyspread is a spreadsheet that accepts a pure python expression in each cell. Highlights: + No non-python syntax add-ons + Access to python modules from cells + 3D grid + Numpy object array for representation of string entry into grid cell + Numpy object array for representation of eval function array + Cell access via slicing of numpy function array + X, Y, and Z yield current cell location for relative reference Requires: Python 2.5, Numpy 1.0.4, and wxPython 2.8.7.1. License: GPL Best Regards Martin Manns -- mmanns at gmx.net -- http://mail.python.org/mailman/listinfo/python-list
Python Logging question
I am new to Python and I am trying to understand how to utilize the RotatingFileHandler to rollover when the file gets to a certain size. I followed some examples that I have found for setting the size and the number of files. However, I am finding that when the log file gets close to the threshold I start getting errors in the handlers.py file saying the file is closed. I am using Python 2.5 on Windows. Is this a problem others have seen? Is this a handler that is widely used or is there a better one that is generally used? The error that I am receiving is shown below. Traceback (most recent call last): File C:\Python25\Lib\logging\handlers.py, line 73, in emit if self.shouldRollover(record): File C:\Python25\Lib\logging\handlers.py, line 147, in shouldRollover self.stream.seek(0, 2) #due to non-posix-compliant Windows feature ValueError: I/O operation on closed file My configuration file is setup as such: [handler_file_detailed] class:handlers.RotatingFileHandler level:DEBUG formatter:detailed mode=a maxsize=400 backcount=5 args:('python.log','a',400,5) I would appreciate any feedback on this subject. Thanks, Todd -- http://mail.python.org/mailman/listinfo/python-list
Re: program to Ping ip addresses
On Tue, Apr 15, 2008 at 07:24:05AM -0700, shawn s wrote: Hi I am trying to modify a small program i found off the internet as follows... I can get the 'tracert' to work and it gives me all the info back. However, when i replace the tracert with 'ping', the commamd prompt shows 'testing' and the script freezes... any suggestions as why it is doing that. import os import sys xyz = 1 while xyz==1: ip = raw_input(command ) zx = open(log.txt, a) if ip.lower()==exit: ask = raw_input(Are you sure you want to exit? (Y\\N) ) if ask.lower()==y: sys.exit() elif ask.lower()==n: print(That's what I thought.) else: print(Wrong choice. Retard.) elif ip.lower()==range: stin = raw_input(Enter function: ) sec = raw_input(Enter the first 3 sections: ) b = raw_input(Enter beginning number: ) intb=int(b) e = int(raw_input(Enter ending number: )) while intb=e: print (stin + ' ' + sec + '.' + b ) z = os.system(stin + ' ' + sec + '.' + b ) print z if z==0: print(+str(sec)+.+str(b)+ is online.) zx.write(+str(sec)+.+str(b)+ is online.\n) elif z==1: print(Either +str(sec)+.+str(b)+ is offline, or ping request has been blocked.) zx.write(Either +str(sec)+.+str(b)+ is offline, or ping request has been blocked.\n) intb = intb + 1 b=str(intb) else: print(Wrong choice. Retard.) I love that you call the users of your app retards :) That rocks! ping runs forever. tracert doesnt. try: ping -w 5 -- Nick Stinemates ([EMAIL PROTECTED]) http://nick.stinemates.org -- http://mail.python.org/mailman/listinfo/python-list
Re: How to have unittest tests to be executed in the order they appear?
On Tue, Apr 15, 2008 at 03:14:39PM -0400, D'Arcy J.M. Cain wrote: However, do consider writing your tests so that order is irrelevant. If a test depends on a previous test running then it isn't a proprt self-contained test. For one thing, you can't run a single test that way if you wanted to. Agreed! -- Nick Stinemates ([EMAIL PROTECTED]) http://nick.stinemates.org -- http://mail.python.org/mailman/listinfo/python-list
Re: Getting subprocess.call() output into a string?
On Tue, Apr 15, 2008 at 11:16:01PM +0200, David wrote: Still, about StringIO... The module description says you can use it to read and write strings as files, not that you can use strings *everywhere* you can use files. In your specific case, StringIO doesn't work, because the stdout redirection takes place at the operating system level (which uses real file handles), rather than in a python library (for which StringIO would probably work). David. -- http://mail.python.org/mailman/listinfo/python-list Just a note to all of those who are interested. I have yet to get this to work properly for an app which runs indefinitely and you want to read the output at a specified interval. Right now the only way I can read is if the _close() method has been called. Anyway, I wrote a wrapper around it so I could easily change the implementation if I could ever find a better solution. Here's my code: === import subprocess import os import select class ProcessMonitor: def __init__(self): self.__process = None self.__stdin = None self.__stdout = None def _create(self, process): self.__process = subprocess.Popen(process, stdin=subprocess.PIPE, stdout=subprocess.PIPE, close_fds=True) self.__stdin = self.__process.stdout self.__stdout = self.__process.stdout def _close(self): os.kill(self.__process.pid,9) def _listen(self): get from stdout return .join(self.__stdout.readlines()) def _listen2(self): My attempt at trying different things. inp, out = self.__process.communicate() print out -- Nick Stinemates ([EMAIL PROTECTED]) http://nick.stinemates.org -- http://mail.python.org/mailman/listinfo/python-list
Easiest way to get started with WebApps?
which is the easiest module to use to just get started with webapps quicklya nd starting getting things up and running, not advanced stuff just basic. -- http://mail.python.org/mailman/listinfo/python-list
Re: python beginer
On Wed, Apr 16, 2008 at 12:50:51PM +0530, ashish kamble wrote: hi, can anyone tell me hw to start with webapplication scripting(e.g login page..etc) if anyone has soln for this or simple e.g that mention above please send me by and have a nice day -- http://mail.python.org/mailman/listinfo/python-list Start with learning how to type. -- Nick Stinemates ([EMAIL PROTECTED]) http://nick.stinemates.org -- http://mail.python.org/mailman/listinfo/python-list
Re: insert python script in current script
On Wed, Apr 16, 2008 at 01:41:13PM -0500, Larry Bates wrote: Prashant wrote: I was wondering is there any way to do this: I have written a class in python and __init__ goes like this: def __init__(self): self.name = 'jack' self.age = 50 import data now here there is data.py in the same directory and contents are like: self.address = 'your address' self.status = 'single' The problem is 'self' is giving some error here. I need to know if somehow I can do this. It's like inserting the script as it's part of the file itself. Cheers Can you give a use case for doing this. You would most likely be better doing: class person(object): def __init__(self, name=None, age=None): self.name=name self.age=age personInstance=person(name='jack', age='50) -Larry -- http://mail.python.org/mailman/listinfo/python-list Could it also be that he would like to have a base class? Cause that's what It sounds like to me! class Base: def __init__(self): self.address = address self.status = 1 //use numbers instead of strings :) class Person(Base): def __init__(self): Base.__init__(self) # now you have the self.address, self.status -- Nick Stinemates ([EMAIL PROTECTED]) http://nick.stinemates.org -- http://mail.python.org/mailman/listinfo/python-list
Re: Python 2.5 adoption
Joseph Turian wrote: How widely adopted is python 2.5? We are doing some development, and have a choice to make: a) Use all the 2.5 features we want. b) Maintain backwards compatability with 2.4. So I guess the question is, does anyone have a sense of what percent of python users don't have 2.5? Desktop or server? If server, check what the major Linux distros, like Fedora Core, are shipping with. Check major shared hosting providers to see what they're offering to their customers as standard. John Nagle -- http://mail.python.org/mailman/listinfo/python-list
Re: how turbo geras code works
On Wed, Apr 16, 2008 at 01:35:29AM -0700, reetesh nigam wrote: hi. actually i have developed one small project but now i want to develope a project with the help of html.. please help me out -- http://mail.python.org/mailman/listinfo/python-list OK. Done -- Nick Stinemates ([EMAIL PROTECTED]) http://nick.stinemates.org -- http://mail.python.org/mailman/listinfo/python-list