Re: Anyone understand this syntax error?
Sean Hammond wrote: Anyone understand this? Python 2.4.4c1 (#2, Oct 11 2006, 21:51:02) [GCC 4.1.2 20060928 (prerelease) (Ubuntu 4.1.1-13ubuntu5)] on linux2 Type help, copyright, credits or license for more information. def markdown_perl(input): ... Send 'input' (string) to the markdown perl script, and return the ...output from markdown (string). ... ...input: a string of markdown-formatted text, including \n's at the end ... of lines, that will be sent to the markdown process. ... ...returns: a string of valid XHTML from markdown ... ... import tempfile ... import commands ... file = tempfile.NamedTemporaryFile() ... file.write(input) ... file.flush() ... return commands.getoutput('./markdown.pl '+file.name) File stdin, line 15 return commands.getoutput('./markdown.pl '+file.name) ^ SyntaxError: invalid syntax I don't get it. Syntax seems fine to me, just a normal string concatenation. -- Are you perhaps mixing tabs and spaces? def f(): ... print hello # four spaces before 'print' ... return 42 # one tab before 'return' File stdin, line 3 return 42 ^ SyntaxError: invalid syntax Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: wxpython worked out but can't find api docs for download.
krishnakant Mane [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] hello all. finally I got the accessibility issue out from wxpython. actually almost got it out, but that's another story. now my problem is that I can't gind a downloadable version of wxpython api reference for the latest version or the latest api reference at least. I found the on-line version so please don't provide the same link. when I opened it on line, it took about 8 minuts to get the wx package come up on screen with over 600 links. I need to have some off line reference for the wxpython api. I have enough documentation to get started but I don't have the extencive api references for events and other methods, properties and attributes. can some one point me to a .zip or .tar.gz version of the api docs for wxpython? thanking all. Krishnakant. I am just now learning wxPython, and I used epydoc to generate HTML doc for the classes. To do this: 1. download and install epydoc 2. Fix bug in html.py of epydoc - line 2179 inherit should be inherited 3. Run epydoc against wx/ package directory. You will get numerous INTERNAL ERROR: messages and indentation error messages, but you will end up with a directory of HTML reference docs for the Python classes. -- Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: wxpython worked out but can't find api docs for download.
krishnakant Mane [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] hello all. finally I got the accessibility issue out from wxpython. actually almost got it out, but that's another story. now my problem is that I can't gind a downloadable version of wxpython api reference for the latest version or the latest api reference at least. I found the on-line version so please don't provide the same link. when I opened it on line, it took about 8 minuts to get the wx package come up on screen with over 600 links. I need to have some off line reference for the wxpython api. I have enough documentation to get started but I don't have the extencive api references for events and other methods, properties and attributes. can some one point me to a .zip or .tar.gz version of the api docs for wxpython? thanking all. Krishnakant. Also, there is much info at the wxPython wiki: http://wiki.wxpython.org/index.cgi/FrontPage -- Paul -- http://mail.python.org/mailman/listinfo/python-list
twisted problem with reactor.stop()
hello, everyone I use twisted 1.3 in my python application. in my program, I have one server and on client running at same time (so 2 reactor.run(installSignalHandlers=0) ) the client run in one thread and the server in an other thread ( reactor.callInThread(self.client... , reactor.callInThread(self.server ) when I catch escape button, I make a reactor.stop() but it doesn't seem to work and quit, and the application freeze. does anyone have any solution to quit the application with twisted? thanks in advance Maxime -- http://mail.python.org/mailman/listinfo/python-list
Re: twisted problem with reactor.stop()
[EMAIL PROTECTED] wrote: I use twisted 1.3 in my python application. Isn't 1.3 heavily outdated? The most recent is 2.4. in my program, I have one server and on client running at same time (so 2 reactor.run(installSignalHandlers=0) ) the client run in one thread and the server in an other thread ( - Is it absolutely necessary to use two threads? - Why do you need two reactors running? I'm not even sure if that's possible or why I would want to do this. when I catch escape button, I make a reactor.stop() but it doesn't seem to work and quit, and the application freeze. does anyone have any solution to quit the application with twisted? So it seems you only stop one reactor of two. The other one would have to be stopped, too, I think. Regards, Björn -- BOFH excuse #112: The monitor is plugged into the serial port -- http://mail.python.org/mailman/listinfo/python-list
Re: wxpython worked out but can't find api docs for download.
hi pol, thanks for your helpful suggestion. I tried it but nothing seams to work. I can't get the folder containing html files as you suggested. can you kindly attach a .zip archive of your generated folder as a privat email to me? I will be really thankful. Krishnakant. -- http://mail.python.org/mailman/listinfo/python-list
Re: Parsing data from pyserial
Lone Wolf wrote: reading = ser.read(40) Simply try ser.readline() here, or maybe ser.readline(eol=\r). -- Giovanni Bajo -- http://mail.python.org/mailman/listinfo/python-list
WxPython
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. -- http://mail.python.org/mailman/listinfo/python-list
Resource cleanup
I'm thinking of using Tim Peters' excellent approach to resource clean up see http://mail.python.org/pipermail/python-dev/2006-April/063425.html class _RealTypeResourceCleaner: def __init__(self, *resources): self.resources = resources def __del__(self): if self.resources is not None: for r in self.resources: r.close() self.resources = None # and typically no other methods are needed, or desirable, in # this helper class class RealType: def __init__(*args): ... # and then, e.g., self.cleaner = _ResourceCleaner(resource1, resource2) but am wondering exactly what 'resources' are left available when the r.close method is called in the __del__ method of RealTypeResourceCleaner. In particular, can I rely on the module globals of r still being present if the RealType instance is going away because the main script has terminated, ie if the r.close method refers to a global function is it guaranteed to be available when the close is called? I guess I must be asking if referring to a global in a method is actually a reference to that global or does the reference only occur when the code is executed? I have a vague feeling that I came across problems in the past about the order in which modules were finalized. -- Robin Becker -- http://mail.python.org/mailman/listinfo/python-list
Re: How to realize the interactive python in Eclipse?
purple wrote: I have installed the Eclipse and the plug-in Pydev. Also, I have add an python program in the external tools. When I run the python program in the external tools, i can type python command just like in the python shell.But when I finished running a python file, in the console, I could not type any command to check some argument generated in the process. Is there any way I can make it? thank you~~ Do you not want to run python from eclipse? If so, go to preferences for pydev and show pydev where your python executable is. Then you can use the debug function to look at variables. For the external tools problem with python interactive, did you include -i as an argument for the python interpreter? -- http://mail.python.org/mailman/listinfo/python-list
Re: Resource cleanup
but am wondering exactly what 'resources' are left available when the r.close method is called in the __del__ method of RealTypeResourceCleaner. In particular, can I rely on the module globals of r still being present if the RealType instance is going away because the main script has terminated, ie if the r.close method refers to a global function is it guaranteed to be available when the close is called? I guess I must be asking if referring to a global in a method is actually a reference to that global or does the reference only occur when the code is executed? I have a vague feeling that I came across problems in the past about the order in which modules were finalized. I'm a bit on unsure ground here - so take it with a grain of salt. It is for sure that only executing code will refer to a global - the mere mention of anything can't possibly create a reference (in python at least) - consider this simple example: import random def foo(): print schroedingers_cat if random.random() .5: schroedingers_cat = I'm alive! foo() So I presume it can very well happen that you will lose a module when trying to finalize. So most probably it is the cleverest solution to make the cleaner as self-contained as possible, by storing explicit references to things you might need in the instance itself. But I'm not sure if the transitivity of dependencies might not kick your ass somewhere anyhow. All in all an interesting topic - I'd be looking forward to more insights, and very much liked the link you gave us. Diez -- http://mail.python.org/mailman/listinfo/python-list
cursor.executemany() float error
Data Struct: from (string), to (string), rate (float) when i run this: cursor.executemany('insert into promo (`From`,`To`, `RATE`) \ values (%s,%s,%f)', [ ('AA','BB',10.2), ('CC','DD',10.3) ] ) i got this error: TypeError: float argument required i checked, 10.2 10.3 , there are at the right loc. what went wrong?? -- http://mail.python.org/mailman/listinfo/python-list
Re: Parsing data from pyserial
On 2006-12-03, Lone Wolf [EMAIL PROTECTED] wrote: import serial ser=serial.Serial('com1',baudrate=115200, bytesize=8, parity='N', stopbits=1,xonxoff=0, timeout=1) ser.write(PM 1) #This sets the CMUcam to poll mode for i in range(0,100,1): ser.write(TC 016 240 100 240 016 240\r\n) reading = ser.read(40) print reading components = reading.split() print components ser.close Here is an example output: M 37 79 3 4 59 124 86 25 ['59', '123', '87', '25', 'M', '37', '79', '3', '4', '59', '124', '86', '25', 'M '] M 38 77 3 2 59 124 86 25 ['39', '85', '26', 'M', '38', '77', '3', '2', '59', '124', '86', '25', 'M', '38' , '7'] My problem is that I am trying to get each data point of the packet into a separate variable. Ordinarily, this would be easy, as I would just parse the packet, read the array and assign each element to a variable eg. mx = components[1]. However, that doesn't work here because the original packet and the array that I got from using the split() method are different. I doubt it. Try printing `reading` instead of reading. I suspect that the string you're getting from ser.read() has a carraige-return in it that you aren't seeing when you do print reading. If I were to try read the array created in the first example output, mx would be 123 instead of 37 like it is in the packet. In the second example, the array is 85 while the packet is 38. As near as I can figure out, pyserial is reading a stream of data and helpfully rearranging it so that it fits the original packet format M xxx xxx xxx xxx xxx xxx xxx xxx. No, it isn't. I wrote the Posix low-level code that's in pyserial. I've used pyserial extensively on both Windows and Linux. It doesn't rearrange anything. I would have thought the split() method that I used on original packet (ie the reading variable) would have just returned an array with nine elements like the packet has. This is not the case, and I am at a loss about how to fix this. When something odd seems to be happening with strings, always print `whatever` rather than whatever I've searched the archive here and elsewhere with no luck. Any help REALLY appreciated! -- Grant Edwards grante Yow! There's a SALE on at STRETCH SOCKS down at the visi.com7-11!! -- http://mail.python.org/mailman/listinfo/python-list
Re: Resource cleanup
Diez B. Roggisch wrote: ... I have a vague feeling that I came across problems in the past about the order in which modules were finalized. I'm a bit on unsure ground here - so take it with a grain of salt. It is for sure that only executing code will refer to a global - the mere mention of anything can't possibly create a reference (in python at least) - consider this simple example: import random def foo(): print schroedingers_cat if random.random() .5: schroedingers_cat = I'm alive! foo() yes I guess although foo must know that schroedingers_cat is global it doesn't need to bring it into existence so would fail 50% of the time :) So I presume it can very well happen that you will lose a module when trying to finalize. So most probably it is the cleverest solution to make the cleaner as self-contained as possible, by storing explicit references to things you might need in the instance itself. But I'm not sure if the transitivity of dependencies might not kick your ass somewhere anyhow. I think this must be the right approach. Either the resources or the cleaner should hold everything required for cleanup. Probably the resource is the best place. -- Robin Becker -- http://mail.python.org/mailman/listinfo/python-list
Re: cursor.executemany() float error
progman wrote: cursor.executemany('insert into promo (`From`,`To`, `RATE`) \ values (%s,%s,%f)', [ ('AA','BB',10.2), ('CC','DD',10.3) ] ) i got this error: TypeError: float argument required i checked, 10.2 10.3 , there are at the right loc. what went wrong?? posting a bit more of the traceback, and mentioning what database you're using might be helpful. have you tried using %s markers for all parameters, btw? (SQL data binding and %-style string formatting are two different things, after all). /F -- http://mail.python.org/mailman/listinfo/python-list
Re: cursor.executemany() float error
i am using mysql i tried the cursor.executemany('insert into promo (`From`,`To`, `RATE`) \ values (%s,%s,%s)', [ ('AA','BB',10.2), ('CC','DD',10.3) ] ) and it works. very strange. isn't it? Fredrik Lundh wrote: progman wrote: cursor.executemany('insert into promo (`From`,`To`, `RATE`) \ values (%s,%s,%f)', [ ('AA','BB',10.2), ('CC','DD',10.3) ] ) i got this error: TypeError: float argument required i checked, 10.2 10.3 , there are at the right loc. what went wrong?? posting a bit more of the traceback, and mentioning what database you're using might be helpful. have you tried using %s markers for all parameters, btw? (SQL data binding and %-style string formatting are two different things, after all). /F -- http://mail.python.org/mailman/listinfo/python-list
Re: Parsing data from pyserial
On Sat, 2 Dec 2006 23:02:06 -0500, Lone Wolf [EMAIL PROTECTED] wrote: I'm trying to get data through my serial port from a CMUcam. This gizmo tracks a color and returns a packet of data. The packet has nine data points (well, really eight since the first point is just a packet header) separated by spaces as follows: M xxx xxx xxx xxx xxx xxx xxx xxx Here is the code I am using (python v24): import serial ser=serial.Serial('com1',baudrate=115200, bytesize=8, parity='N', stopbits=1,xonxoff=0, timeout=1) ser.write(PM 1) #This sets the CMUcam to poll mode for i in range(0,100,1): ser.write(TC 016 240 100 240 016 240\r\n) reading = ser.read(40) print reading components = reading.split() print components ser.close In my dealing with serial gizmos I have to put a delay between the request sent to the gizmo and the reading of the serial input buffer for returned data. Serial ports and gizmos need some time to do their thing. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to realize the interactive python in Eclipse?
Thanks so much for your concern~~ In the preferences for pydev, I have added the python.exe in the python interpreters, and also the system PYTHONPATH, Forced built-in libs. I am not sure whether you mean it? I am sorry because I am a green hand on the eclipse. And for the external tools, I have include the -i as an argument for the python interpreter and there is no other argument. Is there any other argument? Thanks so much~~ Do you not want to run python from eclipse? If so, go to preferences for pydev and show pydev where your python executable is. Then you can use the debug function to look at variables. For the external tools problem with python interactive, did you include -i as an argument for the python interpreter? -- http://mail.python.org/mailman/listinfo/python-list
Deleting from a list while iterating
The problems of this are well known, and a suggestion for making this easier was recently posted on python-dev. However, I believe this can be done just as well without a change to the language. What's more, most of the suggested methods (in my search results as well as the suggestion itself) do not scale well, which my approach would solve. My approach is to make a set of indexes to removed while iterating, then use a list comprehension to filter them out after. Timings of this and two other common approaches follow: setapproach = \ def func(count): from random import random items = [random() for i in xrange(count)] remove = set() for index, x in enumerate(items): #...do something... if x 0.5: remove.add(index) items = [x for index, x in enumerate(items) if index not in remove] copyapproach = \ def func(count): from random import random items = [random() for i in xrange(count)] for x in items[:]: if x 0.5: items.remove(x) reverseapproach = \ def func(count): from random import random items = [random() for i in xrange(count)] for index in range(len(items) - 1, -1, -1): if items[index] 0.5: del items[index] import timeit timeit.Timer(stmt='func(1000)', setup=setapproach).timeit(1) 0.0016040802001953125 timeit.Timer(stmt='func(1000)', setup=copyapproach).timeit(1) 0.0085191726684570312 timeit.Timer(stmt='func(1000)', setup=reverseapproach).timeit(1) 0.0011308193206787109 timeit.Timer(stmt='func(1)', setup=setapproach).timeit(1) 0.021183013916015625 timeit.Timer(stmt='func(1)', setup=copyapproach).timeit(1) 1.0268981456756592 timeit.Timer(stmt='func(1)', setup=reverseapproach).timeit(1) 0.038264989852905273 timeit.Timer(stmt='func(10)', setup=setapproach).timeit(1) 0.23896384239196777 timeit.Timer(stmt='func(10)', setup=copyapproach).timeit(1) 274.57498288154602 timeit.Timer(stmt='func(10)', setup=reverseapproach).timeit(1) 2.2382969856262207 As you can see, although reverse iteration is somewhat faster at smaller sizes, a set is substantially faster at larger sizes, and I believe is more readable anyway. Copying shouldn't even be considered unless you know the size will always be trivial ( 1000). I'm sure there's a few other approaches that would do even better under certain conditions. One is a generator, if your input and output should both be iterators. Another is using slicing to move contiguous sections of retained items over the removed items. I leave both of these as an exercise for the reader. -- Adam Olsen, aka Rhamphoryncus -- http://mail.python.org/mailman/listinfo/python-list
Re: twisted problem with reactor.stop()
On 3 Dec 2006 03:16:44 -0800, [EMAIL PROTECTED] wrote: hello, everyone I use twisted 1.3 in my python application. in my program, I have one server and on client running at same time (so 2 reactor.run(installSignalHandlers=0) ) the client run in one thread and the server in an other thread ( reactor.callInThread(self.client... , reactor.callInThread(self.server ) when I catch escape button, I make a reactor.stop() but it doesn't seem to work and quit, and the application freeze. does anyone have any solution to quit the application with twisted? thanks in advance Maxime Don't do this. You don't need separate threads for client and server code. There is only one reactor, and you can only run it in one thread. Use it for both your client and your server. Jean-Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Deleting from a list while iterating
In [EMAIL PROTECTED], Rhamphoryncus wrote: My approach is to make a set of indexes to removed while iterating, then use a list comprehension to filter them out after. Timings of this and two other common approaches follow: setapproach = \ def func(count): from random import random items = [random() for i in xrange(count)] remove = set() for index, x in enumerate(items): #...do something... if x 0.5: remove.add(index) items = [x for index, x in enumerate(items) if index not in remove] Why do you make it that complicated? If you are going to build a new list anyway, this can be done without the `set()` and just one listcomp: items = [x for x in items if x 0.5] No need to iterate twice over the `items`. The two other approaches you gave are just needed if it's important that the elements are deleted in place, i.e. that you don't rebind `items` to a new object. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Deleting from a list while iterating
Rhamphoryncus wrote: As you can see, although reverse iteration is somewhat faster at smaller sizes, a set is substantially faster at larger sizes, and I believe is more readable anyway. your set approach doesn't modify the list in place, though; it creates a new list, in a rather roundabout way. if modification in place isn't important, the normal way is of course to create a *new* list: items = [i for i in items if not i 0.5] on my machine, that's about two orders of magnitude faster than your fast approach for n=10. (or twice as fast, if I don't factor out the time it takes to *create* the original list from the benchmark). /F -- http://mail.python.org/mailman/listinfo/python-list
Re: About alternatives to Matlab
Jon Harrop wrote: In particular, I think you are eagerly allocating arrays when, in a functional language, you could just as easily compose closures. You are completely wrong. I'll give an example. If you write the Python: a[:] = b[:] + c[:] + d[:] I think that is equivalent to the ML: fill a (map2 ( + ) (map2 ( + ) b c) d) which can be deforested in ML to avoid the creation of the intermediate result b[:] + c[:] by using a closure to add three values at once: fill a (map3 (fun b c d - b + c + d) b c d) which will be much faster because it doesn't generate an intermediate array. Ah, but, this wasn't about temporaries when you spoke of eagerly allocating arrays, was it? But yes, you're right, in this example temporary arrays are created; arrays that Ocaml would not need. (I don't exactly understand why you'd need a functional language to get this optimization, though.) You might have guessed that you can get rid of most temporary arrays, at the expense of readability, with numpy. For example, replacing d1[:] = odd[:] - C1*even[:] with numpy.multiply(-C1,even,d1) numpy.add(d1,odd,d1) eliminates the intermediate. No unnecessary array allocations; no closures necessary. I'm curious whether this shared-slicing isn't, in some ways, advantageous over the Ocaml way. I presume that in Ocaml, the way you'd share array data is to create a closure can apply some operation to selected elements of the array, returning the result. But could this as easily modify the array in-place? I presume a good compiler could be able to inline the function and optimize the call to an in-place operation, but I'm not sure how well this works in practice. Here's a version of D4_Transform that uses no temporary arrays (aside from the work arrays s1, d1, and d2, which are allocated only once). It's about 40% faster for me than the one with infix operations. I'd be curious how it compares to a correct Ocaml version. (I'd still expect Ocaml to be at least twice as fast.) def alt_D4_Transform(x, s1=None, d1=None, d2=None): add = numpy.add multiply = numpy.multiply C1 = 1.7320508075688772 C2 = 0.4330127018922193 C3 = -0.066987298107780702 C4 = 0.51763809020504137 C5 = 1.9318516525781364 if d1 == None: d1 = numpy.zeros(x.size/2,numpy.Float) s1 = numpy.zeros(x.size/2,numpy.Float) d2 = numpy.zeros(x.size/2,numpy.Float) odd = x[1::2] even = x[:-1:2] multiply(-C1,even,d1) add(d1,odd,d1) multiply(C2,d1,s1) add(s1,even,s1) d2[0] = C3 * d1[-1] multiply(C3,d1[:-1],d2[1:]) add(s1,d2,s1) d2[0] = d1[0] + s1[-1] add(d1[1:],s1[:-1],d2[1:]) multiply(C4,s1,even) multiply(C5,d2,odd) if x.size 2: alt_D4_Transform(even,s1[0:even.size/2],d1[0:even.size/2],d2[0:even.size/2]) It seems to me a big help is the ability to fold multiple array operations into a single loop, which is optimization a dynamically-typed language like Python can't easily make. (It'd require are really smart JIT compiler or some concessions in dynamicity.) Writing a JIT to compile this kind of stuff is easy. Eh, getting a JIT to do the optimization I spoke of in Python is not easy. It would be relatively easy in a statically typed language. In Python, it'd be tantamount to rewriting a dynamically reconfigurable version of numpy--you'd have to duplicate numpy's complex type-dispatching rules. My point is that this is fundamentally bad code, Whoa, there. I realize that for people who prefer functional programming, with their recursively reductionist way of thinking, it might seem as if leaving any sort of reducibility in final result is fundamentally bad, but that's a pretty strong thing to say. so why bother trying to write a Python JIT? Why not just write in a better language for this task? Optimising within a fundamentally slow language seems silly to me. Because, for most people, language choice is not a greedy maximizing of a single issue. Nobody who uses numpy is under the impression that it can match a statically-typed language that is compiled to machine code in peak performance. (Matlab is fair game, of course.) But speed is not the only important thing. I use Python because it's a excellently designed language that fits my overall needs, and numpy because sometimes I need more speed than vanilla Python. Only when speed is critical (for example, 3D collision detection) do I write an extension in a better language for the task (i.e. C). This is something that's quite popular in the numerically-intensive computing community, BTW. Many people use Python to handle boring stuff like file I/O, memory managment, and non-critical numerical calculations, and write C or Fortran extensions to do the numerically-intensive stuff. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: Deleting from a list while iterating
Fredrik Lundh wrote: on my machine, that's about two orders of magnitude faster than your fast approach for n=10. oops. forget that; it's three times faster, if you're actually creating the entire list, and not just a generator that will create it on demand ;-) /F -- http://mail.python.org/mailman/listinfo/python-list
Re: Deleting from a list while iterating
Rhamphoryncus schrieb: setapproach = \ def func(count): from random import random items = [random() for i in xrange(count)] remove = set() for index, x in enumerate(items): #...do something... if x 0.5: remove.add(index) items = [x for index, x in enumerate(items) if index not in remove] This is different from the other approaches in that it doesn't modify items. If you wanted a new list, you could incrementally build one already in the first pass, no need to collect the indices first (as BlackJack explains). If you wanted in-place modification, I'd do newitems = [] for x in items: if not (x 0.5): newitems.append(x) items[:] = newitems copyapproach = \ def func(count): from random import random items = [random() for i in xrange(count)] for x in items[:]: if x 0.5: items.remove(x) This happens to work for your example, but is incorrect in the general case: you meant to write del items[i+removed] here, as .remove(x) will search the list again, looking for the first value to remove. If your condition for removal happens to leave some items equal to x in the list, it would remove the wrong item. Because the numbering changes while the iteration is in progress, you have to count the number of removed items also. Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: Deleting from a list while iterating
Marc 'BlackJack' Rintsch wrote: Why do you make it that complicated? If you are going to build a new list anyway, this can be done without the `set()` and just one listcomp: Fredrik Lundh wrote: your set approach doesn't modify the list in place, though; it creates a new list, in a rather roundabout way. if modification in place isn't important, the normal way is of course to create a *new* list: items = [i for i in items if not i 0.5] on my machine, that's about two orders of magnitude faster than your fast approach for n=10. Sorry, I should have clarified that the original post assumed you needed info from the do something phase to determine if an element is removed or not. As you say, a list comprehension is superior if that is not necessary. -- Adam Olsen, aka Rhamphoryncus -- http://mail.python.org/mailman/listinfo/python-list
Re: Deleting from a list while iterating
Marc 'BlackJack' Rintsch wrote: No need to iterate twice over the `items`. The two other approaches you gave are just needed if it's important that the elements are deleted in place, i.e. that you don't rebind `items` to a new object. and even when you do, that can often be written as, e.g: items[:] = (i for i in items if not i 0.5) /F -- http://mail.python.org/mailman/listinfo/python-list
Re: Deleting from a list while iterating
Rhamphoryncus wrote: Sorry, I should have clarified that the original post assumed you needed info from the do something phase to determine if an element is removed or not. As you say, a list comprehension is superior if that is not necessary. that's spelled out = [] for i in items: ... do something ... if i 0.5: out.append(i) in Python, and is only a little slower than a list comprehension, as written above. if performance is really important, move the method lookup out of the loop: out = [] append = out.append for i in items: ... do something ... if i 0.5: append(i) /F -- http://mail.python.org/mailman/listinfo/python-list
Re: Deleting from a list while iterating
Martin v. Löwis wrote: Rhamphoryncus schrieb: setapproach = \ def func(count): from random import random items = [random() for i in xrange(count)] remove = set() for index, x in enumerate(items): #...do something... if x 0.5: remove.add(index) items = [x for index, x in enumerate(items) if index not in remove] This is different from the other approaches in that it doesn't modify items. If you wanted a new list, you could incrementally build one already in the first pass, no need to collect the indices first (as BlackJack explains). I didn't feel this distinction was worth mentioning, since oldlist[:] = newlist is so trivial. The only solution that really avoids making a copy is the reverse-iteration one. If you wanted in-place modification, I'd do newitems = [] for x in items: if not (x 0.5): newitems.append(x) items[:] = newitems I agree, that does seem simpler. copyapproach = \ def func(count): from random import random items = [random() for i in xrange(count)] for x in items[:]: if x 0.5: items.remove(x) This happens to work for your example, but is incorrect in the general case: you meant to write del items[i+removed] here, as .remove(x) will search the list again, looking for the first value to remove. If your condition for removal happens to leave some items equal to x in the list, it would remove the wrong item. Because the numbering changes while the iteration is in progress, you have to count the number of removed items also. I agree that the example I gave here sucks. However, I copied it from another posting as a recommended method to get removal to work *right* (without noticing how slow it is). There seems to have been many distinct approaches to this problem over the years. Hopefully we can converge on a single ideal solution (or a few situational ones) as TOOWTDI. -- Adam Olsen, aka Rhamphoryncus -- http://mail.python.org/mailman/listinfo/python-list
Re: best way to align words?
Oleg Batrashev a écrit : This means that if you have 10 sentences with 5 words in each there is 5^10 space and time complexity. Definitelly, there are better algorithms from dynamic programming, but you should review your needs: how many sentences, words you have. it can be few to many, actually it depends of the words i'm looking for. -- http://mail.python.org/mailman/listinfo/python-list
Re: Parsing data from pyserial
On 2006-12-03, Si Ballenger [EMAIL PROTECTED] wrote: In my dealing with serial gizmos I have to put a delay between the request sent to the gizmo and the reading of the serial input buffer for returned data. Serial ports and gizmos need some time to do their thing. I doubt that's the issue. He's reading with a 1-second timeout value. -- Grant Edwards grante Yow! The Korean War must at have been fun. visi.com -- http://mail.python.org/mailman/listinfo/python-list
Re: About alternatives to Matlab
Carl Banks wrote: fill a (map3 (fun b c d - b + c + d) b c d) which will be much faster because it doesn't generate an intermediate array. Ah, but, this wasn't about temporaries when you spoke of eagerly allocating arrays, was it? I had thought that all of the array operations were allocating new arrays at first but it seems that at least assignment to a slice does not. Does: a[:] = b[:] + c[:] allocate a temporary for b[:] + c[:]? But yes, you're right, in this example temporary arrays are created; arrays that Ocaml would not need. (I don't exactly understand why you'd need a functional language to get this optimization, though.) I thought that functional programming could get you both the brevity of Python's slicing and the performance of C's compilation but I was wrong. You can get the brevity of the Python approach in C. You might have guessed that you can get rid of most temporary arrays, at the expense of readability, with numpy. For example, replacing d1[:] = odd[:] - C1*even[:] with numpy.multiply(-C1,even,d1) numpy.add(d1,odd,d1) eliminates the intermediate. No unnecessary array allocations; no closures necessary. Right. Performance will probably go from 5x slower to 2x slower because you're traversing the arrays twice instead of once. I'm curious whether this shared-slicing isn't, in some ways, advantageous over the Ocaml way. That's exactly what I thought to start with. The author of F# is working on getting slicing into his language but the use of slicing in this Python benchmark corrupted my fragile little mind. Slicing is a terrible way to approach this problem if you're using a compiled language like F#. 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, 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]). I presume that in Ocaml, the way you'd share array data is to create a closure can apply some operation to selected elements of the array, returning the result. Yes. That is certainly one way of doing it. But could this as easily modify the array in-place? Absolutely. A closure would capture a reference to the array. Arrays are mutable so you could alter the array from within the closure. In F# you could even execute the closures concurrently to alter different parts of the same array at the same time. I just tried that and it is actually slower to multithread this. I presume a good compiler could be able to inline the function and optimize the call to an in-place operation, but I'm not sure how well this works in practice. Surprisingly well it seems: F# and OCaml are almost as fast as C/C++! Here's a version of D4_Transform that uses no temporary arrays (aside from the work arrays s1, d1, and d2, which are allocated only once). It's about 40% faster for me than the one with infix operations. I'd be curious how it compares to a correct Ocaml version. (I'd still expect Ocaml to be at least twice as fast.) I get: 1.57s Python (in-place) It seems to me a big help is the ability to fold multiple array operations into a single loop, which is optimization a dynamically-typed language like Python can't easily make. (It'd require are really smart JIT compiler or some concessions in dynamicity.) Writing a JIT to compile this kind of stuff is easy. Eh, getting a JIT to do the optimization I spoke of in Python is not easy. It would be relatively easy in a statically typed language. In Python, it'd be tantamount to rewriting a dynamically reconfigurable version of numpy--you'd have to duplicate numpy's complex type-dispatching rules. There aren't any complicated types in the above code. In fact, there are only two types: float and float array. Type checking is easy in this case, compilation to C is also easy, then you just dispatch to the compiled C code when the types are ok. You would want to write your Python code like C code but that is shorter in this case. You may also want to flag code for compilation manually in order to avoid the overhead of compiling code unnecessarily. My point is that this is fundamentally bad code, Whoa, there. I realize that for people
Re: A mail from Steve Ballmer. See what Microsoft will do and follow.
JustStand [EMAIL PROTECTED] wrote: In many ways, it was the launch of Windows 95 and Office 95 eleven years ago that signaled the start of this transformation. ... Right. 11 years ago I switched from Amiga to Linux. -- Web (en): http://www.no-spoon.de/ -*- Web (de): http://www.frell.de/ -- http://mail.python.org/mailman/listinfo/python-list
Re: text adventure question
On 2006-12-02, Ara Kooser ghashsnaga at gmail.com wrote: I am working on a text adventure game for python to get back into python programming. My version 0.1 used only functions so I could get familiar with how those work. I want to move beyond that. I am not sure what would be a good Python way of handling this. I was wondering if classes would help? What things should be included in the main program? That's so funny! I did the same thing when I was learning Python! My cousin and I wrote some text adventure games when we were teenagers (the code was on a TRS-80 in BASIC back then, and the BASIC program became a kind of interpreter to interpret the adventure program files). I re-wrote it in C, then Java, then Python. I used it as a sort of learning tool, and since Python is so good with strings, it became very efficient. I now have the code running on one of my web pages, so you can play the games on-line: http://www.skyrush.com/explore/ -Joe -- http://mail.python.org/mailman/listinfo/python-list
Re: About alternatives to Matlab
Jon Harrop wrote: I had thought that all of the array operations were allocating new arrays at first but it seems that at least assignment to a slice does not. Does: a[:] = b[:] + c[:] allocate a temporary for b[:] + c[:]? Yep. [snip] Not only is that shorter than the Python, 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 [snip] 1.57s Python (in-place) So, optimized Python is roughly the same speed as naive Ocaml optimized Ocaml is roughly the same speed as C++ It seems to me a big help is the ability to fold multiple array operations into a single loop, which is optimization a dynamically-typed language like Python can't easily make. (It'd require are really smart JIT compiler or some concessions in dynamicity.) Writing a JIT to compile this kind of stuff is easy. Eh, getting a JIT to do the optimization I spoke of in Python is not easy. It would be relatively easy in a statically typed language. In Python, it'd be tantamount to rewriting a dynamically reconfigurable version of numpy--you'd have to duplicate numpy's complex type-dispatching rules. There aren't any complicated types in the above code. In fact, there are only two types: float and float array. You're vastly underestimating the complexity of numpy objects. They have an awful lot going on under the covers to make it look simple on the surface. There's all kinds of type-checking and type-conversions. A JIT that folds loops together would have to have knowledge of that process, and it's a lot of knowledge to have. That is not easy. Type checking is easy in this case, compilation to C is also easy, then you just dispatch to the compiled C code when the types are ok. You would want to write your Python code like C code but that is shorter in this case. You may also want to flag code for compilation manually in order to avoid the overhead of compiling code unnecessarily. My point is that this is fundamentally bad code, Whoa, there. I realize that for people who prefer functional programming, with their recursively reductionist way of thinking, it might seem as if leaving any sort of reducibility in final result is fundamentally bad, but that's a pretty strong thing to say. I was referring to the slicing specifically, nothing to do with functional programming. My F# and OCaml code are now basically identical to the C++ code. It is pretty strong thing to say that anything is fundamentally bad just because it's not fast as something else. Fundamental badness ought to run deeper than some superficial, linear measure. so why bother trying to write a Python JIT? Why not just write in a better language for this task? Optimising within a fundamentally slow language seems silly to me. Because, for most people, language choice is not a greedy maximizing of a single issue. Nobody who uses numpy is under the impression that it can match a statically-typed language that is compiled to machine code in peak performance. (Matlab is fair game, of course.) But speed is not the only important thing. In this specific context (discrete wavelet transform benchmark), I'd have said that speed was the most important thing after correctness. So let's say I'm planning to write this complicated graphical program, that does all sorts of stuff. I/O, networking, database, etc. It's a medium throughput program, and a slow language like Python is sufficient to run it, except for this one tiny part where I have to transform of wave data. Now, I was going to write the program in Python, and use the very convenient numpy to do the transformation part. No problem, numpy will be fast enough for my needs. But wait! It's silly try to optimize code in a fundamentally slow language! It's vanity to even try! I guess for the sake of getting this little D4 transform to double in speed I'll scrap Python and write the whole thing in OCaml. (Or I can begrudingly admit that it's not really silly to try to optimize a slow language.) [snip] This is really great work but I can't help but wonder why the authors chose to use Python when other languages seem better suited. I'd like to work on raising people's awareness of these alternatives, and probably create some useful tools in the process. So I'm keen to learn what Python programmers would want/expect from F# and OCaml. What would it take to make you convert? Them not being functional would be a good start Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: wxpython worked out but can't find api docs for download.
Go to: http://wxpython.org/download.php#binaries and in the documentation part, download both wxPython-docs and wxPython-newdocs. Hope this helps. -- http://mail.python.org/mailman/listinfo/python-list
Re: wxpython worked out but can't find api docs for download.
Sorry, I think all you want is wxPython-newdocs, which is the wxPython-specific documentation. -- http://mail.python.org/mailman/listinfo/python-list
Re: Parsing data from pyserial
On Sun, 03 Dec 2006 16:52:33 -, Grant Edwards [EMAIL PROTECTED] wrote: On 2006-12-03, Si Ballenger [EMAIL PROTECTED] wrote: In my dealing with serial gizmos I have to put a delay between the request sent to the gizmo and the reading of the serial input buffer for returned data. Serial ports and gizmos need some time to do their thing. I doubt that's the issue. He's reading with a 1-second timeout value. I would think a time delay would be needed between the below two lines in the code if he expects to get a useable data string back from the gizmo for the command sent to it. ser.write(TC 016 240 100 240 016 240\r\n) reading = ser.read(40) -- http://mail.python.org/mailman/listinfo/python-list
Re: Parsing data from pyserial
Grant Edwards wrote: When something odd seems to be happening with strings, always print `whatever` rather than whatever :-) Unholy perlism, Batman! For the benefit of gentle readers who are newish and might not have seen the ` character in Python code outside a string literal, or for those who'd forgotten, there is a cure: | re.sub(r`(.*?)`, rrepr(\1), print `whatever`, `foo`, `bar`) | 'print repr(whatever), repr(foo), repr(bar)' :-) -- http://mail.python.org/mailman/listinfo/python-list
Re: Parsing data from pyserial
On 2006-12-03, Si Ballenger [EMAIL PROTECTED] wrote: In my dealing with serial gizmos I have to put a delay between the request sent to the gizmo and the reading of the serial input buffer for returned data. Serial ports and gizmos need some time to do their thing. I doubt that's the issue. He's reading with a 1-second timeout value. I would think a time delay would be needed between the below two lines in the code if he expects to get a useable data string back from the gizmo for the command sent to it. ser.write(TC 016 240 100 240 016 240\r\n) reading = ser.read(40) No. A delay isn't needed as long as the device responds within 1 second. The read() call will wait up to 1 second for the first byte of the response. -- Grant Edwards grante Yow! NEWARK has been at REZONED!! DES MOINES has visi.combeen REZONED!! -- http://mail.python.org/mailman/listinfo/python-list
Re: Parsing data from pyserial
Si Ballenger wrote: I would think a time delay would be needed between the below two lines in the code if he expects to get a useable data string back from the gizmo for the command sent to it. ser.write(TC 016 240 100 240 016 240\r\n) reading = ser.read(40) why's that? if the gizmo is busy doing its thing, read() will wait for up to one second before giving up. /F -- http://mail.python.org/mailman/listinfo/python-list
Re: Parsing data from pyserial
On 2006-12-03, John Machin [EMAIL PROTECTED] wrote: Grant Edwards wrote: When something odd seems to be happening with strings, always print `whatever` rather than whatever :-) Unholy perlism, Batman! OK, make that print repr(whatever). :) -- Grant Edwards grante Yow! I selected E5... but at I didn't hear Sam the Sham visi.comand the Pharoahs! -- http://mail.python.org/mailman/listinfo/python-list
problem formatting dates from text fields.
hello all. thanks for the help and for pointing me to the proper url for wxpython related issues. I am so happy that I now have a very easy gui library that can do practically every thing with such ease (no flames intended but I was never at so much ease with java swing ). I however have a problem with dates. I am tired searching for some good tutorial that can explain the basic functionality of wx.datetime class and the datetime picker. I want to display the date in dd/mm/ format and allow the user to change the dates. I then will like to take the value (the entire date) and put into a database. now this is my first question. the other problem is even more tough to solve with my given knowledge of wx.datetime and related classes. unfortunately the database given to me has a text field for date and the data is neetly entered. but when I get the data back from that text field I some how want to convert it back to actual date in the same dd/mm/ format and send this as a value to my date time picker. how can I achieve this? thanking all. Krishnakant. -- http://mail.python.org/mailman/listinfo/python-list
please provide urls for some python success stories.
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: About alternatives to Matlab
Carl Banks wrote: 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 [snip] 1.57s Python (in-place) So, optimized Python is roughly the same speed as naive Ocaml optimized Ocaml is roughly the same speed as C++ Absolutely not: Optimized Python is 14% slower than badly written OCaml. Given the problem, rather than the Python solution, nobody would write OCaml code like that. Unoptimised but well-written OCaml/C/C++ is 2.5-2.8x faster than the fastest Python so far whilst also requiring about half as much code. Optimising the C++ by hoisting the O(log n) temporary array allocations into one allocation makes it another 20% faster. I'm sure there are plenty more optimisations... There aren't any complicated types in the above code. In fact, there are only two types: float and float array. You're vastly underestimating the complexity of numpy objects. They have an awful lot going on under the covers to make it look simple on the surface. There's all kinds of type-checking and type-conversions. A JIT that folds loops together would have to have knowledge of that process, and it's a lot of knowledge to have. That is not easy. My suggestion doesn't really have anything to do with numpy. If you had such a JIT you wouldn't use numpy in this case. 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). I was referring to the slicing specifically, nothing to do with functional programming. My F# and OCaml code are now basically identical to the C++ code. It is pretty strong thing to say that anything is fundamentally bad just because it's not fast as something else. Fundamental badness ought to run deeper than some superficial, linear measure. The slice based approach is not only slower, it is longer, more obfuscated and more difficult to optimise. That doesn't just apply to Python and numpy, it also applies to Matlab, Mathematica etc. Which begs the question, if you were writing in a compiled language like F# would you ever use slices? Now, I was going to write the program in Python, and use the very convenient numpy to do the transformation part. What makes numpy convenient? No problem, numpy will be fast enough for my needs. Ok. But you'd rather have a compiler? But wait! It's silly try to optimize code in a fundamentally slow language! It's vanity to even try! I guess for the sake of getting this little D4 transform to double in speed C++ is currently 3.4x faster than Python. I'll scrap Python and write the whole thing in OCaml. Why not drop to C for this one function? [snip] This is really great work but I can't help but wonder why the authors chose to use Python when other languages seem better suited. I'd like to work on raising people's awareness of these alternatives, and probably create some useful tools in the process. So I'm keen to learn what Python programmers would want/expect from F# and OCaml. What would it take to make you convert? Them not being functional would be a good start They don't impose functional programming on you. -- Dr Jon D Harrop, Flying Frog Consultancy Objective CAML for Scientists http://www.ffconsultancy.com/products/ocaml_for_scientists -- http://mail.python.org/mailman/listinfo/python-list
Using win32gui.SendMessage and SysListView32 control
Hope someone can steer me in the right direction. I am trying to use python to collect the values from a Win32 application's control. I can successfull query an retreive the values ListBox, Edit and Buttons, however, the application uses a control called a 'SysListView32' Control. MSDN says that this descends from CListView control and the msdn website reference for this control is; http://msdn2.microsoft.com/en-gb/library/ms670560.aspx (scroll to the message constants) This page seems to imply that the control can be queried with messages, however, my problem seems to be that pywin32.win32con does not define a constant for the LVM series of messages. Any other suggestions ?? I am looking for something similar to code below which does a fine job of collecting all of the text values from a ListBox control; count = win32gui.SendMessage(hndl,win32con.LB_GETCOUNT) vals = [] for i in range(count): strlen = win32gui.SendMessage(hndl,win32con.LB_GETTEXTLEN) text = ' '*(strlen+1) #Buffer for returned text -50 characters lentext = win32gui.SendMessage(hndl,win32con.LB_GETTEXT,i,text) txt = text[0:lentext] print Hndl: %8s Class: %-10s TxtLen:%3s TxtVal: %s% (hndl,clname,lentext,txt) vals.append(txt.strip()) Thanks in advance. -- http://mail.python.org/mailman/listinfo/python-list
Re: Deleting from a list while iterating
Rhamphoryncus schrieb: This is different from the other approaches in that it doesn't modify items. If you wanted a new list, you could incrementally build one already in the first pass, no need to collect the indices first (as BlackJack explains). I didn't feel this distinction was worth mentioning, since oldlist[:] = newlist is so trivial. The only solution that really avoids making a copy is the reverse-iteration one. The distinction is relevant for performance, as the slice assignment has a complexity linear with the number of elements. Whether making a copy is expensive depends on the precise data: the solution that makes the copy in reverse may have quadratic complexity (if the number of removed elements increases with the list size); the version that appends all remaining elements to a new list and then does slice assignment should behave better-than-quadratic (in recent versions, it should give you linear performance). Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: please provide urls for some python success stories.
Hello Krishnakant There is a book Python success stories. Download the 2 volumes from here http://pythonology.org/success If you want to convince java programmers to use python, show them this presentation from PyCon2003 The seven habits of highly effective technology disruption www.infoether.com/~rich/pycon2003.pdf It shows how to use MSAgent technology in java. Don't forget to tell them about Jython - Everyone is raving about the all-new Yahoo! Mail beta.-- http://mail.python.org/mailman/listinfo/python-list
Thread error
Hi guys, when I close the application I get the following error: - Traceback (most recent call last): File main.py, line 88, in module while exit : pass KeyboardInterrupt Unhandled exception in thread started by Error in sys.excepthook: Original exception was: - This is the code: - # Echo client program import socket import sys import thread import mtalk HOST = '192.168.0.115'# The remote host PORT = 3580 # The same port as used by the server buff = buffStatus = 0 s = None exit = 1 ### keywordDataIn ### def keywordDataIn(): global buff, buffStatus, exit talkmsg = mtalk.TalkMessage() while exit: line = sys.stdin.readline() if line == 'quit\n': exit = 0 break elif line != '\n': lock.acquire() buff = talkmsg.Make(line) buffStatus = 1 lock.release() elif line == '\n': pass ### dataToServer ### def dataToServer(): global buff, buffStatus, exit while exit: if buffStatus == 1: try: lock.acquire() s.sendall(buff) buff = buffStatus = 0 lock.release() except: socket.error pass # errore da controllare ## dataFromServer ## def dataFromServer(): global exit while exit: data = s.recv(1024) print 'Received', repr(data) ### Main ### if __name__ == __main__ : for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socket.SOCK_STREAM): af, socktype, proto, canonname, sa = res buffStatus = 0 try: s = socket.socket(af, socktype, proto) except socket.error, msg: print(Unexpected error) s = None sys.exit(1) try: s.connect(sa) print 'Connection ...' except socket.error, msg: print(The server was not reachable) s.close() s = None sys.exit(1) print 'Connected' # mutex lock = thread.allocate_lock() thread.start_new_thread(keywordDataIn, ()) thread.start_new_thread(dataToServer, ()) thread.start_new_thread(dataFromServer, ()) while exit : pass s.close() - Tnx -- http://mail.python.org/mailman/listinfo/python-list
Re: Using win32gui.SendMessage and SysListView32 control
[EMAIL PROTECTED]: This page seems to imply that the control can be queried with messages, however, my problem seems to be that pywin32.win32con does not define a constant for the LVM series of messages. These are defined in win32/lib/commctrl.py in my installation. Neil -- http://mail.python.org/mailman/listinfo/python-list
Re: problem formatting dates from text fields.
Dennis Lee Bieber wrote: On Mon, 4 Dec 2006 01:11:30 +0530, krishnakant Mane [EMAIL PROTECTED] declaimed the following in comp.lang.python: I am tired searching for some good tutorial that can explain the basic functionality of wx.datetime class and the datetime picker. I want to display the date in dd/mm/ format and allow the user to change the dates. Simplest is probably to do what many web-sites use for credit card expiration dates... Ignore any pre-built date-time modules... Create three integer fields, make the first two drop-down lists pre-populated with days and months. And validate the results later (just to cover someone putting in 31 02 ). My 2 cents worth: (1) this annoys the bejaysus out of data inputters who can type 31\t12 a lot faster than they can pick it out of two drop-down lists. (2) this would annoy the bejaysus out of data users if they were aware of the extent of off-by-one errors caused by using drop-down lists. Cheers, John -- http://mail.python.org/mailman/listinfo/python-list
Interface Designer
Hi list! I'm starting to program in python, i need a soft interface designer and adapt this interface to python. Somebody can help me with this? Sorry, my english is very bad. Regards to all. -- http://mail.python.org/mailman/listinfo/python-list
Re: Using win32gui.SendMessage and SysListView32 control
[EMAIL PROTECTED] schrieb: Hope someone can steer me in the right direction. I am trying to use python to collect the values from a Win32 application's control. I can successfull query an retreive the values ListBox, Edit and Buttons, however, the application uses a control called a 'SysListView32' Control. MSDN says that this descends from CListView control and the msdn website reference for this control is; http://msdn2.microsoft.com/en-gb/library/ms670560.aspx (scroll to the message constants) This page seems to imply that the control can be queried with messages, however, my problem seems to be that pywin32.win32con does not define a constant for the LVM series of messages. All the relevant message ids are in comCtl.h a 340k file. This might explain why win32con does only cover some ids. Best is to download and install the platform sdk, wich you may get for free from Microsoft. It comes shipped along with all the headers and the complete documentation for all the apis windows offers the dedicated programmer. http://www.microsoft.com/downloads/details.aspx?familyid=0BAF2B35-C656-4969-ACE8-E4C0C0716ADBdisplaylang=en And ...just a hint, check the ctypes module, wich will give you full access to all the apis windows has to offer and lets you translate C code almost 1:1 to python. Regards Jürgen -- http://mail.python.org/mailman/listinfo/python-list
Re: About alternatives to Matlab
Jon Harrop wrote: Carl Banks wrote: 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 [snip] 1.57s Python (in-place) So, optimized Python is roughly the same speed as naive Ocaml optimized Ocaml is roughly the same speed as C++ Absolutely not: Optimized Python is 14% slower than badly written OCaml. I'd call that roughly the same speed. Did you use any sort of benchmark suite that miminized testing error, or did you just run it surrounded by calls to the system timer like I did? If the latter, then it's poor benchmark, and 10% accuracy is better than you can expect. (Naive tests like that tend to favor machine code.) Given the problem, rather than the Python solution, nobody would write OCaml code like that. Unoptimised but well-written OCaml/C/C++ is 2.5-2.8x faster than the fastest Python so far whilst also requiring about half as much code. Frankly, I have a hard time believing anyone would naively write the Ocaml code like the optimized version you posted. You'd know better than I, though. Optimising the C++ by hoisting the O(log n) temporary array allocations into one allocation makes it another 20% faster. I'm sure there are plenty more optimisations... There aren't any complicated types in the above code. In fact, there are only two types: float and float array. You're vastly underestimating the complexity of numpy objects. They have an awful lot going on under the covers to make it look simple on the surface. There's all kinds of type-checking and type-conversions. A JIT that folds loops together would have to have knowledge of that process, and it's a lot of knowledge to have. That is not easy. My suggestion doesn't really have anything to do with numpy. If you had such a JIT you wouldn't use numpy in this case. 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. I was referring to the slicing specifically, nothing to do with functional programming. My F# and OCaml code are now basically identical to the C++ code. It is pretty strong thing to say that anything is fundamentally bad just because it's not fast as something else. Fundamental badness ought to run deeper than some superficial, linear measure. The slice based approach is not only slower, it is longer, more obfuscated and more difficult to optimise. That doesn't just apply to Python and numpy, it also applies to Matlab, Mathematica etc. 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. If it was critical for it to be fast, then I'd pull out the stops and write it as efficiently as possible. In my experience, a typical middle size program will have half a dozen or so subroutines where it's critical to be as fast as possible. 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. Now, I was going to write the program in Python, and use the very convenient numpy to do the transformation part. What makes numpy convenient? It's in Python, it's almost always fast enough, it's clean, it scales up well, it expresses mathematical concepts straightforwardly, it's well suppported, it has useful advanced functionality built in (linear algebra, etc.). And a lot of the time, you don't have to worry about indexing. 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. 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. But wait! It's silly try to optimize code in a fundamentally slow language! It's vanity to even try! I guess for the sake of getting this little D4 transform to double in speed C++ is currently 3.4x faster than Python. Oh, well *that* made all the difference. I'll
Re: evaluating gui modules, any experience on tkinter?
Tkinter is lame, but it works everywhere and is what I keep coming back to despite my many complaints about it. If youre application can be fit into a web porgramming framework, that may well be the best way to go. Your browser can probably render a better gui than any of the other frameworks can. Cheers, -T -- http://mail.python.org/mailman/listinfo/python-list
Re: About alternatives to Matlab
Carl Banks wrote: Optimized Python is 14% slower than badly written OCaml. I'd call that roughly the same speed. Did you use any sort of benchmark suite that miminized testing error, or did you just run it surrounded by calls to the system timer like I did? System timer, best of three. If the latter, then it's poor benchmark, and 10% accuracy is better than you can expect. (Naive tests like that tend to favor machine code.) Yes, they are roughly the same speed. My objection was that this OCaml program was not the unoptimised one, it was the badly written one. The unoptimised OCaml/F#/C++ are all several times faster than this OCaml, and much shorter and simpler too. Unoptimised but well-written OCaml/C/C++ is 2.5-2.8x faster than the fastest Python so far whilst also requiring about half as much code. Frankly, I have a hard time believing anyone would naively write the Ocaml code like the optimized version you posted. That wasn't optimised. I haven't optimised any of my solutions. The OCaml I posted was a naive convolution with some unnecessary allocation. You'd know better than I, though. When asked to convolve an array with a 4-element array (h0..h3), I think most programmers would write (pseudocode): for i in [0 .. n-4] x[i] = h0 y[i] + h1 y[i+1] + h2 y[i+2] + h3 y[i+3] in most languages. That is the essence of this benchmark. You can express it even more succinctly with a dot product: for i in [0 .. n-4] x[i] = h . y[i:] In this case, you'd want a cyclic array type too. 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? 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. 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). 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. 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. 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. Why not drop to C for this one function? Why would I? The assumptions clearly stated that numpy is fast enough. Why would I take several hours to write a C extension when I could do it with numpy in about 20 minutes, *and it's fast enough*? Is it very difficult to interface Python to other languages efficiently? But let me offer you some advice: if you wan't to lure people from Python, speed isn't going to cut it. Most people who chose Python (and, let's face it, most people who use Python chose it themselves) already knew it
Python library for reading ODF Spreadsheets
Hi all, I have had a look on google/freshmeat etc. so please forgive me if I've missed an obvious answer. Can someone point me to a simple library to read/write ODF spreadsheets (i.e. OpenOffice Calc 2). I know I can interface with OOo but this is running on a server where I would rather avoid a full-on library. Something like http://sourceforge.net/projects/pyexcelerator/ but for reading ODF. I have found write only solutions - but no read library except for the full Monte OOo/UNO which I want to avoid. Please, please help. Or the pragmatist in me will be forced to use XLS to get this job done. Thanks in advance for any help. Jonny (I'm not on the list. Please CC me answers). -- Jonathan Hunt [EMAIL PROTECTED] Website: http://www.me.net.nz (PGP Public Key available there) Ph: +6463535975 Mob: +64212106185 Work: +6463505799x3529 He is no fool who gives what he cannot keep to gain what he cannot lose. Jim Elliot pgpF114vbyRQI.pgp Description: PGP signature -- http://mail.python.org/mailman/listinfo/python-list
Re: Python library for reading ODF Spreadsheets
On 4/12/2006 10:18 AM, Jonathan Hunt wrote: Hi all, I have had a look on google/freshmeat etc. so please forgive me if I've missed an obvious answer. Can someone point me to a simple library to read/write ODF spreadsheets (i.e. OpenOffice Calc 2). I know I can interface with OOo but this is running on a server where I would rather avoid a full-on library. Something like http://sourceforge.net/projects/pyexcelerator/ but for reading ODF. I have found write only solutions - but no read library except for the full Monte OOo/UNO which I want to avoid. Please, please help. Or the pragmatist in me will be forced to use XLS to get this job done. Thanks in advance for any help. There is no such library as you describe. Jonny (I'm not on the list. Please CC me answers). Such a request is usually considered to be impertinent bludging and is likely to get you *no* answers. Consider subscribing to the list and reading it. Alternatively you could use a newsreader pointed at news:comp.lang.python or a browser pointed at http://groups.google.com/group/comp.lang.python. HTH, John -- http://mail.python.org/mailman/listinfo/python-list
Re: ftputil upload error
On Sat, 02 Dec 2006 04:03:53 -0800, Croteam wrote: FTPIOError: 550 popravak.txt: Access is denied. Seems pretty self-explanatory to me. M -- http://mail.python.org/mailman/listinfo/python-list
Why not just show the out-of-range index?
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? -- 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 you have a point. I am curious to see how far people are willing to go to defend this omission. It promises to be entertaining. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Why not just show the out-of-range index?
James Stroud wrote: 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 you have a point. I am curious to see how far people are willing to go to defend this omission. It promises to be entertaining. Add Syntax Error: invalid syntax to the list ... -- http://mail.python.org/mailman/listinfo/python-list
Re: Why not just show the out-of-range index?
James Stroud wrote: 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 you have a point. I am curious to see how far people are willing to go to defend this omission. It promises to be entertaining. I'm not sure that anybody is going to defend it as a deliberate omission. Rather, they (like I) will encourage to OP to submit a patch that fixes the problem. -- 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: Parsing data from pyserial
On Sun, 03 Dec 2006 18:44:07 -, Grant Edwards [EMAIL PROTECTED] wrote: On 2006-12-03, Si Ballenger [EMAIL PROTECTED] wrote: In my dealing with serial gizmos I have to put a delay between the request sent to the gizmo and the reading of the serial input buffer for returned data. Serial ports and gizmos need some time to do their thing. I doubt that's the issue. He's reading with a 1-second timeout value. I would think a time delay would be needed between the below two lines in the code if he expects to get a useable data string back from the gizmo for the command sent to it. ser.write(TC 016 240 100 240 016 240\r\n) reading = ser.read(40) No. A delay isn't needed as long as the device responds within 1 second. The read() call will wait up to 1 second for the first byte of the response. Per what was posted (below), it appears that the the appropriate data is being received. It may be possible that the cam may be sending in a mode that is not in alignment with the binary transmission mode of the serial port. As a test I'd jumper between the Tx and Rx pin on the serial port and then send out the M line being received, then see if it will parse as expected. Here is an example output: M 37 79 3 4 59 124 86 25 ['59', '123', '87', '25', 'M', '37', '79', '3', '4', '59', '124', '86', '25', 'M '] M 38 77 3 2 59 124 86 25 ['39', '85', '26', 'M', '38', '77', '3', '2', '59', '124', '86', '25', 'M', '38' , '7'] -- http://mail.python.org/mailman/listinfo/python-list
Re: How to realize the interactive python in Eclipse?
purple wrote: I have installed the Eclipse and the plug-in Pydev. Also, I have add an python program in the external tools. When I run the python program in the external tools, i can type python command just like in the python shell.But when I finished running a python file, in the console, I could not type any command to check some argument generated in the process. Is there any way I can make it? thank you~~ I am beginning to wonder if you attempting to use PyDev as nothing more than a programmer's editor. PyDev is a lot more. You need not debug this way since it includes a visual debugger. Be sure to read the documentation at the web site. http://pydev.sourceforge.net/debug.html http://pydev.sourceforge.net/faq.html -- http://mail.python.org/mailman/listinfo/python-list
Re: Why not just show the out-of-range index?
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, 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. -- http://mail.python.org/mailman/listinfo/python-list
Re: problem formatting dates from text fields.
On 04/12/06, Dennis Lee Bieber [EMAIL PROTECTED] wrote: You don't show us what format is used in the database, so there is nothing to base a conversion on. Is it year/month/day, month/day/year; months numeric or alpha (abbreviated or spelled out). Fields separated by space, comma, -, :, or / the format in the text field is dd/mm/ which is perfect for what I need. but the problem as I said is to get this text into a value that can fit into a date time picker. can this be done? Krishnakant. -- http://mail.python.org/mailman/listinfo/python-list
Re: Parsing data from pyserial
Si Ballenger wrote: Per what was posted (below), it appears that the the appropriate data is being received. [snip] Here is an example output: M 37 79 3 4 59 124 86 25 ['59', '123', '87', '25', 'M', '37', '79', '3', '4', '59', '124', '86', '25', 'M '] M 38 77 3 2 59 124 86 25 ['39', '85', '26', 'M', '38', '77', '3', '2', '59', '124', '86', '25', 'M', '38' , '7'] Based on the split() results (presumably much more reliable than the print reading results) what appears to me is: fragment '59', '123', '87', '25' packet 'M', '37', '79', '3', '4', '59', '124', '86', '25' fragment 'M', '39' [see note] fragment '85', '26' packet 'M', '38', '77', '3', '2', '59', '124', '86', '25', fragment 'M', '38' [note] the 39 obviously aligns with the 37 and 38s, not with the 123 and 124s. However the boundary of the 2 split() results lies before the 39, not after. Puzzling. In any case, I wouldn't call that the appropriate data is being received -- looks like chunks missing to me. -- http://mail.python.org/mailman/listinfo/python-list
trouble with matplotlib
Hi, I am using matplotlib with python to generate a bunch of charts. My code works fine for a single iteration, which creates and saves 4 different charts. The trouble is that when I try to run it for the entire set (about 200 items) it can run for 12 items at a time. On the 13th, I get an error from matplotlib that says it can't access data. However, if I start the program at the point it failed before it works fine and will create the charts for the next 12 before failing. I assume that I am not closing the files properly somehow or otherwise misallocating memory. This is the function that creates a chart: #create and save the figure def CreateFigure(state, facility, unit, SO2, increment, year, P99): size = len(SO2) #Create Plot figure(1, figsize=(10,8)) bar(range(1, size+2), SO2, width=0.1, color='k') grid(True) xlim(0,size) ylim(0, 1.1*SO2[-1]) ylabel('SO2 [lb/hr]') heading = ConstructFigName(state, facility, unit, increment, year) title(heading) #set handles xticklines = getp(gca(), 'xticklines') xgridlines = getp(gca(), 'xgridlines') xticklabels = getp(gca(), 'xticklabels') yticklines = getp(gca(), 'yticklines') #set properties setp(xticklines, visible=False) setp(xgridlines, visible=False) setp(xticklabels, visible=False) setp(yticklines, visible=False) axhspan(P99, P99, lw=3, ec='r', fc='r') ax = gca() #P99 = str(P99) P99 = '%0.1f' % P99 text(0.01, 0.95, '99th Percentile: '+P99+' lb/hr', transform=ax.transAxes) figpath = ConstructFigPath(state, facility, unit, increment, year) savefig(figpath) close() Can you see the problem? thanks, -Lisa -- http://mail.python.org/mailman/listinfo/python-list
Re: Joining data from three different files to be written into three Columns
Everything works in my program except for when it prints out the number is surrounded by brackets but I need to print the number without the brackets. Does anyone know an easy way to do this? #!/usr/bin/env python import array fin = open('relative_x.INT32','rb') fin1=open('relative_y.INT32','rb') fin2=open('income.INT32','rb') outfile=open('test.txt','w') data=[] data1=[] data2=[] while True: try: myInts=array.array('l') myInts.fromfile(fin,1) data.append(myInts.tolist()) myInts1=array.array('l') myInts1.fromfile(fin1,1) data1.append(myInts1.tolist()) myInts2=array.array('l') myInts2.fromfile(fin2,1) data2.append(myInts2.tolist()) data3=zip(data,data1,data2) except EOFError: break for record in data: print record[0],record[1],record[2] thanks Dawn -- http://mail.python.org/mailman/listinfo/python-list
Re: How to realize the interactive python in Eclipse?
Thank you for your website. I used to work with the python shell, but it is quite boring in managing the files, so I know the eclipse and pydev. I think I should focus on the documentations first. Thank you very much. I am beginning to wonder if you attempting to use PyDev as nothing more than a programmer's editor. PyDev is a lot more. You need not debug this way since it includes a visual debugger. Be sure to read the documentation at the web site. http://pydev.sourceforge.net/debug.html http://pydev.sourceforge.net/faq.html -- http://mail.python.org/mailman/listinfo/python-list
Re: Why not just show the out-of-range index?
John Machin wrote: James Stroud wrote: 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 you have a point. I am curious to see how far people are willing to go to defend this omission. It promises to be entertaining. Add Syntax Error: invalid syntax to the list ... But at least if you're using IDLE, the point of syntax error is highlighted. When I was a programmer, I thought as a programmer, I spake as a programmer and I understood as a programmer. But when I became a User, I put away such childish things. -- http://mail.python.org/mailman/listinfo/python-list
Parsing data from pyserial, an (inefficient) solution
I want to thank everybody who tried to help me, and also to post my solution, even though I dont think it is a very good one. Many of you correctly guessed that there was an \r included with the packet from the CUMcam, and you were correct. The actual format of the packet is: M xxx xxx xxx xxx xxx xxx xxx xxx\r. Unfortunately, splitting the packet using \r wouldnt help because the format of the data stream that I get with the components variable (after I split the reading file according to M) generally doesnt include a complete packet at first. For example, I get: [xxx xxx xxx\r, yyy yyy yyy yyy yyy yyy yyy yyy/r, zzz zzz zzz] Therefore, data from before the first \r (which I have shown as xxx) generally is incomplete and I need to go on to the second packet. Also, for those of you who suggested some kind of delay before reading the serial port, you were right. The first packet from the CMUcam is always a null. Anyway, here is my code: # This program reads a serial port hookup up to a CMUcam version 1. # It tracks the middle of a green object and provides a confidence estimate import serial ser=serial.Serial('com1',baudrate=115200, bytesize=8, parity='N', stopbits=1,xonxoff=0, timeout=1) ser.write(TC 016 240 100 240 016 240\r\n) #This line orders the CMUcam to track green reading = ser.read(40) # CMUcam's first data packet is null, so this line gets it out of the way for i in range(0,100,1): reading = ser.read(40) components = reading.split(M) components = components[1] if len(components) 23: # If shorter than 24 it won't have enough data for a full packet subcomponents = components.split() mx = int(subcomponents[0]) my = int(subcomponents[1]) confidence = int(subcomponents[7]) print mx, my, confidence ser.close 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 doesnt do anything to rearrange the data, then the CMUcam must do the heavy lifting of extracting a perfect packet from the data stream. Its a real shame I couldnt use it because the program would be more efficient. FWIW, this code will analyze 2-3 frames per second on my computer, which is enough for my purposes. In case you couldnt tell from the questions/code, I am a total beginner, and I really appreciate this list. All I needed was a hand, not a handout. Wolves are willing to hunt for their supper. Get your own 800 number Voicemail, fax, email, and a lot more http://www.ureach.com/reg/tag -- http://mail.python.org/mailman/listinfo/python-list
Re: trouble with matplotlib
One hack could be to reload the module on each pass. Cheers, -T [EMAIL PROTECTED] wrote: Hi, I am using matplotlib with python to generate a bunch of charts. My code works fine for a single iteration, which creates and saves 4 different charts. The trouble is that when I try to run it for the entire set (about 200 items) it can run for 12 items at a time. On the 13th, I get an error from matplotlib that says it can't access data. However, if I start the program at the point it failed before it works fine and will create the charts for the next 12 before failing. I assume that I am not closing the files properly somehow or otherwise misallocating memory. This is the function that creates a chart: #create and save the figure def CreateFigure(state, facility, unit, SO2, increment, year, P99): size = len(SO2) #Create Plot figure(1, figsize=(10,8)) bar(range(1, size+2), SO2, width=0.1, color='k') grid(True) xlim(0,size) ylim(0, 1.1*SO2[-1]) ylabel('SO2 [lb/hr]') heading = ConstructFigName(state, facility, unit, increment, year) title(heading) #set handles xticklines = getp(gca(), 'xticklines') xgridlines = getp(gca(), 'xgridlines') xticklabels = getp(gca(), 'xticklabels') yticklines = getp(gca(), 'yticklines') #set properties setp(xticklines, visible=False) setp(xgridlines, visible=False) setp(xticklabels, visible=False) setp(yticklines, visible=False) axhspan(P99, P99, lw=3, ec='r', fc='r') ax = gca() #P99 = str(P99) P99 = '%0.1f' % P99 text(0.01, 0.95, '99th Percentile: '+P99+' lb/hr', transform=ax.transAxes) figpath = ConstructFigPath(state, facility, unit, increment, year) savefig(figpath) close() Can you see the problem? thanks, -Lisa -- http://mail.python.org/mailman/listinfo/python-list
Re: Why not just show the out-of-range index?
[EMAIL PROTECTED] wrote: John Machin wrote: Add Syntax Error: invalid syntax to the list ... But at least if you're using IDLE, the point of syntax error is highlighted. Same when using the interactive interpreter, the point of syntax error is highlighted with a caret. However the highlighting of WHERE is useless to people who don't have a clue WHAT the error is, and it needs a forensic guru to suss it out as for example Peter Otten did, only yesterday: Are you perhaps mixing tabs and spaces? def f(): ... print hello # four spaces before 'print' ... return 42 # one tab before 'return' File stdin, line 3 return 42 ^ SyntaxError: invalid syntax -- http://mail.python.org/mailman/listinfo/python-list
Re: Why not just show the out-of-range index?
Russ 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, 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! And I believe that answers your original question. PS: begging for a fix on comp.lang.python is even less likely to get the developer's attention than posting a patch. They listen to patch submissions much more than comp.lang.python. At the very least, you should submit a bug report even if you don't want to take the opportunity to learn how to fix it yourself. -- 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: Parsing data from pyserial
On 3 Dec 2006 17:33:59 -0800, John Machin [EMAIL PROTECTED] wrote: In any case, I wouldn't call that the appropriate data is being received -- looks like chunks missing to me. Well, below is the posted expected return data format from the cam and below that is what has been reported to be returned from the cam when it is polled, which appears to be a fairly reasonable match. I assume that each xxx is a decimal number repersenting a single byte. In the binary mode each x in the string might be considered a byte in itelf and possibly evaluated as such. Anyhow it should be easy to see if the received string can be parsed on it own correctly when not being received via the serial port. That would start to narrow down where something not understood is comming into play. M xxx xxx xxx xxx xxx xxx xxx xxx M 37 79 3 4 59 124 86 25 -- http://mail.python.org/mailman/listinfo/python-list
ANN: UliPad 3.6 released!
What's it? It's an Editor based on wxPython. UliPad(NewEdit is the old name) uses Mixin and Plugin technique as its architecture. Most of its classes can be extended via mixin and plugin components, and finally become an integrity class at creating the instance. So UliPad is very dynamic. You can write the new features in new files, and hardly need to modify the existing code. And if you want to extend the existing classes, you could write mixins and plugins, and this will be bound to the target class that I call Slot Class. This technique will make the changes centralized and easily managed. What's new in 3.6 == New features and improvement: #. Improve definition jump, and if there is no ctag file exist, UliPad can jump in one source file, including: variable, class, method, etc #. Improve auto-completion: variable auto-detect, class structure detect, base class recognize, etc. And it can improve your typing. As you backspace something, auto-completion will also available. And you can also write parameter datatype in function docstring, UliPad will auto recognize the parameter datatype. #. Add range support for live regular expression search support #. Add pairprog plugin, it's a collaborative programming support. One instance can be a server, and others can be client. For server, you can share source file with all client, and both server and client can change the same document and move the caret. UliPad support multi-client. And it has a chatroom support, so developer can use it to talk with each other. #. Add fortran, and lua syntax support. For fortran you should enable fortran plugin. #. Improve the display structure and content of class browser #. Add css auto-completion support Changes: #. Improve class browser windown, and single-click on class icon will expand or collapse the children items #. Fix the bug of clicking on Cancel button on Python Parameter Input Dialog still running #. Fix reStructuredText syntax highlight processing bug #. Fix python syntax analysis bug #. Fix cann't restore the last directories entries as reopen the directory browser bug #. Fix if the filename or directory that you want to open command line window on it(on windows platform) is not the same hard driver, will open wrong path bug. #. Fix music plugin's bug #. Remove open recently-directory functionality #. Fix as changing the encode of the document, but the tab page title doesn't be changed bug Where to download it? download lastest version 3.6: http://wiki.woodpecker.org.cn/moin/UliPad?action=AttachFiledo=gettarget=ulipad_3.6.zip also have windows installer: http://wiki.woodpecker.org.cn/moin/UliPad?action=AttachFiledo=gettarget=UliPad.3.6.exe wiki: http://wiki.woodpecker.org.cn/moin/UliPad svn: http://cvs.woodpecker.org.cn/svn/woodpecker/ulipad/trunk maillist: http://groups.google.com/group/ulipad If you have any problem as using UliPad, welcome to join the UliPad maillist to discuss. Hope you enjoy it. ;-) -- I like python! UliPad The Python Editor: http://wiki.woodpecker.org.cn/moin/UliPad My Blog: http://www.donews.net/limodou -- http://mail.python.org/mailman/listinfo/python-list
Re: Why not just show the out-of-range index?
John Machin wrote: [EMAIL PROTECTED] wrote: John Machin wrote: Add Syntax Error: invalid syntax to the list ... But at least if you're using IDLE, the point of syntax error is highlighted. Same when using the interactive interpreter, the point of syntax error is highlighted with a caret. However the highlighting of WHERE is useless to people who don't have a clue WHAT the error is, and it needs a forensic guru to suss it out as for example Peter Otten did, only yesterday: Are you perhaps mixing tabs and spaces? def f(): ... print hello # four spaces before 'print' ... return 42 # one tab before 'return' File stdin, line 3 return 42 ^ SyntaxError: invalid syntax Well, more information would be better, but at least it's not as bad as Windows: Application xxx could not be started because a required file could not be found. I know the name of the file but I am not going to tell you what it is. -- http://mail.python.org/mailman/listinfo/python-list
Re: Parsing data from pyserial, an (inefficient) solution
Lone Wolf wrote: Your code has a problem when the first character of reading is 'M': you will miss the full packet and pick up a fragment. The length test that you are doing to reject the fragment is a kludge. If the average length of a packet is say 25, then you are throwing away 4% of all packets on average. Try this [untested]: reading = ser.read(40) # components = reading.split(M) # components = components[1] # if len(components) 23: # If shorter than 24 it won't have enough data for a full packet # subcomponents = components.split() pos_past_m = reading.index('M') + 1 subcomponents = reading[pos_past_m:].split() mx = int(subcomponents[0]) my = int(subcomponents[1]) confidence = int(subcomponents[7]) print mx, my, confidence The really sad thing is that I get a perfectly constructed packet from the reading variable, What we tell you three times is true, you are *NOT* getting a perfectly formed packet from the reading variable; you are getting 40 bytes of guff which will be long enough to contain a packet with possible stray fragments at either end. Do this: print len(reading) print repr(reading) and see for yourself. 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. Huh? I thought the CMUcam was *creating* the data stream -- how could it be *extracting* a perfect packet from it? It's a real shame I couldn't use it because the program would be more efficient. Somebody else gave you a clue: use the readline method instead of the read method; have you tried that? It's more likely to stop on a packet boundary that what you are doing. As far as starting on a packet boundary is concerned, have you explored your options with buffering and flow control? FWIW, this code will analyze 2-3 frames per second on my computer, which is enough for my purposes. In case you couldn't tell from the questions/code, I am a total beginner, and I really appreciate this list. All I needed was a hand, not a handout. Wolves are willing to hunt for their supper. Independence is one thing. Ignoring plausible truth told to you by multiple independent people with no axe to grind is another :-) HTH, John -- http://mail.python.org/mailman/listinfo/python-list
Re: About alternatives to Matlab
Jon Harrop wrote: Ok. Perhaps starting a Python JIT in something like MetaOCaml or Lisp/Scheme would be a good student project? I guess for a student project it's not that important, but if you have higher ambitions, make sure you read http://dirtsimple.org/2005/10/children-of-lesser-python.html before you commit to writing what will turn out to be yet another 80% Python VM / JIT compiler. George -- http://mail.python.org/mailman/listinfo/python-list
Re: Parsing data from pyserial
Si Ballenger wrote: On 3 Dec 2006 17:33:59 -0800, John Machin [EMAIL PROTECTED] wrote: In any case, I wouldn't call that the appropriate data is being received -- looks like chunks missing to me. Well, below is the posted expected return data format from the cam and below that is what has been reported to be returned from the cam when it is polled, which appears to be a fairly reasonable match. I assume that each xxx is a decimal number repersenting a single byte. In the binary mode each x in the string might be considered a byte in itelf and possibly evaluated as such. Anyhow it should be easy to see if the received string can be parsed on it own correctly when not being received via the serial port. That would start to narrow down where something not understood is comming into play. M xxx xxx xxx xxx xxx xxx xxx xxx M 37 79 3 4 59 124 86 25 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, flow control, etc. -- http://mail.python.org/mailman/listinfo/python-list
Re: Why not just show the out-of-range index?
On 3 Dec 2006 17:23:49 -0800, Russ [EMAIL PROTECTED] 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, 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! And I have some laundry that I would like you to do for me. Let me know when a convenient time for you to pick it up would be. Jean-Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Python library for reading ODF Spreadsheets
ODT is an XML format, so you can use any XML library, including the one in the default python distribution. It might be zipped XML in which case you will need to uncompress it first. -T John Machin wrote: On 4/12/2006 10:18 AM, Jonathan Hunt wrote: Hi all, I have had a look on google/freshmeat etc. so please forgive me if I've missed an obvious answer. Can someone point me to a simple library to read/write ODF spreadsheets (i.e. OpenOffice Calc 2). I know I can interface with OOo but this is running on a server where I would rather avoid a full-on library. Something like http://sourceforge.net/projects/pyexcelerator/ but for reading ODF. I have found write only solutions - but no read library except for the full Monte OOo/UNO which I want to avoid. Please, please help. Or the pragmatist in me will be forced to use XLS to get this job done. Thanks in advance for any help. There is no such library as you describe. Jonny (I'm not on the list. Please CC me answers). Such a request is usually considered to be impertinent bludging and is likely to get you *no* answers. Consider subscribing to the list and reading it. Alternatively you could use a newsreader pointed at news:comp.lang.python or a browser pointed at http://groups.google.com/group/comp.lang.python. HTH, John -- http://mail.python.org/mailman/listinfo/python-list
Re: Why not just show the out-of-range index?
Jean-Paul Calderone wrote: And I have some laundry that I would like you to do for me. Let me know when a convenient time for you to pick it up would be. What that has to do with this thread escapes me, but since you apparently have nothing better to do than track down information that should have been provided to you, it's no wonder you don't have enough time to do your own laundry. When you call information to get a phone number, do you first ask if they have the number, then call back a second time to get it if the answer is yes? If a policemen gives you a speeding ticket, do you expect him to tell you how fast he thinks you were going, or are you content to wait for the court date? Get your mother to do your laundry -- after she dresses you in the morning. -- http://mail.python.org/mailman/listinfo/python-list
Re: Why not just show the out-of-range index?
Russ 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, 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. But with that argument you just perpetuate the problem. It is the way it is because nobody has cared enough to make it different. That error message has certainly never bothered me enough to wish for something different. You may be able to prompt someone into changing it, but if we've gone this long without caring to fix it, then I'd not hold out much hope for that. Python and the whole open source movement is a volunteer effort by people who care enough to contribute. Your contributions would be welcome, but your complaints are likely to be ignored. Gary Herron -- http://mail.python.org/mailman/listinfo/python-list
Re: problem formatting dates from text fields.
is there a soft copy of wxpython in action available for free download? I saw the book on my book store but since I am totally blind, I have to depend on soft copies. Krishnakant. -- http://mail.python.org/mailman/listinfo/python-list
class property methods getting called only once
In the following code, I could not find out why the set and get methods are not called once I set the property. class Test: ... def __init__(self): ... self._color = 12 ... def _setcolor(self,value): ... print 'setting' ... self._color = value ... def _getcolor(self): ... print 'getting' ... return self._color ... color = property(_getcolor,_setcolor) ... a = Test() a.color getting 12 a.color = 22 a.color 22 For some reason the set method is not getting called at all, Anybody has any clue? thanks. -- Suresh -- http://mail.python.org/mailman/listinfo/python-list
Re: Why not just show the out-of-range index?
Jean-Paul Calderone wrote: On 3 Dec 2006 17:23:49 -0800, Russ [EMAIL PROTECTED] 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, 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! And I have some laundry that I would like you to do for me. Let me know when a convenient time for you to pick it up would be. Jean-Paul Perhaps a better analogy is that the OP has observed (correctly IMHO) that the robes of *all* Pythonistas, including those not yet born and those not yet converted from heathen languages, could be whiter than what they are. There are others whose capability to implement an enhancement is likely to be much greater than his. IOW, apart from being somewhat impolite, he may: * not be able to write C * not understand that apart from listobject.c, he might have to patch (OTTOMH) stringobject.c, tupleobject.c, arraymodule.c and who knows what else [see below] * not come up with a good message Would the following be acceptable, BTW? | [4, 5, 6][10] | IndexError: list index 10 out of range(3) | [4, 5, 6][-4] | IndexError: list index -4 out of range(3) or would something like ... out of range; len is 3 be better? Footnote: Based on 2.4.3 source, quite a few files, many with multiple lines to patch: C:\Python_source\Python-2.4.3\Objectsgrep -n index out of range *.c File bufferobject.c: 406 PyErr_SetString(PyExc_IndexError, buffer index out of range); 450 buffer assignment index out of range); File listobject.c: 144 list index out of range); 165 list assignment index out of range); 389 list index out of range); 693 list assignment index out of range); 881 PyErr_SetString(PyExc_IndexError, pop index out of range); File rangeobject.c: 143 xrange object index out of range); File stringobject.c: 1041PyErr_SetString(PyExc_IndexError, string index out of range); File structseq.c: 62 PyErr_SetString(PyExc_IndexError, tuple index out of range); File tupleobject.c: 104 PyErr_SetString(PyExc_IndexError, tuple index out of range); 123 tuple assignment index out of range); 310 PyErr_SetString(PyExc_IndexError, tuple index out of range); File unicodeobject.c: 5241PyErr_SetString(PyExc_IndexError, string index out of range); C:\Python_source\Python-2.4.3\Modulesgrep -n index out of range *.c File arraymodule.c: 599 PyErr_SetString(PyExc_IndexError, array index out of range); 767 array assignment index out of range); 997 PyErr_SetString(PyExc_IndexError, pop index out of range); File collectionsmodule.c: 399 deque index out of range); 461 deque index out of range); File mmapmodule.c: 648 PyErr_SetString(PyExc_IndexError, mmap index out of range); 736 PyErr_SetString(PyExc_IndexError, mmap index out of range); File regexmodule.c: 181 PyErr_SetString(RegexError, group() index out of range); File _heapqmodule.c: 19 PyErr_SetString(PyExc_IndexError, index out of range); 58 PyErr_SetString(PyExc_IndexError, index out of range); 136 PyErr_SetString(PyExc_IndexError, index out of range); 173 PyErr_SetString(PyExc_IndexError, index out of range); 310 PyErr_SetString(PyExc_IndexError, index out of range); 349 PyErr_SetString(PyExc_IndexError, index out of range); Cheers, John -- http://mail.python.org/mailman/listinfo/python-list
Re: problem formatting dates from text fields.
krishnakant Mane wrote: is there a soft copy of wxpython in action available for free download? I saw the book on my book store but since I am totally blind, I have to depend on soft copies. It is not available for free, no. However, it is available in PDF form from Manning's website: http://www.manning.com/rappin/ If their Yahoo store is not accessible via your web reader (I have no experience, so I won't depend on it), you can email the publisher's customer service at [EMAIL PROTECTED] and I'm sure they will get the book to you in a form you can read. -- 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: class property methods getting called only once
On 3 Dec 2006 21:24:03 -0800, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: In the following code, I could not find out why the set and get methods are not called once I set the property. class Test: ... def __init__(self): ... self._color = 12 ... def _setcolor(self,value): ... print 'setting' ... self._color = value ... def _getcolor(self): ... print 'getting' ... return self._color ... color = property(_getcolor,_setcolor) ... a = Test() a.color getting 12 a.color = 22 a.color 22 For some reason the set method is not getting called at all, Anybody has any clue? thanks. property can only be used in New Style Class. So you should write your Test as: class Test(object): And try again. -- I like python! UliPad The Python Editor: http://wiki.woodpecker.org.cn/moin/UliPad My Blog: http://www.donews.net/limodou -- http://mail.python.org/mailman/listinfo/python-list
Re: Why not just show the out-of-range index?
John Machin wrote: Perhaps a better analogy is that the OP has observed (correctly IMHO) that the robes of *all* Pythonistas, including those not yet born and those not yet converted from heathen languages, could be whiter than what they are. There are others whose capability to implement an enhancement is likely to be much greater than his. 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? And no, it's not a big deal, maybe it's even trivial, but after about the 100th time I finally decided to suggest that it be fixed. I started with comp.lang.python because I had no idea whether this issue had been dealt with already, but I am certainly willing to file a feature request if necessary. Would the following be acceptable, BTW? | [4, 5, 6][10] | IndexError: list index 10 out of range(3) | [4, 5, 6][-4] | IndexError: list index -4 out of range(3) That seems fine to me. Footnote: Based on 2.4.3 source, quite a few files, many with multiple lines to patch: Holy cow! I can't believe that many changes would be necessary unless the IndexError exception is scattered all over the place. I would hope that one well-placed change could fix the bulk of cases. Oh, and thanks for bringing your attention to this matter. This is one of those little issues that comes up so often that I think fixing it could make a significant difference in the overall efficiency of Python programming. -- http://mail.python.org/mailman/listinfo/python-list
Re: problem formatting dates from text fields.
John Machin [EMAIL PROTECTED] wrote: Dennis Lee Bieber wrote: 8-- Simplest is probably to do what many web-sites use for credit card expiration dates... Ignore any pre-built date-time modules... Create three integer fields, make the first two drop-down lists pre-populated with days and months. And validate the results later (just to cover someone putting in 31 02 ). My 2 cents worth: (1) this annoys the bejaysus out of data inputters who can type 31\t12 a lot faster than they can pick it out of two drop-down lists. (2) this would annoy the bejaysus out of data users if they were aware of the extent of off-by-one errors caused by using drop-down lists. Cheers, John This annoyance can be maximised if, after the selection, a pop up dialog window is displayed showing what was chosen, along with the following text: This is what you have chosen - Please indicate whether or not you wish to re try - with the focus on the yes button. and then, when yes is chosen, to start again without any attempt to remember the previously entered values - Hendrik -- http://mail.python.org/mailman/listinfo/python-list
Re: Video feature
Hello Tim, Thank you for your reply. Yes, my site uses Python. Do you have any idea how to add video playing ( video streaming feature)to my webiste? Thank you for help L. Tim Roberts wrote: Lad [EMAIL PROTECTED] wrote: I would like to add on my website a possibility for visitors to upload video and watch other user's video. How much difficult would it be with Python? It's not all that hard, although you can probably download something that will do most of the job, probably in PHP. Is your website already using Python? -- Tim Roberts, [EMAIL PROTECTED] Providenza Boekelheide, Inc. -- http://mail.python.org/mailman/listinfo/python-list
Re: A mail from Steve Ballmer. See what Microsoft will do and follow.
JustStand wrote: For detail, view http://www.homeoftester.com/viewtopic.php?t=281 __ I have a dream, I hope I can be as strong as Enter key. Does this pointless blogvertisement in anyway compensate for the fact that windows sucks so hard? James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Why not just show the out-of-range index?
On Sun, 3 Dec 2006 23:31:56 -0500, Jean-Paul Calderone [EMAIL PROTECTED] wrote: On 3 Dec 2006 17:23:49 -0800, Russ [EMAIL PROTECTED] 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, 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! And I have some laundry that I would like you to do for me. Let me know when a convenient time for you to pick it up would be. Jean-Paul Are you saying that you place such low value on feedback from Python users that you don't even want them to try and ask questions that might help to improve the language? In other words, if I'm not skilled or knowledgeable enough to improve something myself, I shouldn't even mention it? Bill -- http://mail.python.org/mailman/listinfo/python-list
RAD for python
is there a VB-alike tool for python to create forms?? -- http://mail.python.org/mailman/listinfo/python-list
algorithm for sorting functional expressions
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. 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. -- http://mail.python.org/mailman/listinfo/python-list
Re: Why not just show the out-of-range index?
Dennis Lee Bieber wrote: OTOH: IndexError is something I seldom see -- most Python statements are intelligent enough to not need ad hoc indexing. About the only type that I've seen is just an, almost obvious, off-by-one problem... for i in xrange(len(a)): a[i] = a[i] + a[i+1] in which knowing the discrete values isn't that significant (to me, at least) It doesn't occur in things like for itm in a: I agree that implicit indexing (your latter construct) is preferable to explicit indexing if the index is not needed for any other purpose. But sometimes the index itself is needed for some computation. And sometimes a list is randomly accessed without a loop at all. -- http://mail.python.org/mailman/listinfo/python-list
Re: Why not just show the out-of-range index?
Russ wrote: Holy cow! I can't believe that many changes would be necessary unless the IndexError exception is scattered all over the place. I would hope that one well-placed change could fix the bulk of cases. when you write x[i], the interpreter makes no assumptions about x and i and len(x); it just calls the corresponding method (__getitem__), either directly, or via a C-level internal slot. there's no way to generate the error message you want in a single place without changing the semantics of x[i]. /F -- http://mail.python.org/mailman/listinfo/python-list