Re: Why not just show the out-of-range index?
Fredrik Lundh wrote: > Russ wrote: > > >> No one is castigating the OP for bringing up the issue. His suggestion > >> that his > >> time is worth more than that of anyone else, though, is drawing some ire. > > > > I'm afraid that any such "suggestion" is purely in your own > > imagination. > >"Now, that would be rather silly. I would have to familiarize myself >with the code for the Python interpreter, then send a patch to the >maintainers (and hope they notice it in their inboxes), while the >maintainers themselves could probably "fix" the problem in two minutes >flat. No thanks!" That is a perfectly reasonable statement. Forgive me if I underestimated the difficulty of implementing the feature I suggested, but I still don't think it would be difficult for the code maintainers to implement. They are obviously familiar with the code, but I'm not! > and a couple of other posts with a similar tone. open source developers > tend to ignore people who use the "you're just a bunch of code monkeys" > intimidation approach, especially when combined with an undertone of > "what I'm proposing should be easy, and if it isn't, that's because > you're incompetent". claiming to talk for everyone else doesn't really > help, either. Boy, some of you guys seem to have a very low self esteem, reading insults where none exist. "Just a bunch of code monkeys"?!! Where in the friggin' world did I say anything remotely resembling that? I happen to be a proud "code monkey" myself, for crying out loud! And excuse me for suggesting a minor new feature to enhance the productivity of Python without implementing it myself! Geez! -- http://mail.python.org/mailman/listinfo/python-list
Re: Parsing data from pyserial, an (inefficient) solution
Dennis Lee Bieber wrote: > >> The really sad thing is that I get a perfectly constructed >> packet from the reading variable, and that gets butchered when I >> try to slice it up to pick out individual elements. Since >> pyserial doesn’t do anything to rearrange the data, then the >> CMUcam must do the heavy lifting of extracting a perfect packet >> from the data stream. It’s a real shame I couldn’t use it > > More likely it is running fast enough to keep up with the serial > port, and synchronizes on the "\rM". Your code seems to be reading in > bursts and somehow losing parts during your processing (which is > strange, I'd have expected pyserial to buffer some data between reads). > > Lacking that, I'd probably end up creating a thread to handle the > serial port reading, which basically looks like: > > while ser.read(1) != "\r": pass #synchronize > while not Done: > bfr = [] > while True: > c = ser.read(1) > bfr.append(c) > if c == "\r": break > queue.put("".join(bfr)) > > This should result in complete packets (from the "M" to a "\r") Oh well. readline(eol="\r") will do that much better. while 1: data = ser.readline(eol="\r") args = data.split() if args[0] == "M": # command M; do something with args[1:] elif args[0] == "KK": # command KK; do something with args[1:] [.. process other commands ..] else: # Invalid command: might be an incomplete # packet. Just ignore it. pass -- http://mail.python.org/mailman/listinfo/python-list
Re: Why not just show the out-of-range index?
Russ wrote: > And > excuse me for suggesting a minor new feature to enhance the > productivity of Python without implementing it myself! Geez! Like I said, no one is castigating you for making the request. It's been your attitude afterwards that is the problem. You've been pointed to the productive things you can do to resolve the issue that you have: 1. Submit a bug report. 2. Submit a patch. Nothing is going to happen until you do one of these two things. Being more rude (and yes, you are being incredibly rude and insulting) won't move things along. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco -- http://mail.python.org/mailman/listinfo/python-list
Re: algorithm for sorting functional expressions
In <[EMAIL PROTECTED]>, chrisguest wrote: > So I suspect that this is a common problem for those familiar with > partially ordered sets or directed graphs. I'm wondering if anyone else > is familiar with this problem and knows an efficient algorithm that > will solve it. It would be good if any such algorithm would be able to > check for circular definitions in the input. You are looking for "topological sort". Feed a search engine with that term. :-) Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Why not just show the out-of-range index?
Russ wrote: > Boy, some of you guys seem to have a very low self esteem yeah, of course. it's always someone else's fault. now, can you please go to the feature request tracker: http://sourceforge.net/tracker/?group_id=5470&atid=355470 and follow the instructions on that page? -- http://mail.python.org/mailman/listinfo/python-list
Re: algorithm for sorting functional expressions
<[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] >I am trying to write some code that will take a list of functional > expressions, and order them so that those with primitive terms appear > at the beginning of the list and those that are defined by other terms > appear last. > > eg: > getSortedEquations(['b = w + z','a = z - y','w = 2*z + v','z = e + > f','y = p + l']) = > ['w = 2*z + v', 'z = e + f', 'y = p + l', 'b = w + z', 'a = z - y'] > > It is easy enough to tokenise each of the equations and produce a list > like: > ['b', ['w','z']], ['a': ['z','y']], ['w':'z','v'] , ['z', ['e','f']], > ['y',['p','l']] > > But I'd like to find an algorithm that can handle the sorting problem. > > So I suspect that this is a common problem for those familiar with > partially ordered sets or directed graphs. Right. > I'm wondering if anyone else > is familiar with this problem and knows an efficient algorithm that > will solve it. It would be good if any such algorithm would be able to > check for circular definitions in the input. Read http://en.wikipedia.org/wiki/Topological_sorting or just search for "topological sorting" on the net. Regards, Christian -- http://mail.python.org/mailman/listinfo/python-list
Re: algorithm for sorting functional expressions
Marc 'BlackJack' Rintsch wrote: >> So I suspect that this is a common problem for those familiar with >> partially ordered sets or directed graphs. I'm wondering if anyone else >> is familiar with this problem and knows an efficient algorithm that >> will solve it. It would be good if any such algorithm would be able to >> check for circular definitions in the input. > > You are looking for "topological sort". Feed a search engine with that > term. :-) including "python" in the search request might be a good idea. here's a topsort in Python: http://mail.python.org/pipermail/python-list/1999-July/006660.html (note that most code in that module is for analyzing cycles in case the sort fails, not for the sort itself). -- http://mail.python.org/mailman/listinfo/python-list
Re: RAD for python
progman a écrit : > is there a VB-alike tool for python to create forms?? Maybe take a look at DaboDev http://dabodev.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Video stream server
Fredrik, Thank you for your reply > > but I think you're missing the point; you need to provide more > information about your specific requirements than just "a HTML > page that links to a video file". like, say, in what way this > is related to Python, what software you're using today, what > kind of videos we're talking about, etc. The most important thing now is how to add a support for video files. As to kind of videos, it is not too much important because I can allow user to upload/play a certain kinds of videos only or transform some kinds of videos into the correct types > what way this is related to Python, I love Python so I would like to implement video support in Python. That is how it is related to Python only L. > > -- http://mail.python.org/mailman/listinfo/python-list
Re: Why not just show the out-of-range index?
Robert Kern wrote: > Nothing is going to happen until you do one of these two things. Being more > rude > (and yes, you are being incredibly rude and insulting) won't move things > along. I re-read the thread, and I don't see anywhere where I was rude except in reply to rudeness by others. Sorry, but I haven't mastered the "turn the other cheek" thing yet. My suggestion that it would be much easier for the Python maintainers than for me to implement the requested feature is just basic common sense. I would have to spend many hours or days just to familiarize myself with the code, but they are obviously already very familiar with it. And they would probably have to spend nearly as much time checking my patch as they would writing it themselves anyway. By the way, your parenthical assertion that I am "being incredibly rude and insulting" is itself an unwarranted and devious insult, and I will not let you get away with it without being called on it. But I'm willing to forget about it and move on, and I'll assume you are too. -- http://mail.python.org/mailman/listinfo/python-list
Re: Why not just show the out-of-range index?
Russ wrote: > Robert Kern wrote: > >> Nothing is going to happen until you do one of these two things. Being more >> rude >> (and yes, you are being incredibly rude and insulting) won't move things >> along. > > I re-read the thread, and I don't see anywhere where I was rude except > in reply to rudeness by others. Sorry, but I haven't mastered the "turn > the other cheek" thing yet. Learn quickly if you are going to keep asking for other people's help. > My suggestion that it would be much easier for the Python maintainers > than for me to implement the requested feature is just basic common > sense. I would have to spend many hours or days just to familiarize > myself with the code, but they are obviously already very familiar with > it. And they would probably have to spend nearly as much time checking > my patch as they would writing it themselves anyway. You're still missing the other side of the balance: how much the person wants the feature. I simply don't care enough about the issue to put in the effort that it would take me. You don't care enough, either, to put in the effort that it would take you. That's fine. That's your judgment to make. What's disrespectful is your expectation that you can make that judgment call for other people. Just because it might take me less time to do it doesn't mean that I am obliged to want it as much as you do. > By the way, your parenthical assertion that I am "being incredibly rude > and insulting" is itself an unwarranted and devious insult, and I will > not let you get away with it without being called on it. As you wish. Insults are in the ear of the listener, not the speaker. With that rule in mind, however, what I said is a simple statement of fact. If the statement of facts insults you, I'm sorry. You are going to have a very difficult time here. You're also missing that *I'm trying to help you*. The way that you have been acting, regardless of whether you think it is rude or not, will not convince anyone to solve your problem. In short, you've asked for a feature in the hope that someone will think it important enough to do it themselves. No one who has read the thread does. At least, not in the time frame since you've posted. That may change; in which case, you should submit the bug report so that the core developers who didn't read this thread (i.e. nearly all of them) will see it. Maybe they will be in a small-feature-implementing mood and will want to implement it. If you don't submit the bug report, odds are everyone will forget all about it. Or you can take this as a learning opportunity, and make the fix yourself. Then the next time you run into something like this (and I imagine that you will), you can take the two minutes to fix it. > But I'm > willing to forget about it and move on, and I'll assume you are too. Submit the bug report, and I will. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco -- http://mail.python.org/mailman/listinfo/python-list
Re: Multiple FTP download using Muliti thread
import ftplib, posixpath, threading from TaskQueue import TaskQueue def worker(tq): while True: host, e = tq.get() c = ftplib.FTP(host) c.connect() try: c.login() p = posixpath.basename(e) fp = open(p, 'wb') try: c.retrbinary('RETR %s' % e, fp.write) finally: fp.close() finally: c.close() tq.task_done() if __name__ == '__main__': q = TaskQueue() host = 'ftp.microsoft.com' c = ftplib.FTP(host) c.connect() try: c.login() folder = '/deskapps/kids/' for n in c.nlst(folder): if n.lower().endswith('.exe'): q.put((host, n)) finally: c.close() numworkers = 4 for i in range(numworkers): t = threading.Thread(target=worker, args=(q,)) t.setDaemon(True) t.start() q.join() print 'Done.' -- http://mail.python.org/mailman/listinfo/python-list
Re: Multiple FTP download using Muliti thread
Justin Ezequiel wrote: > from TaskQueue import TaskQueue what Python version is this ? -- http://mail.python.org/mailman/listinfo/python-list
Re: Multiple FTP download using Muliti thread
Fredrik Lundh wrote: > Justin Ezequiel wrote: > > > from TaskQueue import TaskQueue > > what Python version is this ? > > oops. forgot to note... http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/475160 -- http://mail.python.org/mailman/listinfo/python-list
Inheritance doesn't work
I have a problem with inheritance under python. The class definition is longer, but the troublesome thing is: from PIL import Image class MandelbrotImage (Image): pass I am getting the following error: Traceback (most recent call last): File "", line 1, in ? File "mandelimage.py", line 3, in ? class MandelImage (Image): TypeError: Error when calling the metaclass bases module.__init__() takes at most 2 arguments (3 given) I am using python 2.4 from the Debian (Sid) packages. Is it a bug, or am I doing something wrong? zefciu -- -BEGIN zefciu's GEEK CODE BLOCK- Version: 3.12 GS d-(+) s+++:-- a-- C++ UL P- L++(+++) E--- W+ N++ o? K? w-- M- V? PS-(--) PE++(+) Y PGP+ t 5 X R tv- b++ DI D- G e>+++ h!>-- y? UF+ --END zefciu's GEEK CODE BLOCK-- -- http://mail.python.org/mailman/listinfo/python-list
Re: Inheritance doesn't work
zefciu wrote: > I have a problem with inheritance under python. The class definition is > longer, but the troublesome thing is: > > from PIL import Image > class MandelbrotImage (Image): > pass > > I am getting the following error: > Traceback (most recent call last): >File "", line 1, in ? >File "mandelimage.py", line 3, in ? > class MandelImage (Image): > TypeError: Error when calling the metaclass bases > module.__init__() takes at most 2 arguments (3 given) > > > I am using python 2.4 from the Debian (Sid) packages. > > Is it a bug, or am I doing something wrong? You're doing something wrong. PIL.Image is a module, not a class. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco -- http://mail.python.org/mailman/listinfo/python-list
Re: Inheritance doesn't work
zefciu wrote: > I have a problem with inheritance under python. The class definition is > longer, but the troublesome thing is: > > from PIL import Image that's a module, not a class. > class MandelbrotImage (Image): > pass PIL's Image class isn't designed to be inherited from. to create new images, use the Image.new() factory. -- http://mail.python.org/mailman/listinfo/python-list
Re: Multiple FTP download using Muliti thread
Justin Ezequiel wrote: > Fredrik Lundh wrote: >> Justin Ezequiel wrote: >> >> > from TaskQueue import TaskQueue >> >> what Python version is this ? >> >> > > oops. forgot to note... > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/475160 Also noteworthy: "This recipe was accepted for inclusion in Py2.5.", i. e. in Python 2.5 you can use Queue instead of TaskQueue. Peter -- http://mail.python.org/mailman/listinfo/python-list
Python Jobs
I'm writing from an IT Recruitment consultancy, I have an opportunity for either an experienced Python developer or someone looking to cross train in to Python in a permanent role. The role is based in the Amersham, Buckinghamshire for a small but well established software house. You will be required to develop a range of bespoke Web applications using a range of Object Orientated languages - Mainly Python. Candidates should be skilled in one or more of the following: OO, PHP, SQL/SQL Server Database Development Integration, XML. More information on application. Excellent opportunity to cross train in other development languages such as PostgreSQL and Python. Training provided. Call for more details - 01932 245500 Matt Hancock - Recruitment Consultant. [EMAIL PROTECTED] www.jenrickcpi.co.uk 01932 245500 -- http://mail.python.org/mailman/listinfo/python-list
Re: RAD for python
progman wrote: > > is there a VB-alike tool for python to create forms?? http://wxglade.sourceforge.net/ http://boa-constructor.sourceforge.net/ http://www.activestate.com/Products/Komodo/ http://www.roebling.de/ hg -- http://mail.python.org/mailman/listinfo/python-list
Re: os.mkdir and mode
Peter Otten <[EMAIL PROTECTED]> wrote: > >> "Where it is used, the current umask value is first masked out." > >> > >> Use os.chmod() after os.mkdir() to get the desired permissions. > > > > I think you meant use os.umask(0) before the os.mkdir() ? > > No, I didn't. What is the difference/advantage of that approach? If you use use os.umask(0) then the os.mkdir(dir, perms) will create the directory with exactly those permissions, no chmod needed. -- Nick Craig-Wood <[EMAIL PROTECTED]> -- http://www.craig-wood.com/nick -- http://mail.python.org/mailman/listinfo/python-list
Re: os.mkdir and mode
Martin v. Löwis <[EMAIL PROTECTED]> wrote: > Nick Craig-Wood schrieb: > > So it looks like python mkdir() is applying the umask where as > > /bin/mkdir doesn't. From man 2 mkdir > > Actually, mkdir(1) has no chance to not apply the umask: it also > has to use mkdir(2), which is implemented in the OS kernel, and > that applies the umask. Try Yes you are right of course. I didn't think that statment through did I! > strace mkdir -m770 test > > to see how mkdir solves this problem; the relevant fragment > is this: > > umask(0)= 022 > mkdir("test", 0770) = 0 > chmod("test", 0770) = 0 > > So it does *both* set the umask to 0, and then apply chmod. > > Looking at the source, I see that it invokes umask(0) not to > clear the umask, but to find out what the old value was. > It then invokes chmod to set any "special" bits (s, t) that > might be specified, as mkdir(2) isn't required (by POSIX spec) > to honor them. That makes sense - the odd sequence above is one of those Unix workarounds then... -- Nick Craig-Wood <[EMAIL PROTECTED]> -- http://www.craig-wood.com/nick -- http://mail.python.org/mailman/listinfo/python-list
get script path
Hi, must I parse argv[0] to get it, or is there an easier way (that works under Windows and *nix)? Ex: python /home/hg/test/test.py ==> test.py #knows it is in /home/hg/test Thanks, hg -- http://mail.python.org/mailman/listinfo/python-list
Re: global name 'self' is not defined
The problem seems to be with ipython, which I have been using to run these scripts. My calling script (call.py) is: import canaryPlaces_test as canp sum=canp.addme(3,5) print sum estoc=canp.estocStn() print estoc The problem script is this one, named canaryPlaces_test.py: def estocStn(): estoc={'lat':29.15,'lon':-15.667,'place':'ESTOC'} return estoc def addme(a,b): sumAb=a+b return sumAb The ok script, named canaryPlaces.py, is identical apart from a comment at the top of one of them. Here is output from 'diff' for the two of them: @suse212:~/python/mapping> diff canaryPlaces_test.py canaryPlaces.py 1c1 < --- > # canaryPlaces [EMAIL PROTECTED]:~/python/mapping> >From the command line I get what I expect calling either canaryPlaces_test.py or canaryPlaces.py: @suse212:~/python/mapping> python call.py 8 {'lat': 29.149, 'place': 'ESTOC', 'lon': -15.667} [EMAIL PROTECTED]:~/python/mapping> However -> Using ipython and calling canaryPlaces.py is fine, but calling canaryPlaces_test.py gives: In [97]: %run call 8 --- exceptions.NameError Traceback (most recent call last) /home/evan/python/mapping/call.py 2 3 sum=canp.addme(3,5) 4 print sum > 5 estoc=canp.estocStn() 6 print estoc /home/evan/python/mapping/canaryPlaces_test.py in estocStn() 5return estoc 6 7 def addme(a,b): 8sumAb=a+b 9return sumAb NameError: global name 'self' is not defined WARNING: Failure executing file: In [98]: On my system this error is repeatable. -Evan Bjoern Schliessmann wrote: > Evan wrote: > > > So I have deleted the 'old' script2 and renamed the new one, and > > no problem. > > Pity. Next time try using diff (or something similar). > > Regards, > > > Björn > > -- > BOFH excuse #115: > > your keyboard's space bar is generating spurious keycodes. -- http://mail.python.org/mailman/listinfo/python-list
Re: Printing Barcodes from webapp?
"Andy Dingley" <[EMAIL PROTECTED]> writes: > Burhan wrote: > > > Is there an easy way to generate barcodes using Python > > Easy way for any application or language to generate barcodes is to > install a barcode font on the client machine, then just generate a > suitable text string for it. This is _very_ easy, if you can get the > font deployed. I usually find myself using Code 39 and printing them > from a HTML document. There are plenty of free code 39 fonts around and > the string mangling to get the barcode structured correctly is just a > trivial prefix / suffix. Sometimes that's really convenient. Depending on the barcode, this may not always be easy, though. Certainly there are some complications, ranging from things like relatively simple check digits, through complicated encodings (my colleague Robin tells me US postal bar codes were a particular pain), up to funny-looking 2D "bar" codes like PDF417, that have lots of complicated rules associated with them. The ReportLab open source toolkit barcode support handles this kind of thing for you -- for the barcodes it supports, anyway. John -- http://mail.python.org/mailman/listinfo/python-list
Re: get script path
hg wrote: > Hi, > > must I parse argv[0] to get it, or is there an easier way (that works > under Windows and *nix)? > > Ex: > > python /home/hg/test/test.py ==> test.py #knows it is in /home/hg/test > > Thanks, > > hg got it: os.path.dirname(sys.argv [0]) -- http://mail.python.org/mailman/listinfo/python-list
Re: get script path
hg wrote: > Hi, > > must I parse argv[0] to get it, or is there an easier way (that works under > Windows and *nix)? > > Ex: > > python /home/hg/test/test.py ==> test.py #knows it is in /home/hg/test IMHO it is easy enough: >>> dname, fname = os.path.split("/home/hg/test/test.py") >>> dname '/home/hg/test' -- HTH, Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: Beautiful Soup Question: Filtering Images based on their width and height attributes
> Hello, > > I want to extract some image links from different html pages, in > particular i want extract those image tags which height values are > greater than 200. Is there an elegant way in BeautifulSoup to do this? Yes. soup.findAll(lambda tag: tag.name=="img" and tag.has_key("height") and int(tag["height"]) > 200) -- http://mail.python.org/mailman/listinfo/python-list
Re: get script path
Rob Wolfe wrote: > > hg wrote: >> Hi, >> >> must I parse argv[0] to get it, or is there an easier way (that works >> under Windows and *nix)? >> >> Ex: >> >> python /home/hg/test/test.py ==> test.py #knows it is in /home/hg/test > > IMHO it is easy enough: > dname, fname = os.path.split("/home/hg/test/test.py") dname > '/home/hg/test' > > -- > HTH, > Rob thanks -- http://mail.python.org/mailman/listinfo/python-list
Execution time of lines within a function
Hello, I have a function that hotshot says is very slow. I can get the aggregate execution time, but is there a way to get the execution time of each line so I can find the bottleneck? Thank you -- http://mail.python.org/mailman/listinfo/python-list
Re: Inheritance doesn't work
How about calling base class __init__ and then the pass statement? --- zefciu <[EMAIL PROTECTED]> wrote: > I have a problem with inheritance under python. The > class definition is > longer, but the troublesome thing is: > > from PIL import Image > class MandelbrotImage (Image): > pass > > I am getting the following error: > Traceback (most recent call last): >File "", line 1, in ? >File "mandelimage.py", line 3, in ? > class MandelImage (Image): > TypeError: Error when calling the metaclass bases > module.__init__() takes at most 2 arguments (3 > given) > > > I am using python 2.4 from the Debian (Sid) > packages. > > Is it a bug, or am I doing something wrong? > zefciu > > -- > -BEGIN zefciu's GEEK CODE BLOCK- > Version: 3.12 > GS d-(+) s+++:-- a-- C++ UL P- L++(+++) E--- W+ N++ > o? > K? w-- M- V? PS-(--) PE++(+) Y PGP+ t 5 X R tv- b++ > DI D- G e>+++ h!>-- y? UF+ > --END zefciu's GEEK CODE BLOCK-- > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: please provide urls for some python success stories.
http://pythonology.org/success this should be enough...but why don't you write a solid app in python and show it to them? Seeing is believing. Bernard krishnakant Mane a écrit : > hello all. > actually I have been recently appointed as a technology consulltent at > a huge company. > and I have couple more such projects in the pypeline. > unfortunately the officials out here are too much in favour of java > and I have personally worked with both and find that python is heaven > in syntax and makes it very easy to do complex things. on speed? I > think experts on this list can give better answer, but efficiency and > maintainance wise there is nothing like python I believe. > the problem here is that I am from India and all indians on this list > can correct me if I am wrong, very few people know about python here. > infact a vast majority of programmers ask me "python? what is that!" > they don't even know that it is a programming language, let alone using it. > but I am amongst the very few who have actually used both java and python. > I need some strong evidence to prove to these stupid and java oriented > officials that there is some thing better than java called python. > can some one provide me some urls or may be share some personal > experience on this issue? > I saw a couple of blogs and a few success stories on the python web site > itself. > but the common answer I am getting is "y! even java can do this and > java is much faster!" > I am really adicted to python due to its superiority and efficiency > and the amount of libraries. > but I need some strong official efidence. > Please help me, I don't want to leave python. > Krishnakant. -- http://mail.python.org/mailman/listinfo/python-list
Re: Execution time of lines within a function
On 2006-12-04, monkeyboy <[EMAIL PROTECTED]> wrote: > I have a function that hotshot says is very slow. I can get the > aggregate execution time, but is there a way to get the > execution time of each line so I can find the bottleneck? Try 'print_callees' on the stats object for your bottleneck. That may help. -- Neil Cerutti -- http://mail.python.org/mailman/listinfo/python-list
Re: About alternatives to Matlab
Jon Harrop wrote: [...] > I first wrote an OCaml translation of the Python and wrote my own > little "slice" implementation. I have since looked up a C++ solution and > translated that into OCaml instead: > > let rec d4_aux a n = > let n2 = n lsr 1 in > let tmp = Array.make n 0. in > for i=0 to n2-2 do > tmp.(i) <- a.(i*2)*.h0+.a.(i*2+1)*.h1+.a.(i*2+2)*.h2+.a.(i*2+3)*.h3; > tmp.(i+n2) <- a.(i*2)*.g0+.a.(i*2+1)*.g1+.a.(i*2+2)*.g2+.a.(i*2+3)*.g3; > done; > tmp.(n2-1) <- a.(n-2)*.h0 +. a.(n-1)*.h1 +. a.(0)*.h2 +. a.(1)*.h3; > tmp.(2*n2-1) <- a.(n-2)*.g0 +. a.(n-1)*.g1 +. a.(0)*.g2 +. a.(1)*.g3; > Array.blit tmp 0 a 0 n; > if n > 4 then d4_aux a (n lsr 1) > > let d4 a = d4_aux a (Array.length a) > > Not only is that shorter than the Python and makes my eyes bleeding, but it's only my personal feeling. Try reading the code above aloud and you will see why `shorter` is not necessarily considered a merit, especially on this group. Besides of that this code is irrelevant to the original one and your further conclusions may not be perfectly correct. Please learn first about the topic of your benchmark and different variants of wavelet transform, namely difference between lifting scheme and dwt, and try posting some relevant examples or use other topic for your benchmarks. Neglecting this issues, I wonder if it is equally easy to juggle arbitrary multidimensional arrays in a statically typed language and do operations on selected axis directly from the interactive interpreter like in the NumPy example from my other post - http://groups.google.com/group/comp.lang.python/msg/a71a5bf00a88ad57 ? I don't know much OCaml so it would be great if you could elaborate on this. > , it is much faster: > > 0.56s C++ (direct arrays) > 0.61s F# (direct arrays) > 0.62s OCaml (direct arrays) > 1.38s OCaml (slices) > 2.38s Python (slices) > 10s Mathematica 5.1 > > Note that all implementations are safe (e.g. C++ uses a.at(i) instead of > a[i]). [...] So why not use C++ instead of all others if the speed really matters? What is your point here? Could you please share full benchmark code, so we could make conclusions too? I would like to get to know about your benchmark methodology. I wonder if you are allocating the input data really dynamically or whether it's size is a priori knowledge for the compiler. > In this specific context (discrete wavelet transform benchmark), I'd have > said that speed was the most important thing after correctness. In this very specific context: Yes, if you are targeting specific one-shot issue like JPEG2000 encoder, where you are using only 2 types of wavelets. In that case you would probably draw back to low-level C or C++ and use a good optimizing compiler for a specific hardware. Not necessarily, if you are doing research with different kinds of wavelets and need a general, flexible and easily adaptable tool or just the computation speed is not considered a bottleneck. Language speed is a great advantage, but if it always was the most important, people would talk directly to the CPUs or knit DSP chips in theirs backyards whenever they need to solve a calculation problem. Please don't make this discussion heading towards `what is the fastest way of doing d4 transform and why OCaml rules` instead of `what is the optimal way of doing things under given circumstances and still have a free afternoon ;-)`. Different tasks need different, well-balanced measures. Neither Python nor OCalm nor any other language is a panacea for every single problem. cheers, fw -- http://mail.python.org/mailman/listinfo/python-list
Re: Why not just show the out-of-range index?
On Mon, 2006-12-04 at 01:04 -0800, Russ wrote: > Robert Kern wrote: > > > Nothing is going to happen until you do one of these two things. Being more > > rude > > (and yes, you are being incredibly rude and insulting) won't move things > > along. > > I re-read the thread, and I don't see anywhere where I was rude Please allow me to break it down for you: Your first reply on this thread, or second message, said: """ Now, that [submitting a patch that fixes the problem] would be rather silly. I would have to familiarize myself with the code for the Python interpreter, then send a patch to the maintainers (and hope they notice it in their inboxes), while the maintainers themselves could probably "fix" the problem in two minutes flat. No thanks! My suggestion is trivial to implement and would benefit every Python programmer (even if only slightly), so I don't think it is too much to ask for. """ You may not have meant this to be rude, but it does come off as rude and arrogant, and I'll explain to you why: In your first post you stated that the feature seems like a no-brainer to you. That implies to the reader that you might have the necessary skill to implement the feature yourself, hence Robert's suggestion to submit a patch was, in the context you gave yourself, neither unreasonable nor silly. I can see how your calling a reasonable suggestion by a valuable community member "silly" would be construed as rude and arrogant. Hope this helps, Carsten. -- http://mail.python.org/mailman/listinfo/python-list
Re: Pimping the 'cgi' module
robert <[EMAIL PROTECTED]> writes: > Harry George wrote: > > When I came from Perl, I too missed perl-isms and specifically CGI.pm, so > > wrote my own: > > http://www.seanet.com/~hgg9140/comp/index.html > > http://www.seanet.com/~hgg9140/comp/pyperlish/doc/manual.html > > http://www.seanet.com/~hgg9140/comp/cgipm/doc/index.html > > Others on this newsgroup said I'd be better off just doing it in raw > > python. After a while, I realized that was true. You do > > triple-quoted templates with normal python idioms. Throw in > > some persistence mechanisms to deal with maintaining state across > > transactions, and you are in business. > > Since then I've looked at Zope, Plone, TurboGears, Django, and (for > > standalone apps) Dabo. TurboGears is mostly a set of recommendations > > on what 3rd party packages to use, with a wee bit of glueware. So far > > nothing feels as simple as just doing it in python. > > > Thats the fragmented journey, almost any web programmer has to go when coming > to python. A clear standard, even a clear intro, for simple tasks, like > doing state mng, db, error handling, etc. is not there on an easy path. > > For a level above cgi, what do you think about cherrypy ? > http://docs.cherrypy.org/ > > Robert I have only done "hello, world" stuff in cherrypy. We do everything from apache, so the server part of cherrypy wouldn't be needed, and getting to it from a mod_rewrite would just be extra hassle. Mostly we do model-view-controller, were the "view" may be batch, commandline, desktop gui, GUI, SOAP, etc. If it works with a simple coded-by-hand CGI, that's all we do. -- Harry George PLM Engineering Architecture -- http://mail.python.org/mailman/listinfo/python-list
Annoucement- pyljvim-0.0.3 Released.
pyljvim is a a Livejournal Plugin for Vim. One can post to the Livejournal directly from vim! :) It is available at: http://www.vim.org/scripts/script.php?script_id=1724 Installation is pretty easy and so is the usage. Thanks, Senthil http://phoe6.livejournal.com Contemptuous lights flashed across the computer's console. -- Hitchhiker's Guide to the Galaxy -- http://mail.python.org/mailman/listinfo/python-list
Re: WxPython
On 3 Dec 2006 04:14:08 -0800, Raja <[EMAIL PROTECTED]> wrote: > Hi, > I am trying to develop an application which would mainly do the > following 2 things . I would like to know how it can be achieved and > also the libraries needed for it . > > i) active window tracking > In this substate, the application records the title bar > contents of the active/foreground window > and how long, in seconds, that that window is active/in > the foreground. If the same window > remains in the foreground but the title bar changes (as > happens with a web browser application) then a new record is created > for each new window title. If a window title is recorded that > was previously recorded (on the same date -- see "Data > Structures" info in section 4.4), > then the time should be added to the previously recorded > active time for that window title. > -- Example -- >1) User clicks "Start" -> app enters "recording" state. >2) User opens window titled "Window 1" -> app looks for > any prior records for "Window 1" > on current date. Finding none, it creates a new > record. >3) User opens another window titled "Window 2" -> app > records total time spent in "Window 1", then looks for any prior > records for "Window 2" on current date. Finding none, >it creates a new record. >4) User re-raises/re-activates previous window "Window > 1" -> app records total time spent > in "Window 2", then looks for any prior records for > "Window 1" on current date. It finds >the record created earlier, so no new record is > created. >5) User clicks "Stop" (or "Exit") -> the app adds the > time just spent in "Window 1" to the > previously recorded time spent in "Window 1". App > then returns to "ready" state. > ii) idle > In this substate, the app has detected that the computer's > screensaver is active and no time > will be recorded for the active/foreground window. This > substate is entered automatically > (from the active window tracking state) when the > screensaver activates and exited > automatically (returning to the active window tracking > state) when the screensaver is > deactivated. Note that this substate should only be > entered if the app was in the active > window tracking state when the screensaver activated. > > > Awaiting Your Reply, > Thank You , > Raja. > wxPython is a toolkit for writing interfaces, and most of the functionality you want are systems tasks. wxPython can provide the UI, but for the system calls you'll need to use the pywin32 module or ctypes to work directly with the win32 api. -- http://mail.python.org/mailman/listinfo/python-list
Re: About alternatives to Matlab
Filip Wasilewski wrote: > So why not use C++ instead of all others if the speed really matters? > What is your point here? If speed matters, one should consider using hand-coded assembly. Nothing really beats that. But it's painful and not portable. So lets forget about that for a moment. Contrary to what most computer scientists think, C++ is not the tool of choice if speed really matters. Numeric computing is typically done in Fortran 90/95. That is not without reason. There are aspects of the C++ language that makes certain numerical optimizations impossible, e.g. the potential for pointer aliasing within tight loops, which hampers register allocation. For example: for(i=0; ihttp://latticeqcd.blogspot.com/2006/11/why-we-use-fortran-and-python.html -- http://mail.python.org/mailman/listinfo/python-list
Re: Parsing data from pyserial
On 2006-12-04, John Machin <[EMAIL PROTECTED]> wrote: > Try reading previous posts. The OP reported that to be returned from > the cam, based on print forty_bytes, not print repr(forty_bytes). I > think everybody (including possibly even the OP) is willing to believe > that the cam is *generating* correct parseable stuff, followed by '\r' > -- the problem now is how to get as many samples per second as is > reasonable in the face of problems like lack of buffering, What lack of buffering? -- Grant Edwards grante Yow! RELATIVES!! at visi.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Parsing data from pyserial, an (inefficient) solution
On 2006-12-04, Giovanni Bajo <[EMAIL PROTECTED]> wrote: [...] >> This should result in complete packets (from the "M" to a "\r") > > Oh well. readline(eol="\r") will do that much better. Yup. Using readline() has been suggested several times. It sure seems like the obvious solution to me as well. > while 1: > data = ser.readline(eol="\r") > args = data.split() > if args[0] == "M": > # command M; do something with args[1:] > elif args[0] == "KK": > # command KK; do something with args[1:] > [.. process other commands ..] > else: > # Invalid command: might be an incomplete > # packet. Just ignore it. > pass -- Grant Edwards grante Yow! Hmmm... A hash-singer at and a cross-eyed guy were visi.comSLEEPING on a deserted island, when... -- http://mail.python.org/mailman/listinfo/python-list
Printing unix Line endings from Windows.
Hi all, I've got a problem here which has me stumped. I've got a python script which does some text processing on some files and writes it back out to the same file using the fileinput module with inplace set to True. The script needs to run from Windows, but the files need to be written with Unix line endings. Is there any way of doing this without having to post-process the file in binary mode (a-la the crlf.py script) Cheers, -- http://mail.python.org/mailman/listinfo/python-list
Re: rdf, xmp
Imbaud Pierre wrote: > I have to add access to some XMP data to an existing python > application. > XMP is built on RDF, I'm just looking at the XMP Spec from the Adobe SDK. First impressions only, as I don't have time to read the whole thing in detail. This spec doesn't inspire me with confidence as to its accuracy and consistency. I think I've already seen some obscure conditions where developers will be unable to unambiguously interpret the spec. Compared to MPEG-7 however, at least it's not 700 pages long! The spec does state that property values can be structured, which is one of the best reasons to start using RDF for storing metadata. However I think actual use of these would be minimal in "typical" XML applicaations. At worst it's a simple data typing exercise of a two-valued tuple for "dimensions", rather than separate height and width properties. These are no problem to process. In particular, the XMP data model is a single-rooted tree, i.e. there is an external model of "a resource" (i.e. one image file) and an XMP document only addresses a single "resource" at a time. A major restriction in XMP is that it has no concept of shared resources between properties (and it can't, as there's no rdf:ID or rdf:about allowed). This is always hard to process, but it's also very valuable for doing metadata. Imagine a series of wildlife images that all refer to a particular safari, national park and species. We might be able to share a species reference between images easily enough by referring to a well-known public vocabulary, but it would also be useful (and concise) to be able to define one "expedition" in a subject property on one image, then share that same resource to others. As it is, we'd have to duplicate the full definition. Even in XMP's "separate document for each image resource" model we still might wish to do something similar, such as both photographer and director being the same person. When you start having 20MB+ of metadata per video resource (been there, done that!) then this sort of duplication is a huge problem. Not just because of the data volume, but because we need to identify that referenced resources are identical, not merely havingg the same in their property values (i.e. I'm the same John Smith, not just two people with the same name). There is no visible documentation of vocabularies, inetrnal or external. Some pre-defined schemas are given that define property sets, but there's nothing on the values of these, or how to describe that values are being taken from a particular external vocabulary (you can do this with RDF, but they don't describe it). This isn't widely seen as important, except by people who've already been through large media annotation projects. It's RDF-like, not just XML. However it's also a subset of RDF - in particular rdf:about isn't supported, which removes many of the graph structure constructs that make RDF such a pain to process with the basic XML tools. Read their explicit not on which RDF features aren't supported -- they're enough to make XMP easily processable with XSLT. The notes on embedding of XMP in XML and XML in XMP are both simplistic and ugly. I still don't see much _point_ in XMP. I could achieve all this much with two cups of coffee, RDF and Dublin Core and a whiteboard pen. Publishing metadata is good, publishing new _ways_ of publishing metadata is very bad! Overall, it could be far better, it could be better without being more complicated, and it's at least 5 years behind industry best practice for fields like museums and libraries. It's also a field that's still so alien to media and creative industries that the poor description and support of XMP will cause them to invent many bad architectures and data models for a few years to come. -- http://mail.python.org/mailman/listinfo/python-list
Re: Why not just show the out-of-range index?
I think your biggest initial recoil to the response you got was in the request that you submit a patch. You thought, "Geez, I just want one friggin' error message changed, and they want me to learn the whole Python development environment." Given your newbiness with Python, probably a better response to you would be, "Submit this as a feature request at the SF tracker page. If you really feel ambitious, put together a patch to go with it, it will increase the likelihood of getting accepted about 50X." A couple of other notes: - The core developers do post here, but the real core Python development discussions go on on the pydev mailing list. - Please recognize that you did get at least one response from John Machin, who scanned the code for this simple error message, and found that the impact was actually in about a dozen places (not uncommon when peeling away at the onion of source code, you've probably seen this yourself). This gave all of us a better appreciation of the size of the effort required for what initially seemed like a 30-second job. (BTW, there are *never* any 30-second jobs, especially in a package the size of Python.) So let me echo the effbot and ask that you submit this at the feature request tracker page on SF - I think you've spent more time in posting to this thread than it would have taken to submit this request. If you don't want to learn the Python dev environment, that's fine, you might consider composing a pydev mailing list submission making your case on the merits of implementing some user-friendliness features, such as more explanatory error messages. But the plain truth is, patches speak louder than words, on pydev even moreso than c.l.py. -- Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Execution time of lines within a function
Thanks Neil, I looked at that, but maybe I don't understand the output. I was hoping to see the cummulative time for the function and then the time associated with each statement (line) within the function. In the hotshot output below, I can see the function being called 100 times, which is correct, but the rest seems at too low a level for me to understand which statements are causing the slow execution. Any suggestions? hw6r3.py:276(main) hw6r3.py:73(findw)(100) 26700.865 hw6r3.py:126(findphi)(100) 6153.585 hw6r3.py:173(findu)(100) 1823.852 hw6r3.py:197(findv)(100) 2392.977 numeric.py:31(zeros_like)(3) 0.072 numeric.py:286(array_str)(1) 0.677 rpc.py:545(__getattr__)(13) 0.197 rpc.py:589(__call__)(12) 51.334 rpc.py:319(putmessage) :1(fileno)(12)0.039 rpc.py:149(debug)(12)0.126 rpc.py:236(asyncreturn) rpc.py:149(debug)(24)0.126 rpc.py:242(decoderesponse)(12) 0.015 rpc.py:277(getresponse)(12) 48.166 Regards, Frank Neil Cerutti wrote: > On 2006-12-04, monkeyboy <[EMAIL PROTECTED]> wrote: > > I have a function that hotshot says is very slow. I can get the > > aggregate execution time, but is there a way to get the > > execution time of each line so I can find the bottleneck? > > Try 'print_callees' on the stats object for your bottleneck. That > may help. > > -- > Neil Cerutti -- http://mail.python.org/mailman/listinfo/python-list
Factory pattern implementation in Python
Hi, I need to parse a binary file produced by an embedded system, whose content consists in a set of events laid-out like this: ... Every "event" is a single byte in size, and it indicates how long is the associated "data". Thus, to parse all events in the file, I need to take it like a stream and read one event at a time, consuming bytes according to the event value, and jumping to the next event, until an EOF is reached. Since there are dozens of almost completely heterogeneous events and each one of them may imply different actions on the program parsing the file, I thought it would be convenient to have one class encapsulating the logic for every event. The parser would then sit in a loop, creating objects of different classes and calling a method (say "execute"). That method (different in every class) is responsible for consuming the bytes associated with the event. Hence, as the class the parser needs to instantiate in each iteration is not known in advance, a factory should be implemented. Somehow the factory should know how to map an event to a class. I don't know of the best way I should do that in Python. I made an attempt along the following lines: 1. Create a base class for the events; 2. For every descendant class declare (in the class body) a public attribute "eventNum" and assign it the value of the event it will be responsible for; 3. At runtime, the factory constructor scans the event class hierarchy and builds a dictionary mapping "eventNum"'s to classes. A draft of the implementation follows: # # # class EvtBase: def __init__(self, file): self.file = file def execute(self): pass class Evt1(EvtBase): eventNum = 1 def execute(self): ... class Evt2(EvtBase): eventNum = 2 def execute(self): ... ... class EvtN(EvtBase): eventNum = N def execute(self): ... # # import inspect import events class Factory: def __isValidEventClass(self, obj): if inspect.isclass(obj) and obj != events.EvtBase and \ events.EvtBase in inspect.getmro(obj): for m in inspect.getmembers(obj): if m[0] == 'eventNum': return True return False def __init__(self): self.__eventDict = {} for m in inspect.getmembers(events, self.__isValidEventClass): cls = m[1] self.__eventDict.update({cls.eventNum: cls}) def parseEvents(self, file): while not file.eof(): ev = file.read(1) self.__eventDict[ev](file).execute() # I'm using the inspect module to find the event classes. One drawback of this approach is the need to keep the event classes in a module different from that of the factory, because the getmembers method expects an already parsed object or module. (The advantage is keeping the event number near the class declaration.) I've already had to make the solution generic and I found it was not straightforward to separate the common logic while avoiding the need to keep the factory and the events in two distinct modules. Is there anything better I can do? I don't have enough experience with Python, then I don't know whether it offers a more obvious way to address my problem. Thanks in advance. -- Romulo A. Ceccon 'romulo%s\x40yahoo.com.br' % 'ceccon' -- http://mail.python.org/mailman/listinfo/python-list
Re: Why not just show the out-of-range index?
Carsten Haese wrote: > On Mon, 2006-12-04 at 01:04 -0800, Russ wrote: > > Robert Kern wrote: > > > > > Nothing is going to happen until you do one of these two things. Being > > > more rude > > > (and yes, you are being incredibly rude and insulting) won't move things > > > along. > > > > I re-read the thread, and I don't see anywhere where I was rude > > Please allow me to break it down for you: > > Your first reply on this thread, or second message, said: > > """ > Now, that [submitting a patch that fixes the problem] would be rather > silly. I would have to familiarize myself > with the code for the Python interpreter, then send a patch to the > maintainers (and hope they notice it in their inboxes), while the > maintainers themselves could probably "fix" the problem in two minutes > flat. No thanks! > > My suggestion is trivial to implement and would benefit every Python > programmer (even if only slightly), so I don't think it is too much to > ask for. > """ > > You may not have meant this to be rude, but it does come off as rude and > arrogant, and I'll explain to you why: In your first post you stated > that the feature seems like a no-brainer to you. That implies to the > reader that you might have the necessary skill to implement the feature > yourself, hence Robert's suggestion to submit a patch was, in the > context you gave yourself, neither unreasonable nor silly. I can see how > your calling a reasonable suggestion by a valuable community member > "silly" would be construed as rude and arrogant. Thanks for explaining why the OP was rude. Having been reading and listening to english for only a few decades probably, I am sure the OP (and me too!) appreciates your explanation of rudeness. It was really hard for me to see it until you explained it so well. The great thing about c.l.p. is how much one learns about non-Python things here. (oops, I hope I wasn't rude by saying there were non-Python things? I didn't mean to diminish Python in any way.) Russ, Please rememer that learning Python is not done overnight -- there are many different levels of knowlage and only the most elite Pythonists have reached True Understanding. Since there are many things you don't understand, it is best you (and me too!) do not make suggrestions publically. Infidels could read them and inplying that Python is not perfect and you will undermine the spritual growth of many other newbies.. Such dangerous sugggestions should be made privately at the alter of Sourceforge, with a lot of deep self-reflection and piety. Until you achive greater understanding it is best if in public you make sure that you write with the following in mind: Python is perfect Perl sucks Static typing sucks Python is faster than C Quoting frequently from the holy Zen of Python is also helpful. Please remember that many regulars here are members of the holy priesthood because they have spent many years studying the Python scriptures. Be as circumspect in addressing them as you would be a medival knight or Japanese samurai. Only by following their guidance with complete devoutness and faith will you be able to achive the deepest level of Python appreciation. Hope this helps. -- http://mail.python.org/mailman/listinfo/python-list
Re: Inheritance doesn't work
zefciu wrote: > class MandelbrotImage (Image): > pass > I am getting the following error: > File "mandelimage.py", line 3, in ? > class MandelImage (Image): How do you get that error with that code? -- http://mail.python.org/mailman/listinfo/python-list
Re: Inheritance doesn't work
John Salerno wrote: > How do you get that error with that code? $ python >>> import os >>> class foo(os): ... pass ... Traceback (most recent call last): File "", line 1, in TypeError: Error when calling the metaclass bases module.__init__() takes at most 2 arguments (3 given) -- http://mail.python.org/mailman/listinfo/python-list
Re: Using win32gui.SendMessage and SysListView32 control
Thanks for your help. I will check them out. -- http://mail.python.org/mailman/listinfo/python-list
python Noob - basic setup question / problem
Running SUSE 10.1 on an AMD64. When I try and run a python program I get the following error: /usr/bin/python2: bad interpreter: No such file or directory "which python" gives me "/usr/local/bin/python" "which python2.4" gives me "/usr/local/bin/python2.4" But /usr/bin/python is symlinked to python2.4 "python -> python2.4" "which python2" and nothing comes up. Basically I have no idea what's going on... help please! Thanks, SETH -- http://mail.python.org/mailman/listinfo/python-list
Ensure a variable is divisible by 4
I am sure this is a basic math issue, but is there a better way to ensure an int variable is divisible by 4 than by doing the following; x = 111 x = (x /4) * 4 Just seems a bit clunky to me. -- http://mail.python.org/mailman/listinfo/python-list
Re: Factory pattern implementation in Python
[EMAIL PROTECTED] wrote: > Hi, > > I need to parse a binary file produced by an embedded system, whose > content consists in a set of events laid-out like this: > > ... > > Every "event" is a single byte in size, and it indicates how long is > the associated "data". Thus, to parse all events in the file, I need to > take it like a stream and read one event at a time, consuming bytes > according to the event value, and jumping to the next event, until an > EOF is reached. > > Since there are dozens of almost completely heterogeneous events and > each one of them may imply different actions on the program parsing the > file, I thought it would be convenient to have one class encapsulating > the logic for every event. The parser would then sit in a loop, > creating objects of different classes and calling a method (say > "execute"). That method (different in every class) is responsible for > consuming the bytes associated with the event. > > Hence, as the class the parser needs to instantiate in each iteration > is not known in advance, a factory should be implemented. Somehow the > factory should know how to map an event to a class. I don't know of the > best way I should do that in Python. I made an attempt along the > following lines: > > 1. Create a base class for the events; > 2. For every descendant class declare (in the class body) a public > attribute "eventNum" and assign it the value of the event it will be > responsible for; > 3. At runtime, the factory constructor scans the event class hierarchy > and builds a dictionary mapping "eventNum"'s to classes. > > A draft of the implementation follows: > > # > > # # > > class EvtBase: > def __init__(self, file): > self.file = file > > def execute(self): > pass > > class Evt1(EvtBase): > eventNum = 1 > def execute(self): > ... > > class Evt2(EvtBase): > eventNum = 2 > def execute(self): > ... > > ... > > class EvtN(EvtBase): > eventNum = N > def execute(self): > ... > > > # # > > import inspect > import events > > class Factory: > def __isValidEventClass(self, obj): > if inspect.isclass(obj) and obj != events.EvtBase and \ > events.EvtBase in inspect.getmro(obj): > for m in inspect.getmembers(obj): > if m[0] == 'eventNum': > return True > return False > > def __init__(self): > self.__eventDict = {} > for m in inspect.getmembers(events, self.__isValidEventClass): > cls = m[1] > self.__eventDict.update({cls.eventNum: cls}) > > def parseEvents(self, file): > while not file.eof(): > ev = file.read(1) > self.__eventDict[ev](file).execute() > > # > > I'm using the inspect module to find the event classes. One drawback of > this approach is the need to keep the event classes in a module > different from that of the factory, because the getmembers method > expects an already parsed object or module. (The advantage is keeping > the event number near the class declaration.) I've already had to make > the solution generic and I found it was not straightforward to separate > the common logic while avoiding the need to keep the factory and the > events in two distinct modules. > > Is there anything better I can do? I don't have enough experience with > Python, then I don't know whether it offers a more obvious way to > address my problem. > > Thanks in advance. If you actually intend to 1) name your Event subclasses Evt1, Evt2, ... EvtN and not give more descriptive (but unrelated to the magic event number) names, and 2) put them all in one module (events.py), you can avoid the code duplication of putting the event number both in the class name and as a class attribute. Your dispatcher could then be as simple as: import events def parseEvents(file): while not file.eof(): ev = int(file.read(1)) cls = getattr(events, 'Evt%d' % ev) cls(file).execute() By the way, it is not clear from your description if the event number equals to the size of the associated data. If it is, you can factor out the data extraction part in the factory function and pass just the extracted data in the Event constructor instead of the file: def parseEvents(file): while not file.eof(): ev = int(file.read(1)) cls = getattr(events, 'Evt%d' % ev) cls(file.read(ev)).execute() George -- http://mail.python.org/mailman/listinfo/python-list
Re: Why not just show the out-of-range index?
On Mon, 2006-12-04 at 08:49 -0800, [EMAIL PROTECTED] wrote: > Carsten Haese wrote: > > On Mon, 2006-12-04 at 01:04 -0800, Russ wrote: > > > Robert Kern wrote: > > > > > > > Nothing is going to happen until you do one of these two things. Being > > > > more rude > > > > (and yes, you are being incredibly rude and insulting) won't move > > > > things along. > > > > > > I re-read the thread, and I don't see anywhere where I was rude > > > > Please allow me to break it down for you: > > > > Your first reply on this thread, or second message, said: > > > > """ > > Now, that [submitting a patch that fixes the problem] would be rather > > silly. I would have to familiarize myself > > with the code for the Python interpreter, then send a patch to the > > maintainers (and hope they notice it in their inboxes), while the > > maintainers themselves could probably "fix" the problem in two minutes > > flat. No thanks! > > > > My suggestion is trivial to implement and would benefit every Python > > programmer (even if only slightly), so I don't think it is too much to > > ask for. > > """ > > > > You may not have meant this to be rude, but it does come off as rude and > > arrogant, and I'll explain to you why: In your first post you stated > > that the feature seems like a no-brainer to you. That implies to the > > reader that you might have the necessary skill to implement the feature > > yourself, hence Robert's suggestion to submit a patch was, in the > > context you gave yourself, neither unreasonable nor silly. I can see how > > your calling a reasonable suggestion by a valuable community member > > "silly" would be construed as rude and arrogant. > > Thanks for explaining why the OP was rude. Having been > reading and listening to english for only a few decades > probably, I am sure the OP (and me too!) appreciates your > explanation of rudeness. It was really hard for me to see it > until you explained it so well. The great thing about c.l.p. is > how much one learns about non-Python things here. > (oops, I hope I wasn't rude by saying there were non-Python > things? I didn't mean to diminish Python in any way.) > > Russ, > Please rememer that learning Python is not done overnight -- > there are many different levels of knowlage and only the > most elite Pythonists have reached True Understanding. > > Since there are many things you don't understand, it is > best you (and me too!) do not make suggrestions publically. > Infidels could read them and inplying that Python is not > perfect and you will undermine the spritual growth of > many other newbies.. Such dangerous sugggestions > should be made privately at the alter of Sourceforge, with > a lot of deep self-reflection and piety. > > Until you achive greater understanding it is best if in public > you make sure that you write with the following in mind: > Python is perfect > Perl sucks > Static typing sucks > Python is faster than C > Quoting frequently from the holy Zen of Python is also > helpful. Please remember that many regulars here are > members of the holy priesthood because they have spent > many years studying the Python scriptures. Be as circumspect > in addressing them as you would be a medival knight or > Japanese samurai. Only by following their guidance with > complete devoutness and faith will you be able to achive > the deepest level of Python appreciation. > > Hope this helps. My sarcasm meter just exploded. -Carsten -- http://mail.python.org/mailman/listinfo/python-list
Re: Ensure a variable is divisible by 4
[EMAIL PROTECTED] schrieb: > I am sure this is a basic math issue, but is there a better way to > ensure an int variable is divisible by 4 than by doing the following; > > x = 111 > x = (x /4) * 4 > > Just seems a bit clunky to me. Division with rest: >>> x % 4 3 -- http://mail.python.org/mailman/listinfo/python-list
Re: Ensure a variable is divisible by 4
[EMAIL PROTECTED] wrote: > I am sure this is a basic math issue, but is there a better way to > ensure an int variable is divisible by 4 than by doing the following; > > x = 111 > x = (x /4) * 4 > > Just seems a bit clunky to me. > Use modulo operator '%' if not x % 4: # # Arrive here if x is modulo 4 divisable # -Larry Bates -- http://mail.python.org/mailman/listinfo/python-list
Re: Ensure a variable is divisible by 4
[EMAIL PROTECTED] wrote: > I am sure this is a basic math issue, but is there a better way to > ensure an int variable is divisible by 4 than by doing the following; > > x = 111 > x = (x /4) * 4 > > Just seems a bit clunky to me. if x % 4 == 0: # x is divisible by 4 George -- http://mail.python.org/mailman/listinfo/python-list
Re: python Noob - basic setup question / problem
Lilavivat a écrit : > Running SUSE 10.1 on an AMD64. When I try and run a python program I get > the following error: > > /usr/bin/python2: bad interpreter: No such file or directory > > "which python" gives me "/usr/local/bin/python" > > "which python2.4" gives me "/usr/local/bin/python2.4" > > But /usr/bin/python is symlinked to python2.4 "python -> python2.4" > > "which python2" and nothing comes up. > > Basically I have no idea what's going on... help please! > > Thanks, > SETH Fault of the Python program : it hardcodes that the Python interpreter is /usr/bin/python2 Check the first line of the executable ( I bet it is a simple text file so go away and edit it with emacs/vim/joe/ed ... ). It should be ( with maybe a few spaces here and there ) : #!/usr/bin/python2 replace it with : #!/usr/bin/python -- http://mail.python.org/mailman/listinfo/python-list
Best way for inter-process communication in Python
Hi everyone! Here's the current scenario: I have a program in Python that computes something very fast (<1s), but it takes a considerable amount of time to read the startup data (>90s). Since the startup data is pretty static, I want this program to be resident and ready in memory all the time. The client-side of this program is a function in PostgreSQL. For the sake of simplicity, let's assume it is another program in Python that will be asking the resident one for results on-demand. Let's also assume that there will be dozens of concurrent requests. My problem is: what is the fastest, easiest way to accomplish this inter-process communication? The data between them will be very small: 1Kb max per request. I've thought about SOAP, sockets and named pipes... But since I have no experience on any of them using Python, I can't decide which way is better... Just a few considerations: Python version is 2.4. PostgreSQL version is 8.2RC1, OS version is Windows Server 2003. Thanks in advance, Hugo Ferreira -- GPG Fingerprint: B0D7 1249 447D F5BB 22C5 5B9B 078C 2615 504B 7B85 -- http://mail.python.org/mailman/listinfo/python-list
Re: Printing unix Line endings from Windows.
Ant wrote: > Hi all, > > I've got a problem here which has me stumped. I've got a python script > which does some text processing on some files and writes it back out to > the same file using the fileinput module with inplace set to True. > > The script needs to run from Windows, but the files need to be written > with Unix line endings. > > Is there any way of doing this without having to post-process the file > in binary mode (a-la the crlf.py script) > > Cheers, > You can write to a new file and create your own line endings. When done, delete the original file and rename the output file. -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I print a numpy array?
On 2006-12-02, Robert Kern <[EMAIL PROTECTED]> wrote: > Beliavsky wrote: >> When I print an array in any language, I (and I think most programmers) >> expect by default to have all elements displayed. Matlab, R, and >> Fortran 95 have somewhat similar arrays to numpy, and that is what they >> do. I don't remember Numeric summarizing arrays by default. R has a >> "summary" function as well as a "print" function. > > There are pretty serious problems with interactive use and large arrays. > Formatting the string for a very large array can take a fair bit of time, > often > much more than the computation that generated it. This has been a > long-standing > frustration of many Numeric users. At the interactive prompt, if the statement > you just entered is taking a long time to execute and you Ctrl-C, odds are, > the > traceback points you right in the middle of array2string(), not anything in > the > actual computation itself. Since the interactive prompt prints things out > without the user explicitly asking for it, it's not enough simply to have two > functions available. > > numarray set the default to summarize, and numpy kept numarray's choice. I 100% approve of the summarization by default. It has saved me *many* times. Dave -- http://mail.python.org/mailman/listinfo/python-list
Re: About alternatives to Matlab
Jon Harrop wrote: [snip] > >> That's my point, using numpy encouraged the programmer to optimise in the > >> wrong direction in this case (to use slices instead of element-wise > >> operations). > > > > Ok, I can see that. We have a sort of JIT compiler, psyco, that works > > pretty well but I don't think it's as fast for large arrays as a good > > numpy solution. But it has more to deal with than a JIT for a > > statically typed language. > > Ok. Perhaps starting a Python JIT in something like MetaOCaml or Lisp/Scheme > would be a good student project? ...and finishing would be a good project for a well-funded team of experienced engineers. > >> Which begs the question, if you were writing in a compiled language like > >> F# would you ever use slices? > > > > If I was writing in F#? I absolutely would, because some problems are > > most cleanly, readably, and maintainably done with slices. I don't > > have any speed-lust, and I don't waste time making things fast if they > > don't need to be. I would rather spend my time designing and > > implementing the system, and optimizing things that actually need it. > > I don't want to spend my time tracking down some stupid indexing error. > > Ok. Can you name some problems that are solved more easily with slices than > with indexing? I may have just answered my own question by posting some > really concise pseudocode that uses slices. D4 transform? How about addition? How about the vast majority of cases where slicing is possible? Occasionally you have cases where slicing would work but be complicated, but in most cases, wherever slicing is feasible it's easier, less error-prone, less typing, more readable, more concise, more maintainable. > > Will any other F# people do it? I don't know if they all have > > speed-lust, or if they'd all deliberately avoid slicing to prove some > > kind of point about functional programming and/or non-machine-compiled > > languages, but I assume there'd be some who would do it for the same > > reasons I'd do it. > > My concern is that slices are being pulled into F# because they are popular > in languages like Python and Matlab but I've yet to see an example where > they are actually a good idea (in the context of F#, i.e. a compiled > language where indexing is as fast or faster). It's often a good idea where speed isn't crucial because it's easier, more readable, and more maintainable. I highly suspect F# and other languages would still using slicing for many problems for this reason. OTOH, it's rarely a good idea to always base coding decisions on speed to the exclusion of all other factors. > >> What makes numpy convenient? > > > > ...it scales up well... > > What do you mean? > > > ...it expresses mathematical concepts straightforwardly... > > It didn't express this mathematical concept very straightforwardly. I thought it did. One must know about the shared data nuances and the slicing syntax. Given that, the numpy way closely mimicked the way mathematical formulas look. Put it this way: which one of these two (numpy with slicing, Ocaml with indexing) would it be easer to reverse engineer a mathematical formula out of? I'd say the numpy version with slicing, by a long shot. > > And a lot of the time, you don't have to worry about indexing. > > Right. Ideally you want to factor that out without losing anything. Indeed, > if you do factor the C++ code you should get back to the underlying > mathematical definitions. Ideally, you'd want to write those directly and > have them executed efficiently. I am almost always happy to factor indexing out *with* losing something. > >> > No problem, numpy will be fast enough for my needs. > >> > >> Ok. But you'd rather have a compiler? > > > > Python *is* compiled, buddy. It has a VM that runs bytecode. > > I meant a native-code compiler, of course. > > > But, would I rather have a seperate compile to *machine code*, when an > > automatic compile to VM code is fast enough? > > > > Not remotely. Compilers are a PITA and I avoid them when it's > > possible. > > I can envisage a JIT Python compiler that would spot statically typed code, > compile it with no user intervention and then run it. I implemented such a > thing for Mathematica a few years ago. You can almost never spot "statically typed" code in Python reliably, even with a separate compile stage that does a global analysis. Even Lisp compilers, which are generally known to be the best compilers out there for a dynamically-typed language, don't do too well at this unless you help them out, and Lisp isn't nearly as dynamic as Python. As for JIT's, the best you could do is hook into a function, checking the types of its arguments, and cacheing optimized code for the given type signature. It's basically what psyco does. Anything more would require either help from the programmer or concessions in dynamicity. > >> Why not drop to C for this one function? > > > > Why would I? The assumptions clearl
Re: Ensure a variable is divisible by 4
> I am sure this is a basic math issue, but is there a better way to > ensure an int variable is divisible by 4 than by doing the following; > > x = 111 > x = (x /4) * 4 > > Just seems a bit clunky to me. You're right...you'll want to read up on the "modulo" operator: if x % 4 <> 0: print "Hey, x isn't divisible by 4" http://docs.python.org/lib/typesnumeric.html To do what you describe above, you can also use x = x - (x % 4) which isn't greatly better in the clunkiness department. In both cases, non-divisible-by-4 numbers get bumped down (to the "left" on the number line) in the event that it's not divisible by 4. -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: Factory pattern implementation in Python
On 4 Dec 2006 08:39:17 -0800, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > Hi, > > I need to parse a binary file produced by an embedded system, whose > content consists in a set of events laid-out like this: > > ... > > Every "event" is a single byte in size, and it indicates how long is > the associated "data". Thus, to parse all events in the file, I need to > take it like a stream and read one event at a time, consuming bytes > according to the event value, and jumping to the next event, until an > EOF is reached. > > Since there are dozens of almost completely heterogeneous events and > each one of them may imply different actions on the program parsing the > file, I thought it would be convenient to have one class encapsulating > the logic for every event. The parser would then sit in a loop, > creating objects of different classes and calling a method (say > "execute"). That method (different in every class) is responsible for > consuming the bytes associated with the event. > > Hence, as the class the parser needs to instantiate in each iteration > is not known in advance, a factory should be implemented. Somehow the > factory should know how to map an event to a class. I don't know of the > best way I should do that in Python. I made an attempt along the > following lines: > > 1. Create a base class for the events; > 2. For every descendant class declare (in the class body) a public > attribute "eventNum" and assign it the value of the event it will be > responsible for; > 3. At runtime, the factory constructor scans the event class hierarchy > and builds a dictionary mapping "eventNum"'s to classes. > > A draft of the implementation follows: > > # > > # # > > class EvtBase: > def __init__(self, file): > self.file = file > > def execute(self): > pass > > class Evt1(EvtBase): > eventNum = 1 > def execute(self): > ... > > class Evt2(EvtBase): > eventNum = 2 > def execute(self): > ... > > ... > > class EvtN(EvtBase): > eventNum = N > def execute(self): > ... > > > # # > > import inspect > import events > > class Factory: > def __isValidEventClass(self, obj): > if inspect.isclass(obj) and obj != events.EvtBase and \ > events.EvtBase in inspect.getmro(obj): > for m in inspect.getmembers(obj): > if m[0] == 'eventNum': > return True > return False > > def __init__(self): > self.__eventDict = {} > for m in inspect.getmembers(events, self.__isValidEventClass): > cls = m[1] > self.__eventDict.update({cls.eventNum: cls}) > > def parseEvents(self, file): > while not file.eof(): > ev = file.read(1) > self.__eventDict[ev](file).execute() > > # > > I'm using the inspect module to find the event classes. One drawback of > this approach is the need to keep the event classes in a module > different from that of the factory, because the getmembers method > expects an already parsed object or module. (The advantage is keeping > the event number near the class declaration.) I've already had to make > the solution generic and I found it was not straightforward to separate > the common logic while avoiding the need to keep the factory and the > events in two distinct modules. > > Is there anything better I can do? I don't have enough experience with > Python, then I don't know whether it offers a more obvious way to > address my problem. > I'd have the classes register themselves rather than trying to find them. This removes the need to have a common base class (preserves duck typing) and lets everything communicate via the factory module. #in module Factory.py EventMap = {} #in module events.py import Factory class EventHandler: Factory.EventMap[1] = EventHandler #in module parser.py import Factory handler = Factory.EventMap[event]() handler.handleEvent(data) There's probably some way to wrap the registration up in a metaclass so it's handled implicitly, but I prefer the explicit approach. > Thanks in advance. > > -- > Romulo A. Ceccon > 'romulo%s\x40yahoo.com.br' % 'ceccon' > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: Ensure a variable is divisible by 4
[EMAIL PROTECTED] wrote: > I am sure this is a basic math issue, but is there a better way to > ensure an int variable is divisible by 4 than by doing the following; > > x = 111 > x = (x /4) * 4 > > Just seems a bit clunky to me. > Depends what you mean by 'make it divisable'. Do you want to check it is divisible or do you want to make it divisible? And if you want to make it divisible do you want to go to the next multiple of 4, or the previous? Will McGugan -- http://www.willmcgugan.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Factory pattern implementation in Python
George Sakkis wrote: > If you actually intend to > 1) name your Event subclasses Evt1, Evt2, ... EvtN and not give more > descriptive (but unrelated to the magic event number) names No, those names are just an example. The actual classes have descriptive names. > By the way, it is not clear from your description if the event number > equals to the size of the associated data. I'm sorry, George. The event number has nothing to do with the size of the associated data. I meant the program has a way to discover the size from the event number. -- Romulo A. Ceccon 'romulo%s\x40yahoo.com.br' % 'ceccon' -- http://mail.python.org/mailman/listinfo/python-list
Re: Why not just show the out-of-range index?
Russ schrieb: > I love Python, but every time I get an out-of-range error message, I > wonder why it didn't just tell me what the out-of-range index was and > what the allowable range was. Certainly that information must be > available to the exception handler, or how would it know that it is out > of range? Yes, that is true. The information is readily available. It's not true that it is "trivial" to fix, though: for every fix, there ought to be a new test case also, and you have to run the test suite. Depending on how fast a developer is, it may take between 30min and 1hour to get a fix implemented (for the list case alone, not counting all the other sequences). Even though I could fix it, I don't feel tempted to do so: I never had this problem; in most cases of IndexError, it was very clear what the problem was so I didn't need the additional information. Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: Inheritance doesn't work
Fredrik Lundh wrote: > John Salerno wrote: > >> How do you get that error with that code? > > $ python > import os class foo(os): > pass > > Traceback (most recent call last): > File "", line 1, in > TypeError: Error when calling the metaclass bases > module.__init__() takes at most 2 arguments (3 given) > > > Sure, but I think the question was more about how code that references "MandelbrotImage could yield a stack that references MandelImage. -- http://mail.python.org/mailman/listinfo/python-list
Re: Why not just show the out-of-range index?
Carsten Haese wrote: > You may not have meant this to be rude, but it does come off as rude and > arrogant, and I'll explain to you why: In your first post you stated > that the feature seems like a no-brainer to you. That implies to the > reader that you might have the necessary skill to implement the feature > yourself, hence Robert's suggestion to submit a patch was, in the > context you gave yourself, neither unreasonable nor silly. I can see how > your calling a reasonable suggestion by a valuable community member > "silly" would be construed as rude and arrogant. > > Hope this helps, OK, fair enough. I shouldn't have called his suggestion "silly." When I replied to him I honestly thought it was, but in retrospect I now see that it wasn't. My mistake. By the way, I consider myself a pretty good Python programmer, but I haven't used C in many years, and I have no desire to ever use it -- or even see it -- again. That's one of the reasons I use Python in the first place. (I am fortunate enough to get to choose the language I use.) I think it's unfortunate that Python is written in C, but I won't get into that now. (And yes, I am aware of Jython, but I don't care much for Java either.) -- http://mail.python.org/mailman/listinfo/python-list
Re: Why not just show the out-of-range index?
Russ schrieb: > My suggestion that it would be much easier for the Python maintainers > than for me to implement the requested feature is just basic common > sense. I would have to spend many hours or days just to familiarize > myself with the code, but they are obviously already very familiar with > it. That is all true. However, you seem to be implying that therefore, it is the Python maintainers who ought to fix this. That implication is faulty. Not everything that somebody could do better than you should be done by that other person - some things you have to do yourself if you want to see them done. All Python contributors (including the maintainers) are volunteers, none of us is paid. Volunteers tend to do what they have fun doing or what scratches their own itches. This is just how free software works. > And they would probably have to spend nearly as much time checking > my patch as they would writing it themselves anyway. No: if you already have done the testing, and provided test cases to test it, this is fairly easy to review. Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: Best way for inter-process communication in Python
There is another option that I thought while writing this... I can use the database for data communication. Like having a table with both in and out parameters. On the client-side, I fill the in parameters columns. Then I signal the external application which reads the parameters, and write the output. Which raises me the following question... How do I signal a python application under windows? (Is it possible to send something like a SIGHUP?) Cheers! On 12/4/06, Hugo Ferreira <[EMAIL PROTECTED]> wrote: > Hi everyone! > > Here's the current scenario: I have a program in Python that computes > something very fast (<1s), but it takes a considerable amount of time > to read the startup data (>90s). Since the startup data is pretty > static, I want this program to be resident and ready in memory all the > time. > > The client-side of this program is a function in PostgreSQL. For the > sake of simplicity, let's assume it is another program in Python that > will be asking the resident one for results on-demand. Let's also > assume that there will be dozens of concurrent requests. > > My problem is: what is the fastest, easiest way to accomplish this > inter-process communication? The data between them will be very small: > 1Kb max per request. I've thought about SOAP, sockets and named > pipes... But since I have no experience on any of them using Python, I > can't decide which way is better... > > Just a few considerations: Python version is 2.4. PostgreSQL version > is 8.2RC1, OS version is Windows Server 2003. > > Thanks in advance, > > Hugo Ferreira > > -- > GPG Fingerprint: B0D7 1249 447D F5BB 22C5 5B9B 078C 2615 504B 7B85 > -- GPG Fingerprint: B0D7 1249 447D F5BB 22C5 5B9B 078C 2615 504B 7B85 -- http://mail.python.org/mailman/listinfo/python-list
Re: Why not just show the out-of-range index?
[EMAIL PROTECTED] schrieb: > Thanks for explaining why the OP was rude. Having been > reading and listening to english for only a few decades > probably, I am sure the OP (and me too!) appreciates your > explanation of rudeness You mean, you don't feel insulted if somebody calls you silly? Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: Thread error
Tnx Dennis, this is my first python program, so I don't know every modules :( Anyway thank you so much for the suggestions, corrections and for the whole program :) Thank you -- http://mail.python.org/mailman/listinfo/python-list
SQLObject release 0.7.2
Hello! I'm pleased to announce the 0.7.2 release of SQLObject. What is SQLObject = SQLObject is an object-relational mapper. Your database tables are described as classes, and rows are instances of those classes. SQLObject is meant to be easy to use and quick to get started with. SQLObject supports a number of backends: MySQL, PostgreSQL, SQLite, and Firebird. It also has newly added support for Sybase, MSSQL and MaxDB (also known as SAPDB). Where is SQLObject == Site: http://sqlobject.org Mailing list: https://lists.sourceforge.net/mailman/listinfo/sqlobject-discuss Archives: http://news.gmane.org/gmane.comp.python.sqlobject Download: http://cheeseshop.python.org/pypi/SQLObject/0.7.2 News and changes: http://sqlobject.org/docs/News.html What's New == Features & Interface * sqlbuilder.Select now supports JOINs exactly like SQLObject.select. * destroySelf() removes the object from related joins. Bug Fixes - * Fixed a number of unicode-related problems with newer MySQLdb. * If the DB API driver returns timedelta instead of time (MySQLdb does this) it is converted to time; but if the timedelta has days an exception is raised. * Fixed a number of bugs in InheritableSQLObject related to foreign keys. * Fixed a bug in InheritableSQLObject related to the order of tableRegistry dictionary. * A bug fix that allows to use SQLObject with DateTime from Zope. Documentation Added --- * Added "How can I define my own intermediate table in my Many-to-Many relationship?" to FAQ. For a more complete list, please see the news: http://sqlobject.org/docs/News.html Oleg. -- Oleg Broytmannhttp://phd.pp.ru/[EMAIL PROTECTED] Programmers don't die, they just GOSUB without RETURN. -- http://mail.python.org/mailman/listinfo/python-list
Re: Execution time of lines within a function
On 2006-12-04, monkeyboy <[EMAIL PROTECTED]> wrote: > Thanks Neil, > > I looked at that, but maybe I don't understand the output. I > was hoping to see the cummulative time for the function and > then the time associated with each statement (line) within the > function. > > Any suggestions? I don't think the Python Profiler goes down to that level. The next step might be to analyze the function yourself and try to understand why it is so slow. Post the code here and let the readers pick it apart. > In the hotshot output below, I can see the function being > called 100 times, which is correct, but the rest seems at too > low a level for me to understand which statements are causing > the slow execution. > > hw6r3.py:276(main) hw6r3.py:73(findw)(100) 26700.865 Is this the print_callees output? -- Neil Cerutti -- http://mail.python.org/mailman/listinfo/python-list
decorators question
Hi, i am new to python and i have a question about how decorators are working. I have understand HOW they do their magic but i am trying to figure out WHEN they do it... I have the following simple example: #- def author(author_name): def decorator(func): func.author_name = author_name return func return decorator @author("some author") def F(): pass # print F.author_name #- I am using Eclipse/PyDev and when i run this snippet from the PyDev debugger, i see that even though i do not call F() (or reference F.author_name), the decorator and all this stuff is executed and updates F.autor_name variable. How is this thing really working ?? I mean, if we run this .py file (pythn test.py) from the command prompt, what the runtime will do, even if we do not have ane commands to execute, only functions as above ? It will load all the module, all the functions and when it sees that some function(s) are decorating, then it will start execute respectives decorators ? And this will do it for all decorated functions ?? Even if we do not have any references to these functions ? Shouldn't this code called when we actually DO call it ? Thanks a lot for any enlightment on this, objectref -- http://mail.python.org/mailman/listinfo/python-list
ISAPI filter
Hi all, I'm trying to write an ISAPI filter in Python, using the examples that come in the "isapi" directory of the win32com package. The installation program itself runs fine, but when I examine the properties of my web server, my filter has a big red down arrow next to it. But I can't seem to figure out where I should be looking to find the trouble. If anyone can point me to the right place (or see an obvious error in the code below), I'd appreciate it. -Chris from isapi import isapicon, threaded_extension from isapi.simple import SimpleFilter import sys import traceback import urllib ## class ImageProtectFilter(SimpleFilter): "Image Protection Filter" filter_flags = isapicon.SF_NOTIFY_AUTHENTICATION def HttpFilterProc(self, fc): return isapicon.SF_STATUS_REQ_HANDLED_NOTIFICATION # # The entry points for the ISAPI filter. def __FilterFactory__(): return ImageProtectFilter() if __name__=='__main__': # If run from the command-line, install ourselves. from isapi.install import * params = ISAPIParameters() # Setup all filters - these are global to the site. params.Filters = [ FilterParameters(Name="ImageProtectFilter", Description=ImageProtectFilter.__doc__), ] HandleCommandLine(params) -- http://mail.python.org/mailman/listinfo/python-list
Re: Execution time of lines within a function
The output was from print_callees(). It appears as though print_stats() and print_callees() return the same data, just in a different orangization. There is supposed to be a "lineevents=1" option in hotshot.Profile, for line timings, but it doesn't seem to work in Python 2.4. Thanks for your help Neil Cerutti wrote: > On 2006-12-04, monkeyboy <[EMAIL PROTECTED]> wrote: > > Thanks Neil, > > > > I looked at that, but maybe I don't understand the output. I > > was hoping to see the cummulative time for the function and > > then the time associated with each statement (line) within the > > function. > > > > Any suggestions? > > I don't think the Python Profiler goes down to that level. The > next step might be to analyze the function yourself and try to > understand why it is so slow. Post the code here and let the > readers pick it apart. > > > In the hotshot output below, I can see the function being > > called 100 times, which is correct, but the rest seems at too > > low a level for me to understand which statements are causing > > the slow execution. > > > > > > hw6r3.py:276(main) hw6r3.py:73(findw)(100) 26700.865 > > Is this the print_callees output? > > -- > Neil Cerutti -- http://mail.python.org/mailman/listinfo/python-list
Re: About alternatives to Matlab
Carl Banks wrote: > > Ok. Perhaps starting a Python JIT in something like MetaOCaml or Lisp/Scheme > > would be a good student project? > > ...and finishing would be a good project for a well-funded team of > experienced engineers. I think this is a good idea. We could use the AST from the CPython compiler, translate on the fly to ANSI Common Lisp, and pass it off to SBCL (which is very fast and supports native threads). It would even solve the issue of Python's crappy GIL and reference counting (as opposed to a modern garbage collector). Another option would be to use something like pyrex to compile Python on-the-fly to C, and then compile using GCC or MSVC. A third option would be to translate on the fly to Scheme, and compile using Bigloo. It would not be a JIT-compiler, but rather something like the Lisp solution where individual functions can be compiled when speed is important. It sounds like a fun project to me. -- http://mail.python.org/mailman/listinfo/python-list
Re: decorators question
king kikapu wrote: > It will load all the module, all the functions and when it sees that > some function(s) are decorating, then it will start execute respectives > decorators ? @decorator def func(): pass is *exactly* the same thing as: def func(): pass func = decorator(func) > And this will do it for all decorated functions ?? Even if we do not > have any references to these functions ? Python calls the decorator, not the decorated function. additional reading: http://www.python.org/doc/2.4.4/whatsnew/node6.html http://www.python.org/dev/peps/pep-0318 and the relevant chapters in the tutorial and the language reference. -- http://mail.python.org/mailman/listinfo/python-list
Re: Factory pattern implementation in Python
Romulo A. Ceccon wrote: > George Sakkis wrote: > > > If you actually intend to > > 1) name your Event subclasses Evt1, Evt2, ... EvtN and not give more > > descriptive (but unrelated to the magic event number) names > > No, those names are just an example. The actual classes have > descriptive names. Even then, I'd prefer a naming convention plus a global Event registry than relying on inspect, both for implementation and (mostly) documentation reasons. It's good if a human can browse through a list of a few dozen names and immediately know that CamelCasedNameEndingWithEvent is an Event subclass. It's also good to be able to find in one place the explicit mapping of magic numbers to classes rather than searching in the whole file (or worse, multiple files) for it. YMMV. George -- http://mail.python.org/mailman/listinfo/python-list
Python bindings for RCS apps
There is pySVN for subversion but does other revision control system systems have some good python bindings/apis ? with good docs and some examples. -- http://mail.python.org/mailman/listinfo/python-list
Re: Ensure a variable is divisible by 4
[EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > I am sure this is a basic math issue, but is there a better way to > ensure an int variable is divisible by 4 than by doing the following; > > x = 111 > x = (x /4) * 4 You should use // for future compatibility which is guaranteed to be an integer division whereas / isn't (see "from __future__ import division") Eg (x // 4) * 4 For the particular case of 4 being 2**2, you might consider x & ~0x3 which is a common idiom. If you want to round to the next largest 4 then add 3 first, eg for x in range(0,12): (x + 3) & ~0x3 Which prints 0,4,4,4,4,8,8,8,8,12... You could also consider the funky x>>2<<2 -- Nick Craig-Wood <[EMAIL PROTECTED]> -- http://www.craig-wood.com/nick -- http://mail.python.org/mailman/listinfo/python-list
Re: Why not just show the out-of-range index?
Russ wrote: > Every Python programmer gets this message occasionally: > > IndexError: list index out of range > > The message tells you where the error occurred, but it doesn't tell > you what the range and the offending index are. Why does it force > you to determine that information for yourself when it could save > you a step and just tell you? This seems like a "no-brainer" to me. > Am I missing something? I think the same could be said of virtually all exceptions. What I think would be ideal is that whenever an exception is raised, the traceback tells you: 1) What the exception is 2) The names of the variables involved in the offending expression (or their character position in the line) 3) The values of those variables This would be especially useful in cases where you have some long expression and you get a "cannot concatenate str and list" or whatever. The irritating thing about this as it is is that you cannot tell which variables in the expression are causing the problem. I realize that in some cases the offending expression may not be a single variable, but I am curious whether it would be possible for something like this: "1" + "2" + "3" + "4" + 5 + "6" To point to the actual addition that raises the exception (somewhat like it does for a syntax error), instead of just saying "there is an error somewhere in this line". -- --OKB (not okblacke) Brendan Barnwell "Do not follow where the path may lead. Go, instead, where there is no path, and leave a trail." --author unknown -- http://mail.python.org/mailman/listinfo/python-list
Re: Why not just show the out-of-range index?
Martin v. Löwis wrote: > [EMAIL PROTECTED] schrieb: > > Thanks for explaining why the OP was rude. Having been > > reading and listening to english for only a few decades > > probably, I am sure the OP (and me too!) appreciates your > > explanation of rudeness > > You mean, you don't feel insulted if somebody calls you > silly? This is a hypothetical question, right? Since the OP didn't call you or anyone else silly. O.P. wrote: > > Rather, they (like I) will encourage to OP to submit > > a patch that fixes the problem. > Now, that would be rather silly. I would have to familiarize > myself with the code for the Python interpreter, Seems to me he called the suggestion (made without any knowlage of the OP's abilities regarding C and Python's internals) that he summit a patch, silly. I aggree. His response was well within the bounds of normal usenet discourse. -- http://mail.python.org/mailman/listinfo/python-list
Re: Ensure a variable is divisible by 4
On 2006-12-04, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > I am sure this is a basic math issue, but is there a better > way to ensure an int variable is divisible by 4 if x & 3: print "not divisible by 4" x &= ~3 print "it is now: x = %d" If you want to round to nearest power of 4 rather than truncate: x = (x+2) & ~3 -- Grant Edwards grante Yow! An INK-LING? Sure -- at TAKE one!! Did you BUY any visi.comCOMMUNIST UNIFORMS?? -- http://mail.python.org/mailman/listinfo/python-list
Re: SQLObject release 0.7.2
Oracle? Robert -- http://mail.python.org/mailman/listinfo/python-list
Re: decorators question
> def func(): > pass > > is *exactly* the same thing as: > > def func(): > pass > func = decorator(func) Yes, i know that but i thought that it is so when I call the function, not when the runtime just loads the module... >Python calls the decorator, not the decorated function. Hmmm...ok...it calls the decorator but when ?? It (the runtime) loads the .py file and start to call every decorator it finds on it, regardless of the existance of code that actually calls the decorated functions ?? I understand thet Python does not call the decoratated functiond but it ends up this way... > > additional reading: > > http://www.python.org/doc/2.4.4/whatsnew/node6.html > http://www.python.org/dev/peps/pep-0318 > > and the relevant chapters in the tutorial and the language reference. > I will have a lokk also thera, thanks! > -- http://mail.python.org/mailman/listinfo/python-list
Re: decorators question
> Hmmm...ok...it calls the decorator but when ?? It (the runtime) loads > the .py file and start to call every decorator > it finds on it, regardless of the existance of code that actually calls > the decorated functions ?? > I understand thet Python does not call the decoratated functiond but it > ends up this way... Python simply executes the module body when you import a module. class and def statements result in binding of class and function objects to the corresponding names. It's really that simple. Try the following to get a deeper insight: # file foobar.py def bar(f): return 'some text' @def bar def foo(): print "foo" When you import this module module in an interactive python session you will get he following. >>> from foobar import * called foo >>> bar() # this will fail because bar is not a function Traceback (most recent call last): File "", line 1, in ? TypeError: 'str' object is not callable >>> bar 'some text' Hope that helps;) -- Soni Bergraj http://www.YouJoy.org/ -- http://mail.python.org/mailman/listinfo/python-list
Re: decorators question
king kikapu wrote: > Hmmm...ok...it calls the decorator but when ?? It (the runtime) loads > the .py file and start to call every decorator you seem to be missing that the interpreter *always* executes the code in a module to find out what it contains. "def" and "class" are exe- cutable statement, not compiler directives. and the decorators are simply called right after the corresponding "def" statement has been executed. -- http://mail.python.org/mailman/listinfo/python-list
Re: decorators question
> Shouldn't this code called when we actually DO call it ? Python statements are always executed to create the corresponding class and function objects when a module is imported. Cheers, -- Soni Bergraj http://www.YouJoy.org/ -- http://mail.python.org/mailman/listinfo/python-list
Re: decorators question
There was a copy-and-paste error with my last message. Better try this for foobar.py: def foo(f): print "called foo" return 'some text' @foo def bar(): print "called bar" -- Soni Bergraj http://www.YouJoy.org/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Why not just show the out-of-range index?
On 12/4/06, "Martin v. Löwis" <[EMAIL PROTECTED]> wrote: > Russ schrieb: > > I love Python, but every time I get an out-of-range error message, I > > wonder why it didn't just tell me what the out-of-range index was and > > what the allowable range was. Certainly that information must be > > available to the exception handler, or how would it know that it is out > > of range? > > Yes, that is true. The information is readily available. > > It's not true that it is "trivial" to fix, though: for every fix, there > ought to be a new test case also, and you have to run the test suite. > Depending on how fast a developer is, it may take between 30min and > 1hour to get a fix implemented (for the list case alone, not counting > all the other sequences). Maybe it is not as trivial as the OP thought, but it can't be that hard. It could be implemented as a utility function that does the index checking: bool PyObject_IsIndexOutOfBounds(PyObject *o, const char *ob_name, int i) { if (i < 0 || i >= o->ob_size) { char buf[256]; const char fmt[] = "%s index %d not in range(%d)" snprintf(buf, fmt, ob_name, i, o->ob_size); PyErr_SetString(PyExc_IndexError, buf); return true; } return false; } Then replace all code like: if (i < 0 || i >= a->ob_size) { PyErr_SetString(PyExc_IndexError, "string index out of range"); return NULL; } with: if (PyObject_IsOutOfBounds((PyObject *)a, "string", i) return NULL; Or maybe add "index" and "length" attributes to the PyExc_IndexError? "index" and "length" would of course be the invalid index and "length" the length of the container. That would be harder and probably involve some API change or something. Sorry I haven't thought this through 100%, but I don't see how actually _implementing it_ (getting it through the layers of bureaucracy may be harder) could be so difficult. > Even though I could fix it, I don't feel tempted to do so: I never had > this problem; in most cases of IndexError, it was very clear what the > problem was so I didn't need the additional information. For you yes, for a newbie the extra information would certainly be helpful. -- mvh Björn -- http://mail.python.org/mailman/listinfo/python-list
Re: Python bindings for RCS apps
[EMAIL PROTECTED] wrote: > There is pySVN for subversion but does other revision control system > systems have some good python bindings/apis ? with good docs and some > examples. Here are some starting points for some different systems: Bazaar -- Something about the structure of bzrlib: http://bazaar-vcs.org/Classes Writing plugins: http://bazaar-vcs.org/WritingPlugins Mercurial - Writing extensions: http://www.selenic.com/mercurial/wiki/index.cgi/ExtensionHowto CVS/RCS --- The ViewVC project deals with CVS repositories and RCS files: http://www.viewvc.org/ The cvs2svn tool might be useful: http://cvs2svn.tigris.org/ You might also want to search for repository converters, especially if your interest is focused on CVS, since many people seem to have been interested in migrating from CVS at some point. Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Why not just show the out-of-range index?
On 12/4/06, OKB (not okblacke) <[EMAIL PROTECTED]> wrote: > I think the same could be said of virtually all exceptions. What I > think would be ideal is that whenever an exception is raised, the > traceback tells you: > > 1) What the exception is > 2) The names of the variables involved in the offending expression > (or their character position in the line) > 3) The values of those variables There was a patch to that effect and a thread about it on python-dev two years ago [1]. Most python-devvers seemed skeptical. But the issue haven't come to closure yet. [1] - http://mail.python.org/pipermail/python-dev/2005-February/051470.html -- mvh Björn -- http://mail.python.org/mailman/listinfo/python-list
Re: Python spam?
Hendrik van Rooyen wrote: >"Aahz" <[EMAIL PROTECTED]> wrote: > > > >>Anyone else getting "Python-related" spam? So far, I've seen messages >>"from" Barry Warsaw and Skip Montanaro (although of course header >>analysis proves they didn't send it). >>-- >> >> > >not like that - just the normal crud from people giving me get rich quick tips >on the stock market that is aimed at mobilising my money to follow theirs to >help influence the price of a share... > >- Hendrik > > > > I'm ALWAYS getting python spam but what worries me, is the spammers Know my personal home address, and I NEVER EVER fill out any forms pages with my personal info - I think I'm being harrassed by hackers or something... John -- http://mail.python.org/mailman/listinfo/python-list
Re: Why not just show the out-of-range index?
BJörn Lindqvist wrote: > Sorry I haven't thought this through 100% obviously not. -- http://mail.python.org/mailman/listinfo/python-list
Python-URL! - weekly Python news and links (Dec 4)
QOTW: "We of all people should understand Worse Is Better. And I forgot to mention a little flash in the pan called Python, for which Tkinter (2+2 left as an exercise) is the GUI of choice." - Ken Tilton (on comp.lang.lisp, perhaps stretching the meaning of "of choice" somewhat) http://groups.google.com/group/comp.lang.lisp/msg/4d4945fb2706fc24 "It isn't that mobile platforms speak a different language to the web: they're perfectly capable of running AJAX software, from Python to JavaScript to full-blown Java and Flash." - Andrew Orlowski, The Register, "The mobile web: in praise of conv ... divergence" http://www.theregister.co.uk/2006/11/30/opera_mini_web/ Still, comp.lang.python manages to score a less than on-topic quote of the week: "> If you compare eclipse to VS, it is not that memory hungry. And if you compare Saturn to Jupiter, it's not that big." -- sjdevnull responding to hg http://groups.google.com/group/comp.lang.python/msg/13d0b24029b6e753 A provisional PyCon schedule has been made available with three... no, four lightning talk sessions: http://groups.google.com/group/comp.lang.python.announce/browse_frm/thread/7fd3fc7fbe4f7100 http://pycon.blogspot.com/2006/12/abundance-of-lightning-talks.html Python's "benevolent dictator" himself gave a talk recently, as previously mentioned in Python-URL!, and Niall Kennedy summarises the content for those not in attendance: http://www.niallkennedy.com/blog/archives/2006/11/google-mondrian.html Fof us who skimmed PEP 263 and thought that only "emacs-style" comments were allowed when telling Python about source file encodings, a careful re-reading is advised. Examples for vim users are provided in the context of a source code tidier, PythonTidy: http://groups.google.com/group/comp.lang.python/browse_frm/thread/c62220ff0f4cb30a Ravi Teja spells out communications architectures and mechanisms in the context of CORBA: http://groups.google.com/group/comp.lang.python/msg/3f056c5c87279aca The One Laptop Per Child developers and testers briefly consider Python development environments (in the context of things Alan Kay presented at EuroPython 2006): http://mailman.laptop.org/pipermail/devel/2006-November/003176.html ... while the "Python in education" special interest group mulls over the notion of a "view source" button for running programs: http://mail.python.org/pipermail/edu-sig/2006-November/007418.html E..and the best way to try the latest Python-related developments in the OLPC project: http://mail.python.org/pipermail/edu-sig/2006-December/007441.html Reconstructor is an Ubuntu Linux Live CD creator written in Python and licensed under the GNU General Public License (GPL): http://reconstructor.aperantis.com/ Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. For far, FAR more Python reading than any one mind should absorb, much of it quite interesting, several pages index much of the universe of Pybloggers. http://lowlife.jp/cgi-bin/moin.cgi/PythonProgrammersWeblog http://www.planetpython.org/ http://mechanicalcat.net/pyblagg.html comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Python411 indexes "podcasts ... to help people learn Python ..." Updates appear more-than-weekly: http://www.awaretek.com/python/index.html Steve Bethard continues the marvelous tradition early borne by Andrew Kuchling, Michael Hudson, Brett Cannon, Tony Meyer, and Tim Lesher of intelligently summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing
Re: Inheritance doesn't work
J. Clifford Dyer wrote: > Sure, but I think the question was more about how code that references > "MandelbrotImage could yield a stack that references MandelImage. Yeah, I guess I could have been more specific. :) -- http://mail.python.org/mailman/listinfo/python-list
Re: Factory pattern implementation in Python
Dennis Lee Bieber: > Presuming the is a type code I'd just set up a list of functions: > Then create a dictionary of them, keyed by the code > processors = { "1" : process_1, > "2" : process_2, > > "x" : process_x } Just a dict of functions was my solution too, I think avoiding more complex solutions is positive. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list