CFP: PyCon 2006
PyCon 2006 Call for Proposals Want to share your expertise? PyCon 2006 is looking for proposals to fill the formal presentation tracks. PyCon 2006 will be held February 24-26 2006 in Addison, Texas (near Dallas). Previous PyCons have had a broad range of presentations, from reports on academic and commercial projects to tutorials and case studies, and we hope to continue that tradition this year. As long as the presentation is interesting and potentially useful to the Python community, it will be considered for inclusion in the program. For 2006, we're especially interested in tutorial presentations that will teach conference-goers something new and useful. Can you show attendees how to: use a module? explore a Python language feature? package an application? Important Dates == * Submission deadline: October 31, 2005 * Acceptance deadline: November 15, 2005 * Electronic copy deadline: February 15, 2006 PyCon Topics === Suitable topics for PyCon presentations include, but are not limited to: * Core Python * Other implementations: Jython, IronPython, PyPy, and Stackless * Python libraries and extensions * Databases * Documentation * GUI Programming * Game Programming * Network Programming * Open Source Python projects * Packaging Issues * Programming Tools * Project Best Practices * Embedding and Extending * Science and Math * Web-based Systems Submission Format Proposals should be 250 to 1000 words long (i.e., one to four pages in manuscript format), containing the following information: * Author name(s) * Contact Information * Requested timeslot (30 minutes, 45 minutes, or either) * Summary of proposed presentation * Presentation outline * Intended audience (non-programmers, beginning programmers, advanced users, CPython developers, etc.) ASCII format is preferred (plain or reST), with HTML as a secondary alternative. If you have any queries about submission, or if you would like to discuss the possibility of submitting in a different format or style, please send mail to the conference organizers at [EMAIL PROTECTED] Session lengths include time for audience questions. You should budget at least five minutes for questions; for example, a 30-minute talk will be 25 minutes of presentation and 5 minutes of questions. The preferred length for talks is 30 minutes. You can request a 45-minute slot, but proposals requiring 45 minutes will be reviewed more stringently and tutorial talks will be preferred for these longer slots. Submission Mechanics === Use the PyCon Online Proposal Submission http://submit.pycon.org to send us your proposals and ideas. If your proposal is accepted, you have the option of including a companion paper along with your presentation. The paper will get published on the PyCon web site. Presentations and papers may be in text (plain or reST), HTML, or PDF; HTML or text are preferred. We suggest, but do not require, that authors place their papers under a Creative Commons license. Please visit the CC 'Choose a License' page to select a license that meets your requirements. A Wiki page has suggestions and advice for speakers: http://wiki.python.org/moin/PyCon2006/SpeakerNotes Other Presentations === If you don't want to make a formal presentation, you can still bring your new project or idea to PyCon. There will be several Lightning Talk sessions for talks no longer than five minutes. There will be a significant amount of Open Space for informal and spur-of-the-moment presentations. Open Space consists of thirty-minute blocks that are allocated during PyCon. These blocks can be used for presentations, round table discussions, hands-on tutorials, or anything else. Typically, people propose ideas for the sessions which are then voted on by attendees. -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
pybwidget release 0.1.2
pybwidget is a Python wrapper around the 'bwidget' family of widgets for Tkinter. It includes these classes: Entry Label Button ArrowButton ProgressBar ScrollView Separator MainFrame LabelFrame TitleFrame PanelFrame ScrolledWindow ScrollableFrame PanedWindow ButtonBox PagesManager NoteBook Dialog StatusBar LabelEntry ComboBox SpinBox Tree ListBox MessageDialog ProgressDialog PasswordDialog SelectFont SelectColor I know it's been a long time, but I've finally gotten around to making a new release of pybwidget, called 0.1.2_1.7.0. It has all the fixes I could find that have been mentioned in the tkinter-discuss mailing list archives. Compared to 0.1.1, here's a summary of changes: * add ROOT as a module-level constant, as requested * bindtabs, bind_image, bind_text all handle the 'func' parameter properly * several instances of 'self.tl' corrected to 'self.tk' * the 'nodes' function of the Tree widget now passes all arguments to Tk * The xbm-format images are installed by setup.py * how to run setup.py is mentioned in README.html This release is available at http://tkinter.unpythonic.net/bwidget Please report your experiences, good or bad, on the Tkinter mailing list tkinter-discuss@python.org Jeff Epler [EMAIL PROTECTED] pgpidcZT87hcU.pgp Description: PGP signature -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
Re: round() wrong in Python 2.4?
Reinhold Birkenfeld wrote: Robert Kern wrote: Antoon: Python 2.3 isn't rounding 0.0225 up while pyton 2.4 rounds it down. Written in Pseudocode: not (Py2.3 rounding up and Py2.4 rounding down) I presumed the isn't was a typo given the while. -- Robert Kern [EMAIL PROTECTED] In the fields of hell where the grass grows high Are the graves of dreams allowed to die. -- Richard Harter -- http://mail.python.org/mailman/listinfo/python-list
Re: week-year conversion to date
Thanks! Both solutions worked perfectly. -- http://mail.python.org/mailman/listinfo/python-list
Re: round() wrong in Python 2.4?
Robert Kern wrote: Reinhold Birkenfeld wrote: Robert Kern wrote: Antoon: Python 2.3 isn't rounding 0.0225 up while pyton 2.4 rounds it down. Written in Pseudocode: not (Py2.3 rounding up and Py2.4 rounding down) I presumed the isn't was a typo given the while. Oh never mind. I'm sorry I started this line of conversation. -- Robert Kern [EMAIL PROTECTED] In the fields of hell where the grass grows high Are the graves of dreams allowed to die. -- Richard Harter -- http://mail.python.org/mailman/listinfo/python-list
Frivolous pursuit - automated game playing program
My son showed me this Flash game, Orbit (there are *many* links on the web out there for it, here's one for the Google-challenged: http://uploads.ungrounded.net/25/250408_orbit.swf), and it is *addicting*. Basically, you control a comet to traverse through the gravitational fields of randomly placed planets. Your only inputs are starting x,y location and starting direction and speed, defined by clicking, dragging, and releasing the mouse (imagine the click/mouseDown picks the starting location, the drag pulls a rubberbanded line from that spot, and the release/mouseUp begin's the comet's journey). The simulation looks quite pretty, and I can visualize the physics and math of the numerical simulation. I've been able to reach Level 18, that is up to 18 planets. (Note - this program doesn't solve the 3-body or n-body problem, it simply numerically simulates the system given a set of initial conditions. There is no random behavior here - the program retraces the exact same path given the same initial conditions.) The behavior is beautifully chaotic - small changes in the initial conditions can have large changes in the simulation results. I'm stuck at Level 18, but I would like to write a Python program to automate the trial-and-error playing of this game. Of course, once I have the technology to drive the game from a Python program, I can then build in optimization logic (gradient-following, Newton-Raphson, neural net, etc.), not just randomly click about the screen. Any suggestions on how I might write a Python program to: 1. automatically click-drag in another window 2. detect the running and completion of the simulation (the panel flashes when the comet collides with a planet) -- Paul -- http://mail.python.org/mailman/listinfo/python-list
Builtin classes list, set, dict reimplemented via B-trees
Nifty, Tim Peters responded to my e-mail. I must've said something interesting. Cool, a PyCelebrity! [barnesc at engr.orst.edu] ... I've gotten bored and went back to one of my other projects: reimplementing the Python builtin classes list(), set(), dict(), and frozenset() with balanced trees (specifically, counted B-trees stored in memory). In short, this allows list lookup, insertion, deletion in O(log(N)) time. It allows the set and dictionary types to be maintained in order, and insert/lookup/remove operations here take O(log(N)) time as well. Getting the k least or k greatest elements takes O(log(N)+k) time. Note that BTrees for Python have been part of ZODB for many years: Section 5.3, _BTrees Package_ http://www.zope.org/Wikis/ZODB/FrontPage/guide/node6.html If you install ZODB, you can use its BTrees as in-memory data structures without using any of the rest of ZODB. If you want to persist them, great, that's what ZODB is for. Note that ZODB's are really B+ trees, so iterating over the smallest k takes O(k) time. As an extension to Python's mapping protocol, the keys/values/items/iterkeys/itervalues/iteritems methods also accept optional lower and upper bounds on the keys to return. A gotcha: For scalability in multiprocess database apps, ZODB's BTrees do not store their size. As a result, len(a_ZODB_BTree) takes time linear in the number of elements. Thanks for the link! ... So my question is: are there any other *practical* applications of a B-tree based list/set/dict ? Yes. In other words, is this module totally worth coding, That's a different question entirely ;-) or is it just academic wankery and theoretical flim flam ? :) It's probably not a way to get rich quick. Well, the Tim Peters PyCelebrity experience was fun, but not quite as exhilarating as advertised. I'm not sure what to say. Did I get my money's worth? There were no winks, even a little sarcasm. I guess, overall, yeah it was cool, it was worthwhile, it was fun, man, it was a life-changing moment! Thanks for tuning in to PyCelebrity weekly. We're always glad to be part of your inexplicable existence in The Hostile And Indifferent Universe (Incorporated). Contributions come from hackers like you! Reporting live from Python-list, this is...Connelly Barnes. Next up: Startling photographs show that Guido van Rossum was KIDNAPPED BY ALIENS in 1990! Rumor has it that his superhuman language design skills are really due to neuroimplanted nanotube processors! -- http://mail.python.org/mailman/listinfo/python-list
Re: List of integers L.I.S. (SPOILER)
Thank you both for your replies. And my personal Thank you! to Mr. Hettinger for all his tremendous work! Perhaps because you are not using a real Usenet client? Yes! And I don't even know what is the beast - Usenet client. I just keep in Favorites of my browser (IE 6.0) this link: http://groups.google.com/group/comp.lang.python/ -- http://mail.python.org/mailman/listinfo/python-list
ddd or eclipse with mod_python
Hi I am using mod_python for web development, I am in need of some ide , can i use ddd or eclipse with pydev with mod_python. can these ide's handle requests from mod_python and run server side scripts any help or pointers are greatly appreciated thanks clive -- http://mail.python.org/mailman/listinfo/python-list
Hello everything
I have an application in tkinter, one button call to another window, but the position of this window is random, i' whish to ask at the list, if exist a function to put the window in x position of the screen, if exist, which function is it?... thanks in advanced... david -- http://mail.python.org/mailman/listinfo/python-list
Re: What XML lib to use?
Robert Kern wrote: His interpretation of your words is a perfectly valid one even in the context of this thread. in Python explicitly provides a context for the rest of the sentence. Exactly. in Python, not in an application with an existing API. (also, if the OP had been forced to use an existing API by external constraints, don't you think he would have mentioned it?) In English, at least, it is perfectly reasonable to presume that explicit contexts override implicit ones. Letting a part of a sentence override the context of the discussion is perhaps popular in certain tabloid journalist circles, and among slash- dot editors and US political bloggers, but most people do in fact have a context buffer memory that can hold more than a few words. (how come you're so sure I wasn't talking about, say, the Python Lisp com- piler? or the Monty Python sketch with the sadistic Belgian instrument- making monk? or a Harry Potter book?) I know what I meant. You know what I meant. Paul knows what I meant. If you still want to play the but there is a way to interpret this in another way game, file a bug report against the python.org what is python? summary page. /F -- http://mail.python.org/mailman/listinfo/python-list
Re: PyGTK or wXPython?
Magnus Lycka wrote: What OS(es) do yo need to support? My apps will mostly be run on Windows desktops, but there are some Linux users. I'm curious about PyGTK on Windows. It seems to me that the GTK+ Windows port is lagging behind a bit (no 2.8?), doesn't look or behave quite as native windows apps do, is clunky to install, and isn't as stable and complete as e.g. wxPython. Am I wrong? The GTK+ port is lagging behind on Windows (I think they have a 2.6 port). GTK+ doesn't look exactly like Windows, but the install is clean and easy - I use GIMP on Windows for graphic editing and it works just fine (it used to be worse) I'm leaning towards PyGTK because it seems less clunky than wxPython on wxWidgets. -- http://mail.python.org/mailman/listinfo/python-list
Re: Hello everything
David Pantoja wrote: I have an application in tkinter, one button call to another window, but the position of this window is random, i' whish to ask at the list, if exist a function to put the window in x position of the screen, if exist, which function is it?... try w.geometry(%+d%+d % (xoffset, yoffset)) or w.geometry(%dx%d%+d%+d % (width, height, xoffset, yoffset)) also see: http://smurl.name/w2s /F -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter add_cascade option_add
On Wed, 14 Sep 2005 09:58:25 -0600, Bob Greschke [EMAIL PROTECTED] wrote: Eric Brunel [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] On Tue, 13 Sep 2005 22:31:31 -0600, Bob Greschke [EMAIL PROTECTED] wrote: Root.option_add(*?*font, Helvetica 12 bold) Want to get rid of the font =: Widget.add_cascade(label = File, menu = Fi, font = Helvetica 12 bold) Does anyone know what ? should be to control the font of the cascade menus (the labels on the menu bar)? *Menu*font handles the part that drops down, but I can't come up with the menu bar labels part. option_add('*Menu.font', 'helvetica 12 bold') works for me for all sorts of menu items (cascade, commands, checkbuttons, whatever...). What is your platform? There may be a few limitations for menu fonts on Windows. You can set the font for the labels on the menu bar, and you can set the font of the items in the drop down portion independently (except on Windows where you cannot control the font of the menu bar labels). I just don't know how to set the font for the menu bar labels using an option_add command. ...option_add(*Menu*font, Helvetica 12 bold) works fine ...option_add(*Cascade*font, Helvetica 12 bold) does not, because I can't figure out what to put in for Cascade. There must be something, because I can use font = Helvetica 12 bold in the add_cascade command OK (see below). I'm still not sure what your exact requirements are. Do you want to have a different font for the menu bar labels and the menu items and to set them via an option_add? If it is what you want, I don't think you can do it: the menus in the menu bar are just ordinary items for tk, and you can't control separately the different kind of menu items. In addition, you can have cascade menus in regular menus, like in: -- from Tkinter import * root = Tk() menuBar = Menu(root) root.configure(menu=menuBar) fileMenu = Menu(menuBar) menuBar.add_cascade(label='File', menu=fileMenu) openRecentMenu = Menu(fileMenu) fileMenu.add_cascade(label='Open recent', menu=openRecentMenu) openRecentMenu.add_command(label='foo.txt') openRecentMenu.add_command(label='bar.txt') fileMenu.add_command(label='Quit', command=root.quit) root.mainloop() -- All menu items get the options you defined via option_add('*Menu.*', ...), whether they are cascade or commands or whatever. Not doing so would end up in quite weird results. To do what you seem to want, I'd create a custom class for menu bars like this: -- from Tkinter import * class MyMenuBar(Menu): def __init__(self, master, **options): Menu.__init__(self, master, **options) master.configure(menu=self) def add_cascade(self, **options): if not options.has_key('font'): options['font'] = ('helvetica', 14, 'bold') Menu.add_cascade(self, **options) root = Tk() menuBar = MyMenuBar(root) fileMenu = Menu(menuBar) menuBar.add_cascade(label='File', menu=fileMenu) openRecentMenu = Menu(fileMenu) fileMenu.add_cascade(label='Open recent', menu=openRecentMenu) openRecentMenu.add_command(label='foo.txt') openRecentMenu.add_command(label='bar.txt') fileMenu.add_command(label='Quit', command=root.quit) root.mainloop() -- This prevents you from putting the font=... option in all menus you create in your menu bar without the need for an option_add. HTH -- python -c print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17;8(%,5.Z65\'*9--56l7+-']) -- http://mail.python.org/mailman/listinfo/python-list
Pythonutils 0.2.2 , ConfigObj 4.0.0 Beta 5, odict 0.1.1
The response to pythonutils__ was very good. Especially the odict__ module (ordered dictionary) - it's had over one hundred and fifty downloads already. Thanks to some useful user feedback, Nicola Larosa has updated and improved it. More embarassingly we've done a bugfix release of ConfigObj__ - now up to beta 5. This fixes another couple of bugs - we aim to get out of beta someday.. All this is my way of saying that *odict 0.1.2*, *pythonutils 0.2.2*, and *ConfigObj beta 5*, are all available from the `Voidspace Modules`__ page. __ http://www.voidspace.org.uk/python/pythonutils.html __ http://www.voidspace.org.uk/python/odict.html __ http://www.voidspace.org.uk/python/configobj.html __ http://www.voidspace.org.uk/python/modules.shtml (The pythonutils update contains odict 0.1.1 *and* ConfigObj Beta 5) All the best, Fuzzyman http://www.voidspace.org.uk/python/ -- http://mail.python.org/mailman/listinfo/python-list
new in python
hello everyone : I'm new in python and I would like to know what is the capabilleties of this language.Please let me know and how I can make a program in python exe thanks alot -- http://mail.python.org/mailman/listinfo/python-list
Python in C integration and WxPython
Hi all, I made a small dialog in WxPython. I can run the python script with a double-click or through command line, and everything goes fine (dialog appears, which means that wx module has been found). Then, I decided to write a C program (under Windows, with Cygwin) that will read my script (through PyRun_SimpleFile() function) and run it. But the system doesn't find the wx module to import... Traceback (most recent call last): File Dialog.py, line 2, in ? import wx ImportError: No module named wx How can I say to my program where to search for this module ? I tried to set $PYTHONPATH and $PYTHONHOME, but this doesn't change anything. More generally : Does a C program that embedded python run an external executable (interpreter), or does it only load libraries ? Thank you very much for any help on this topic. Best regards. -- http://mail.python.org/mailman/listinfo/python-list
Re: some advice about Python GUI apps
Hi Kris, I used several GUI's, also wx. You should look at eric3, it's by far the best of all. http://www.die-offenbachs.de/detlev/eric3.html Eric3 uses Qt. Qt is also great with C++. I ported a major Python project from Windows to Linux under Python-Qt and encountered no problem whatsoever. I use eric3 with Novell/SuSE Pro 9.3. All you need is already there. Good luck, malv -- http://mail.python.org/mailman/listinfo/python-list
Re: Software bugs aren't inevitable
Paddy [EMAIL PROTECTED] writes: As I write, the main article starts here: http://www.spectrum.ieee.org/sep05/2164 With the sidebar here: http://www.spectrum.ieee.org/sep05/2164/extsb1 Thanks, the article is slightly interesting but it doesn't say much. I'm sure a lot more is going on than the article describes. And if they're so sure their Z specifications are correct, why can't they generate code from them automatically? I've heard stories like that told about Haskell. People have seen Haskell programs and thought they were simply formal specifications of some kind, and been surprised to find out that they were actual runnable programs. -- http://mail.python.org/mailman/listinfo/python-list
Re: new in python
blackfox505 [EMAIL PROTECTED] wrote: I'm new in python and I would like to know what is the capabilleties of this language.Please let me know and how I can make a program in python exe if you want to know how to make programs in python, start here: http://wiki.python.org/moin/BeginnersGuide if you want to know how to turn python program into exe files, this page might help: http://effbot.org/zone/python-compile.htm /F -- http://mail.python.org/mailman/listinfo/python-list
Re: p2exe using wine/cxoffice
James Stroud [EMAIL PROTECTED] wrote: My department has switched from vmware to wine/cxoffice. Fascinating. If you don't mind, and if others don't mind an off-topic diversion, can you spend a few minutes explaining what led to this decision? Wine is pretty good, but it will never be as thorough and compatible as a VMware session. -- - Tim Roberts, [EMAIL PROTECTED] Providenza Boekelheide, Inc. -- http://mail.python.org/mailman/listinfo/python-list
Re: optimizing out getattr
Daishi Harada wrote: I'd like to get the 'get2' function below to perform like the 'get1' function (I've included timeit.py results). labels = ('a', 'b') def get1(x): return (x.a, x.b) def mkget(attrs): def getter(x): return tuple(getattr(x, label) for label in attrs) return getter get2 = mkget(labels) # % timeit.py -s import test test.get1(test.a) # 100 loops, best of 3: 0.966 usec per loop # % timeit.py -s import test test.get2(test.a) # 10 loops, best of 3: 4.46 usec per loop I'm not sure how to write 'mkget' to do achieve this, however, except to use 'exec' - is that what would be necessary? No, you can just sit back and wait -- for Python 2.5: $ cat attr_tuple25.py import operator class A: a = 1 b = 2 get2 = operator.attrgetter(a, b) def get1(x): return x.a, x.b $ python2.5 -m timeit -s'from attr_tuple25 import A, get1, get2' 'get1(A)' 100 loops, best of 3: 0.813 usec per loop $ python2.5 -m timeit -s'from attr_tuple25 import A, get1, get2' 'get2(A)' 100 loops, best of 3: 0.495 usec per loop Time till release is not included in the timings :-) Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: ddd or eclipse with mod_python
Sakcee wrote: Hi I am using mod_python for web development, I am in need of some ide , can i use ddd or eclipse with pydev with mod_python. Don't know, but you may want to check Eric3, a full blown Python IDE with support for mod_python debugging. -- bruno desthuilliers python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')]) -- http://mail.python.org/mailman/listinfo/python-list
Re: urllib.open problem
Astan Chee wrote: I have a python script which runs perfectly on my machine. However a machine that I tested it on gives the following error message: Traceback (most recent call last): File whip.py, line 616, in OnRebootRunning File whip.py, line 626, in RebootCustom File urllib.pyc, line 77, in urlopen File urllib.pyc, line 170, in open TypeError: cannot concatenate 'str' and 'NoneType' objects The code snipplet where this error happens is f = urllib.urlopen(http://www.hotmail.com/) notes= f.readlines() Does anyone know what causes this error? Im perplexed because it works on some machines and it doesnt work on other computers although they all have the same spec. assuming you're using Python 2.4, the relevant portion of urllib.py looks like this: urltype, url = splittype(fullurl) if not urltype: urltype = 'file' if urltype in self.proxies: proxy = self.proxies[urltype] urltype, proxyhost = splittype(proxy) host, selector = splithost(proxyhost) url = (host, fullurl) # Signal special case to open_*() else: proxy = None name = 'open_' + urltype # -- this is line 170 the error message indicates that urltype is None when you get to line 170, and the only way it can get set to None is a bogus proxy setting (causing splittype to fail). checking the environment for things that end with _proxy should help. /F -- http://mail.python.org/mailman/listinfo/python-list
Re: working with VERY large 'float' and 'complex' types
Paul Rubin calculates exp(1000.0): You could rearrange your formulas to not need such big numbers: x = 1000. log10_z = x / math.log(10) c,m = divmod(log10_z, 1.) print 'z = %.5fE%d' % (10.**c, m) Nice approach. We should never forget that we do have mathematical skills beside the computers. But, shouldn't you switch c and m in the last row? /MiO -- http://mail.python.org/mailman/listinfo/python-list
wxPython and window sizing
I have a small problem; I would like to have a reasonable minimum size for a wx.Window. A simplified version of my code: s = wx.SplitterWindow(self, -1) curves = wx.Notebook(s) curve = wx.Window(curves, ID_BLANKCURVE, style=wx.SUNKEN_BORDER, size=(300,200)) curves.AddPage(curve, Blank) textbox = wx.TextCtrl(s, ID_TEXTBOX, style=wx.TE_MULTILINE, size=(-1,50)) s.SetMinimumPaneSize(50) s.SplitHorizontally(curves, textbox) s.SetSashGravity(0.8) Here 'self' is the main window class, i.e. inherited from wx.Frame. What I would like to happen is that both the curve area and the textbox would have an absolute minimum size when moving the sash or resizing the window. How to get this behaviour? I have tried setting the minimum sizes of the curve and the textbox by using the SetMinSize() method, but this does not seem to affect anything. Already when the window is shown the upper pane (i.e. the notebook curves) is smaller than (300,200) set in the code. TIA, - Ville -- Ville Voipio, Dr.Tech., M.Sc. (EE) -- http://mail.python.org/mailman/listinfo/python-list
Re: Windows Python 2.4: Unbuffered flag causes SyntaxError oninteractive sessions?
Lonnie Princehouse wrote: After doing some more reading, I now think this isn't a bug. Evidently the unbuffered flag not only makes stdin unbuffered, but it also forces it into binary mode. I didn't realize that when I posted earlier. So the SyntaxErrors arise because the interpreter isn't converting \r\n into \n because stdin is binary. Not a bug, although it would be nice to have an unbuffered text mode flag too... D'oh. It seems a little bizarre to me that the compiler isn't prepared to treat carriage returns as whitespace during its tokenizations. The only area I would anticipate problems would be string literals containing end-of-line sequences embedded within triple-quotes. It would seem to make sense to program the compiler defensively to ignore embedded \r characters. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
change an element of a list
Hi! I have a list of lists and in some of these lists are elements which I want to change. Here an example: lists=[('abc', 4102, 3572), ('def', 2707, 'None'), ('ghi', 'None', 4102)] 'None' should be replaced by 0 or NULL or something else. But as far as I know the replace function of the module string does not work for lists. Any ideas? Thanks for some help! Dirk -- http://mail.python.org/mailman/listinfo/python-list
Re: Software bugs aren't inevitable
Steven D'Aprano is still unhappy with the linear complexity recursive Fibonacci I proposed as as an alternative to the cascading recursion which for some people is standard or obvious or other similar attribution which is not valid anymore. RuntimeError: maximum recursion depth exceeded (eg calling Jerzy Karczmarczuk's efficiently recursive function with n=1000, while my iterative version works for at least values of n an order of magnitude larger.) Yes, the maximum recursion depth in Python is an artificial limit. But that artificial limit is built into Python specifically to protect you from running into a real recursion limit based on the hardware and architecture of your PC, with painful consequences. Oh, I LOVE technical solutions like that: Everybody knows that you should not exceed some speed in your car. So, our new technology is such that if you reach 160 km per hour, your engine breaks. Surely it is an artificial limit, but it is there to protect you from worse problems with painful consequences. I do not feel guilty for proposing a function which fails for n1000. This solution, in Haskell works for ANY n, and doesn't fill the stack at all (provided it is strictified, i.e. the laziness does not produce some thunk accumulation) fib n = fibo n 0 1 where fibo 0 a _ = a fibo 1 _ b = b fibo n a b = fibo (n-1) b (a+b) But tail recursion is NOT iteration in Python. So, this version: def fib1(n,a=0,b=1): if n==0: return a elif n==1: return b return fib1(n-1,b,a+b) which in a 'decent' language (no offense meant, just thinking what will be considered scandalous in 40 years...) would run for any n, in Python breaks for n1000 again. [[Terry Reedy proposed another variant; mine is a bit shorter, perhaps a bit more elegant]]. I am sorry, but Python, as every other programming language is full of decisions ad hoc, not always universally appreciated. Recursion can be and IS often optimised, and tail recursion in functional languages is entirely removed (no stack filling.) Stacks can be and are sometimes allocated on heap, so the comment of somebody who discussed the dichotomy stack/heap, pointing out the difference in size, may be altogether irrelevant. Again, we, the users are not responsible for the memory allocation policy in Python... So, this paragraph Recursion is frequently extravagant in its use of resources: if nothing else, it takes resources to call a function, and recursion means you call the same function over and over again. There is a reason why functional programming never really took off. is for me a biased view of the problem. Justified only by the fact that at the beginning of functional programming (sixties) nobody cared about the efficiency. Now, such languages as Clean, or good implementations of Scheme are very well optimized. OCaml as well, and Haskell is improving every 3 months. Functional languages did take off, but since a pure functionalism requires particular, quite sophisticated techniques in GOOD algorithm design and implementation, they are less adapted to the brutal world than C or Python. The reasons of relatively small popularity are much less technical than psychological, and this is KNOWN. (Terry Hancock formulated this plainly, he prefers dumb ways because he wants to solve problems, and he doesn't like to perform gymnastics with his brain. We have to accept those attitudes. But I believe that this is the effect of teaching standards; people don't learn high-level algorithm design when they are young enough...) If you google for Fibonacci sequences, you will find dozens, possibly hundreds, of implementations virtually identical to the one I gave. Also significant numbers of Java apps that run slow for values of n larger than 30 or 40 -- a good sign that they are using the naive algorithm. It is a rare under-graduate or secondary school textbook that suggests that the naive algorithm is anything but a poor idea. If you Google for anything, you will find hundreds of stupidities, since nowadays the proliferation of amateurish tutorials etc. on the Web is simply terrible... I WILL NOT assume the responsibility for all the bad solutions. On the other hand, I suspect that there will be people who will not follow this thread, who will just remember your first posting on the subject, and they will remain convinced that recursion /per se/ is lousy, and that your cascading algorithm is *THE* standard recursive solution. Yes, YOU are in the state of sin! [Optional smiley here]. But, I have used myself the cascading version. It was done on purpose, in order to get to the following solution. [[I preferred to use a global dict, but other ways of doing it are also possible]]. fibdic={0:0,1:1} def fibd(n): if not fibdic.has_key(n): r=fibd(n-1)+fibd(n-2) fibdic[n]=r return fibdic[n] And here the recursion limit won't get you!! But the memoization
Re: global interpreter lock
Stephen Thorne wrote: On 15/09/05, Michael Sparks [EMAIL PROTECTED] wrote: At the moment, one option that springs to mind is this: yield WaitDataAvailable(inbox) Twisted supports this. help(twisted.internet.defer.waitForDeferred) Thanks for this. I'll take a look and either we'll use that or we'll use something that maps cleanly. (Reason for pause is because running on mobiles is important to us.) Thanks for the example too :) Best Regards, Michael. -- [EMAIL PROTECTED], http://kamaelia.sourceforge.net/ British Broadcasting Corporation, Research and Development Kingswood Warren, Surrey KT20 6NP This message (and any attachments) may contain personal views which are not the views of the BBC unless specifically stated. -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie - instanciating classes from other files
[EMAIL PROTECTED] wrote: Hey guys, i just started learning python (i usually use java/C). this has got me stumped as its not mentioned in the documentation (unless im skimming it every time). How does one instanciate a class from another file i thought it would be ---code--- import file.py thisFile = ClassName() ---not code--- It's clear you haven't worked through the tutorial. It's short, easy, and educational, so why not save yourself from embarrassment and whip through it rather than trying to learn Python by guess-and-error? -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: change an element of a list
Dirk Hagemann wrote: Hi! I have a list of lists and in some of these lists are elements which I want to change. Here an example: lists=[('abc', 4102, 3572), ('def', 2707, 'None'), ('ghi', 'None', 4102)] 'None' should be replaced by 0 or NULL or something else. Your list is a list of tuples, and what you want here is to replace an element of a tuple - which is not directly possible since tuples are immutables (but of course there's a way... !-) But as far as I know the replace function of the module string does not work for lists. Nope, but you can still replace or modify an element of a list. here a (very QD and probably naive and suboptimal) possible solution: def my_replace(alist, target, replacement): Takes a list of tuples and for each tuple 'replace' target with 'replacement for i, t in enumerate(alist): l = list(t) while target in l: l[l.index(target)] = replacement alist[i] = tuple(l) my_replace(lists, 'None', 'NULL') HTH -- bruno desthuilliers ruby -e print '[EMAIL PROTECTED]'.split('@').collect{|p| p.split('.').collect{|w| w.reverse}.join('.')}.join('@') python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')]) -- http://mail.python.org/mailman/listinfo/python-list
Python CSV writer confusion.
Hi. I am trying to write out a csv file with | instead of comma, because I have a field that may have many commas in it. I read in a csv file, sort it, and want to write it out again. I read the example that says: import csv writer = csv.writer(open(some.csv, wb)) writer.writerows(someiterable) The someiterable is what is confusing me. class Image(object): def __init__(self, title, date, genre, data, value, filename): params = locals() del params['self'] self.__dict__.update(params) def __repr__(self): all_items = self.__dict__.items() return '%s,%s,%s,%s,%s, %s' % (self.title, self.date, self.genre, self.data, self.value, self.filename) def read_images(filename): csv_file = open(filename, rb) reader = csv.reader(csv_file, dialect='excel', delimiter='|') images = [Image(*[field.strip() for field in row]) for row in reader] csv_file.close() return books def sort_images(filename, *attr_names): csv_file = open(filename, rb) reader = csv.reader(csv_file, dialect='excel', delimiter='|') if __name__ == '__main__': images = read_images(rD:\path\to\imagespipe.csv) def get_key(*attr_names): def key(image): return [getattr(image, name) for name in attr_names] return key images.sort(key = get_key(filename)) t = open(r'D:\path\to\filename_sort1.csv', 'w') for image in images: print book #t.write('%s\n' % book) %Before I needed | delimited, this worked #csv.writer(t, dialect='excel', delimiter='|') output = csv.writer(t, dialect='excel', delimiter='|') output.writerows() #output.writerows(image) #output.writerow(image) t.close() This returns an error that says Error: sequence expected My understanding of this is that I am creating a list of lists and I am iterating over it (for image in images), and that image is a list, and is therefore iterable...? I am a bit new at this, and would greatly appreciate any assistance. TIA googleboy -- http://mail.python.org/mailman/listinfo/python-list
Re: change an element of a list
THANKS! That works :-) But meanwhile I found another solution that works in my case. Out of this list of tuples I generated a SQL-Statement which is a simple string. Then I simply checked this string for 'None'. May be too easy... Dirk -- http://mail.python.org/mailman/listinfo/python-list
Re: round() wrong in Python 2.4?
Op 2005-09-14, Robert Kern schreef [EMAIL PROTECTED]: Antoon Pardon wrote: Op 2005-09-13, Robert Kern schreef [EMAIL PROTECTED]: Jeremy Sanders wrote: Nils Grimsmo wrote: Why did round() change in Python 2.4? It the usual floating point representation problem. 0.0225 cannot be represented exactly: That's not what he's asking about. He's asking why his Python 2.3 rounds 0.0225 *up* to 0.023 while his Python 2.4 rounds *down* to 0.022. It's the change in behavior that he's concerned with and isn't just the usual floating point problem. I would say the usual floating point problem is involved. Python 2.3 isn't rounding 0.0225 up while pyton 2.4 rounds it down. 0.0225 isn't representable and it happens that the actual number you get differ. Now which number python should choose when it is fed 0.0225, I don't know. But expressing the different behaviour as a change in round, suggest that the O.P. would be wise to learn about floating point problems Uhh, Python didn't change anything between 2.3 and 2.4 wrt round(). That is what I said, or at least meant to say. The reason he is seeing a difference is because the two executables were built with different compilers. The fact that the version of Python was different in the two cases obscures the real cause. IMO the real cause is unimportant. The real cause can be a different CPU or a different compilor or a different library. What it boils down to is that you can't expect 0,0225 to be represented in a value that will be rounded up. Saying that 0.0225 can't be represented exactly as a binary floating point number is entirely true but is an incomplete answer. Yes, obviously binary floating point representations are involved. But one could always define a standard representation scheme that always gives the same answer for the same input. Can we? I don't think we can, unless you are working with decimal numbers. If you work with floats you are basically saying that the program should choose the best approximation it can. That approximation can differ according to circumstances. So one must be prepared that round(0.225,3) can give different results in different circumstances. The fact is that for some reason there are two schemes being used. Another fact is that this has nothing to do with difference in the versions of Python he is using. Most of Python's floating point behavior is a platform-dependent accident (as Tim Peters always says), and Nils is using two slightly different platforms. Yes and he wouldn't have blamed it on round, had he known or thought about FP representations. -- Antoon Pardon -- http://mail.python.org/mailman/listinfo/python-list
Re: change an element of a list
Dirk Hagemann wrote: THANKS! That works :-) Of course it works. Why wouldn'it it work ?-) But meanwhile I found another solution that works in my case. Out of this list of tuples I generated a SQL-Statement which is a simple string. Then I simply checked this string for 'None'. May be too easy... Nope, why ? If you need to turn this list into a string anyway, doing a replace on the string is of course the simplest and most obvious solution. -- bruno desthuilliers python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')]) -- http://mail.python.org/mailman/listinfo/python-list
re and escape character
i re-format incoming messages like this, command = re.findall(^\002(.{2})\|.*\003$, response)[0] it works well but when response comes with escape characters , my command variable crashes, i cannot parse if response variable is like , response = '\002AB|TIasdasdasd asdasdasd xzczxc qwewer werwer|\003' ps:there must be \002 at the start and \003 at the end. thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: Software bugs aren't inevitable
On Wed, 14 Sep 2005 12:23:00 -0700, Paul Rubin wrote: Steven D'Aprano [EMAIL PROTECTED] writes: It is a mere implementation detail that (for most computer systems, and most programming languages) stack space is at a premium and a deeply recursive function can run out of stack space while the heap still has lots of free memory. Every serious FP language implementation optimizes tail calls and thus using recursion instead of iteration doesn't cost any stack space and it probably generates the exact same machine code. Are you saying that the recursion done by serious languages is a fake? That it is actually implemented behind the scenes by iteration? It seems to me that if recursion and iteration produce the exact same machine code, the argument for preferring recursion over iteration is gutted. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: Oblique Strategies
On Wed, 14 Sep 2005, robin wrote: The Oblique Strategies were originally a set of one-hundred cards, each bearing a short phrase. They were devised by Brian Eno and Peter Schmidt as ways of working through creative problems. When a blockage occurs, draw a card, and see if it can direct you in a tangential way that helps solve the problem. Neat! I can't help but feel that putting the strategies in a file and using 'fortune' to pick them would have been slightly simpler, but since i don't actually seem to have fortune on my machine, i'm actually rather happy that you've done this. I don't know about coding, but i think this might be handy in the cell biology research that constitutes my day job ... tom -- Also, a 'dark future where there is only war!' ... have you seen the news lately? -- applez -- http://mail.python.org/mailman/listinfo/python-list
Oh Yes, They Are [was: Re: Software bugs aren't inevitable]
Paddy wrote: A work colleague circulated this interesting article about reducing software bugs by orders of magnitude: http://www.spectrum.ieee.org/WEBONLY/publicfeature/sep05/0905ext.html Some methods they talk about include removing error prone and ambiguous expressions from their ADA based language Sparc - The example they give is on why they removed the increment operators x++, x-- . A bit of googling shows that they have, in the past mentioned Python in Job specs, but only as one of many languages. I was wondering what Praxis thought of Python, and how good it would be if a Praxis engineer gave a critique of Python as a part of a flow for producing low bug-count software. In this sidebar to the main article: http://www.spectrum.ieee.org/WEBONLY/publicfeature/sep05/0905extsb1.html It seems that they use one equation from the Z notation model and add it as a comment to their main programming languages function definition as a comment, then have a means of automatically testing the comment against the function body. This is rather like how doctest can check the test and expected result given in a doc-string against the implementation given in the function; indeed I wrote up such an example at work and circulated it amongst the resident perl mongers. - Gosh it fealt good :-) So, How do I get feedback from Praxis, Do they already read comp.lang.py? Cheers, Paddy. As far as I can see the advantage of this kind of rigor is best kept for the projects where it really matters (e.g. safety-critical monitoring and control systems). Programming is a growing human activity, and I would suggest that one of Python's designed-in advantages is the ease with which comprehensible implementations of known algorithms can be constructed. Given Guido's expressed interest in Computer Programming for Everyone this comes as no surprise to more. Nonetheless we have to remember that the vast majority of Python programmers wouldn't care about differences between implementation techniques, being happy that they've found *any* way to get the computer to do what they want. I'm sure that a Praxis evaluation of Python would make a very good presentation at PyCon, whose Call for Proposals recently came out. Yes folks, next time around it's PyCon TX 2006, see http://www.python.org/pycon/2006/cfp regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC www.holdenweb.com PyCon TX 2006 www.pycon.org -- http://mail.python.org/mailman/listinfo/python-list
Re: What XML lib to use?
Fredrik Lundh wrote: Robert Kern wrote: His interpretation of your words is a perfectly valid one even in the context of this thread. in Python explicitly provides a context for the rest of the sentence. Exactly. in Python, not in an application with an existing API. Well, if you're still not convinced that DOMs exist outside monolithic applications... ;-) In English, at least, it is perfectly reasonable to presume that explicit contexts override implicit ones. Letting a part of a sentence override the context of the discussion is perhaps popular in certain tabloid journalist circles, and among slash- dot editors and US political bloggers, but most people do in fact have a context buffer memory that can hold more than a few words. I don't really see how an absolutely-qualified complete sentence... Q since there are no *sane* reasons to use SAX or DOM in Python, Q that's mainly a job security issue... ...can somehow be qualified by the preceding discussion, when the only ambiguous context is that == good for learning things. It's an absolute statement of opinion! (And yes, I think we all agree on what Python is.) I know what I meant. You know what I meant. Paul knows what I meant. I actually do know what you mean, but that doesn't mean that the statement in question wasn't misleading, especially to people who aren't familiar with or accustomed to discovering this missing context. It's like saying there are no *sane* reasons to drive a Volvo, possibly in a follow-up to a discussion about how bad Volvos are compared to Saabs. There may well be a sane reason to drive a Volvo, but the statement doesn't allow for the possibility, unless in the hunt for the missing context you're willing to take the term significant whitespace to a whole new level. Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Software bugs aren't inevitable
Hi! 2005/9/15, Jerzy Karczmarczuk [EMAIL PROTECTED]: [snip] But, I have used myself the cascading version. It was done on purpose, in order to get to the following solution. [[I preferred to use a global dict, but other ways of doing it are also possible]]. fibdic={0:0,1:1} def fibd(n): if not fibdic.has_key(n): r=fibd(n-1)+fibd(n-2) fibdic[n]=r return fibdic[n] And here the recursion limit won't get you!! But the memoization techniques are rarely taught nowadays... = And the story doesn't end here. There are backtracking solutions, which in functional (lazy) languages can be emulated through co-recursion, and in Python by the use of generators. Jerzy Karczmarczuk -- http://mail.python.org/mailman/listinfo/python-list It is also possible to do a version that scales logarithmically with n. It relies on the observation that calculation of the fibonacci series can be done by taking the upper left entry of the following matrix exponentiation: n /1 1\ \1 0/ Since exponentiation can be done logarithmically this can be used to calculate fibonacci series faster (at least for big values of n): def mul(m1, m2): ((a, b), (c, d)) = m1 ((e, f), (g, h)) = m2 return [[a*e + b*g, a*f + b*h], [c*e + d*g, c*f + d*h]] def expo(m, n): if n == 0: return [[1, 0], [0, 1]] if n % 2 == 0: r = expo(m, n//2) return mul(r, r) else: return mul(m, expo(m, n - 1)) def fib(n): return expo([[1, 1], [1, 0]], n)[0][0] With this you can calculate really big fibonacci numbers without increasing the recursion depth, even though the expo function is recursively written. Cheers, Carl Friedrich Bolz -- http://mail.python.org/mailman/listinfo/python-list
Britney Spears nude
send me the britney nude photos Yahoo! for Good Click here to donate to the Hurricane Katrina relief effort. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python in C integration and WxPython
It sounds like your C program and Python script are running under different interpreters. Your C program almost certainly is using a Python version that comes with Cygwin, while the script is probably using a native win32 Python that has wxPython installed. Assuming this is true, then compiling your C program natively on Windows should solve the problem. Alternatively, if wxPython is available for cygwin (possibly via cygwin's X server) then installing it would also help. David. Alain Paschoud wrote: Hi all, I made a small dialog in WxPython. I can run the python script with a double-click or through command line, and everything goes fine (dialog appears, which means that wx module has been found). Then, I decided to write a C program (under Windows, with Cygwin) that will read my script (through PyRun_SimpleFile() function) and run it. But the system doesn't find the wx module to import... Traceback (most recent call last): File Dialog.py, line 2, in ? import wx ImportError: No module named wx How can I say to my program where to search for this module ? I tried to set $PYTHONPATH and $PYTHONHOME, but this doesn't change anything. More generally : Does a C program that embedded python run an external executable (interpreter), or does it only load libraries ? Thank you very much for any help on this topic. Best regards. -- http://mail.python.org/mailman/listinfo/python-list
MySQLdb UPDATE does nothing
Hi, I normally work with Java but I'm interested in using Python as well, particularly for little tasks like doing some massaging of data in a MySQL database. Below is my first attempt. I'm sure it's inelegantly written, but my main concern is that the UPDATE sql doesn't actually work, and I can't understand why. No error is returned, it's just that the update does not take place. The SQL itself is fine, though - if I instead write the SQL to a file I can use it from the mysql command line and it does all the updates just fine. What have I missed? John === #!/usr/bin/python # import MySQL module import MySQLdb # connect db = MySQLdb.connect(host=localhost, user=john, passwd=xxx,db=test_db) # create a cursor cursor = db.cursor() # execute SQL statement cursor.execute(SELECT DISTINCT product_id FROM product_attribute) # get the resultset as a tuple result = cursor.fetchall() # iterate through resultset for record in result: sql=SELECT id FROM product_attribute WHERE product_id = +str(record[0]) print +sql cursor.execute(sql) result2=cursor.fetchall() index=0 for record2 in result2: sql=UPDATE product_attribute SET index_column = +str(index)+ WHERE id = +str(record2[0]) print+sql cursor.execute(sql) index+=1 cursor.close() -- http://mail.python.org/mailman/listinfo/python-list
Re: MySQLdb UPDATE does nothing
On 9/15/05, John Moore [EMAIL PROTECTED] wrote: ... my main concern is that the UPDATE sql doesn't actually work, and I can't understand why. You probable need to commit your changes. Try a cursor.commit() call. If all the changes make up one logical transaction, do the commit at the end of the loop. Otherwise, do one after each update. (What does a logical transaction consist of? Only you can answer that! It's a domain question. A transaction is a set of changes that should be applied atomically - i.e., you want them all to happen, or none of them.) -- Cheers, Simon B, [EMAIL PROTECTED], http://www.brunningonline.net/simon/blog/ -- http://mail.python.org/mailman/listinfo/python-list
Re: MySQLdb UPDATE does nothing
sql=UPDATE product_attribute SET index_column = +str(index)+ WHERE id = +str(record2[0]) .. cursor.execute(sql) To allow the DB-API adaptor to correctly take care of value conversion and SQL escaping for you, this should be written as: cursor.execute(UPDATE product_attribute SET col1 = %s WHERE id = %s, (index, record2[0])) As for why the UPDATE has no effect, which version of MySQL are you using? David. -- http://mail.python.org/mailman/listinfo/python-list
python optimization
I use cpython. I'm accustomed (from c++/gcc) to a style of coding that is highly readable, making the assumption that the compiler will do good things to optimize the code despite the style in which it's written. For example, I assume constants are removed from loops. In general, an entity is defined as close to the point of usage as possible. I don't know to what extent these kind of optimizations are available to cpython. For example, are constant calculations removed from loops? How about functions? Is there a significant cost to putting a function def inside a loop rather than outside? -- http://mail.python.org/mailman/listinfo/python-list
FOUND VIRUS IN MAIL from python-list@python.org to [EMAIL PROTECTED]
V I R U S A L E R T Our viruschecker found a VIRUS in your email to [EMAIL PROTECTED]. We stopped delivery of this email! Now it is on you to check your system for viruses In file: /usr/local/mav/basedir/j8FCBSXA032608/Part_2.zip Found the W32/[EMAIL PROTECTED] virus !!! For your reference, here are the headers from your email: - BEGIN HEADERS - Received: from [62.108.101.65] by gigant.zrlocal.net [212.200.56.13] with SMTP id j8FCBSXA032608; Thu Sep 15 14:12:15 2005 +0200 From: python-list@python.org To: [EMAIL PROTECTED] Subject: Information Date: Thu, 15 Sep 2005 14:11:33 +0200 MIME-Version: 1.0 Content-Type: multipart/mixed; boundary==_NextPart_000_0002_62BC.7C7C X-Priority: 1 X-MSMail-Priority: High -- END HEADERS -- -- http://mail.python.org/mailman/listinfo/python-list
Re: MySQLdb UPDATE does nothing
On 9/15/05, John Moore [EMAIL PROTECTED] wrote: I tried that, but got this: Traceback (most recent call last): File moddb.py, line 31, in ? cursor.commit() AttributeError: 'Cursor' object has no attribute 'commit' Oops. I should have said connection.commit(). Posting before thinking again. -- Cheers, Simon B, [EMAIL PROTECTED], http://www.brunningonline.net/simon/blog/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Software bugs aren't inevitable
Steven D'Aprano wrote: On Wed, 14 Sep 2005 12:23:00 -0700, Paul Rubin wrote: Every serious FP language implementation optimizes tail calls and thus using recursion instead of iteration doesn't cost any stack space and it probably generates the exact same machine code. Are you saying that the recursion done by serious languages is a fake? That it is actually implemented behind the scenes by iteration? It seems to me that if recursion and iteration produce the exact same machine code, the argument for preferring recursion over iteration is gutted. Well, in such a way we can discuss for eternity... Please, distinguish between the high-level algorithm formulation, and what computer does under the carpet. The recursion - as put forward by functionalists is a conceptual way of thinking. With passing of new parameters without explicitly updating the variables to which the old ones are assigned. Without loop control variables, nor looping constructs. You don't reassign your variables, you avoid the side-effects. The programs are often clearer and safer, less error-prone. Now, the ugly world of basic computing at the assembly level is imperative, not functional (within standard architectures). The registers ARE reassigned. The stack must be explicitly handled, etc. You *SEE* explicitly the iterative structures. The point of functionalists is that one should avoid that, and leave those nasty things to the compiler. That's all. Your final conclusion is for me rather inacceptable. It is not the machine code which matters, but human effort [provided you spent sufficient time to be fluent in *good* recursive programming of complex tasks.] Jerzy Karczmarczuk -- http://mail.python.org/mailman/listinfo/python-list
Re: Sorting Unix mailboxes
[posted and mailed, in case the OP has given up on reading the group!] On Tue, 13 Sep 2005, [EMAIL PROTECTED] wrote: I'm writing a program in python to sort the mail in standard Unix email boxes. In my prof of concept example I am coping a letter to a second mailbox if the letter was send from a particular email address. When I read the destination mailbox with cat, I can see that something is getting copied to it, but the mail program does not recognize any new letters in the destination mailbox. It would seam that the OutFile.write(Message.get_unixfrom()) line is essential. Absolutely! The From line is the key element in mailbox structure. However if I run with this line uncommented then I get an the following error. TypeError: argument 1 must be string or read-only character buffer, not None. This is happening because Message.get_unixfrom is returning None, rather than a proper From line. According to its documentation, thus method defaults to None if the envelope header was never set. Since you've never set the envelope header, this behaviour is therefore not surprising. But didn't the envelope header get set when you created the message? Actually, no - you created it with email.message_from_file(Envelope.fp), which reads the contents of the email from the file Envelope.fp. Envelope.fp, however, isn't the complete text of the mailbox entry, it's just (AFAICT) the payload of the message. Therefore, the message you create has no headers or envelope, just the body. I created this program by following an example posted somewhere on the Internet, that I can't seam to find anymore. At one time I was able to get Python to put new letters in a mailbox. Also, I was wondering is there were a way to use Python to delete items from a mailbox. Not really. This is a universal problem which affects all programs, regardless of language, with work with file formats consisting of variable-sized records - there's no wasy way to delete them. I could create I temp box of non-deleted then copy to the source box, but that seams messy. A cleaner way would be to copy the non-deleted messages to a new file, then to throw away the old file and rename the new one to replace it. This would avoid the second copy. Alternatively, you could read and write simultaneously with one file, then truncate at the end; this takes a bit more care, though. Here is my example program.. Right. Some of this makes sense to me, but there's quite a lot here that i don't get. Perhaps some of this is a result of the code being excised from its natural context, though. def CopyToBox(Source,Address,Destination): AddressRE=re.compile( ([a-zA-Z0-9._-]+)@([a-zA-Z0-9._-]+)\.([a-zA-Z0-9]+)) Why did you write the regexp to capture the address as three groups? It seems like the only thing you ever do with the groups is put them back together again! Also, it's better to define the regexp once, at global scope, to avoid having to compile it every time the function runs. InFile = open(/home/stevef/mail/%s % Source) OutFile = open(/home/stevef/mail/%s % Destination,a) Box = mailbox.PortableUnixMailbox(InFile) Envelope=Box.next() Why 'Envelope'? That object is a Message, not an Envelope! And did you really mean to throw away the first message in the box like this? while 1: Envelope=Box.next() if Envelope == None: break Why an infinite loop with a break and an explicit next call? Why not a for loop over the mailbox? print Envelope.getallmatchingheaders(from)[0] Match=AddressRE.search( Envelope.getallmatchingheaders(from)[0]) Why getallmatchingheaders(from)[0] rather than getfirstmatchingheader[from]? if Match: Set=Match.groups() if [EMAIL PROTECTED] % Set == Address: print Copy letter from [EMAIL PROTECTED] % Set Message = email.message_from_file(Envelope.fp) Message now contains the email's payload, but not its headers or envelope details, so ... #OutFile.write(Message.get_unixfrom()) ##error That doesn't work. OutFile.write(\n) OutFile.write(Message.as_string()) InFile.close() OutFile.close() return There's no need for an explicit return here. I have to sympathise with you over python's mail-handling libraries, though; having both the rfc822 and email modules around at the same time is quite a headache. Luckily, there's a way to make things simpler and much easier to work with, using a trick described in the docs for the mailbox module: rather than letting the mailbox module make the message objects (using the rfc822 module to do it), we can supply our own message factory function, with which we can create email-module messages right from the start. You need a function like this: def msgfactory(f): while True: try:
Re: python optimization
Hi Neal, I don't believe that cpython currently does any of the optimizations you refer to below. That said, it is very reasonable to adopt a style of coding that is highly readable, making the assumption that the compiler will do good things when coding in Python. Python is one of the most highly optimised languages in the world along the Programmer Productivity metric. Line for line, you can pack more readable, obvious, and maintainablemeaning into Python than pretty much any other language. The upshot is that then you can profile the final running code and see if it really matters that the compiler is using an extra .034 microseconds. That's my $0.028 US (damn inflation!) On 15/09/05, Neal Becker [EMAIL PROTECTED] wrote: I use cpython.I'm accustomed (from c++/gcc) to a style of coding that ishighly readable, making the assumption that the compiler will do good things to optimize the code despite the style in which it's written.Forexample, I assume constants are removed from loops.In general, an entityis defined as close to the point of usage as possible. I don't know to what extent these kind of optimizations are available tocpython.For example, are constant calculations removed from loops?Howabout functions?Is there a significant cost to putting a function def inside a loop rather than outside?--http://mail.python.org/mailman/listinfo/python-list-- A little government and a little luck are necessary in life, but only a fool trusts either of them. -- P. J. O'Rourke -- http://mail.python.org/mailman/listinfo/python-list
Self reordering list in Python
Hello, Do you know how to implement a really efficient self reordering list in Python? (List with a maximum length. When an item is processed, it becomes the first element in the list.) I would like to use this for caching of rendered images. Of course I could implement this in pure Python, I just wonder if there is a faster implementation that uses some cool feature of the standard library. (Maybe a C implementation could be added to the collections module?) Les -- http://mail.python.org/mailman/listinfo/python-list
Re: python optimization
For the most part, CPython performs few optimisations by itself. You may be interested in psyco, which performs several heavy optimisations on running Python code. http://psyco.sf.net/ Defining a function inside a loop in CPython will cause a new function object to be created each and every time the loop runs. No such automatic optimisation is performed there. For the most part, this lack of opimisation not only simplifies the CPython implementation, but also causes code to act much more closely to how it was defined, which is good for new and advanced users alike. Other than psyco, IronPython and PyPy are two projects which you might be interested in if execution performance is of interest to you. http://www.ironpython.com/ http://codespeak.net/pypy/ David. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Bindings for Dirac, (sorta announcement)
We now also have python bindings for Dirac /encoding/ too. If you feel like playing with this (please do!) the same caveats Michael mentioned apply, and the dependancies are the same (pyrex and dirac). A sample video encoding-decoding-viewing pipeline is in: /Code/Python/Kamaelia/Examples/example10 ... in Kamaelia's tree in the CVS repository. Again, the input format is 'raw' yuv video files. Follow Michael's instructions to build your own from AVI files using ffmpeg. Alternatively, download the sample video files from the dirac website, and prepare them by following the instructions you'll find within comments in the example python program. regards Matt Hammond http://kamaelia.sf.net/ -- | Matt Hammond | RD Engineer, BBC Research and Development, Tadworth, Surrey, UK. -- http://mail.python.org/mailman/listinfo/python-list
Re: python optimization
David Wilson wrote: For the most part, CPython performs few optimisations by itself. You may be interested in psyco, which performs several heavy optimisations on running Python code. http://psyco.sf.net/ Defining a function inside a loop in CPython will cause a new function object to be created each and every time the loop runs. No such automatic optimisation is performed there. For the most part, this lack of opimisation not only simplifies the CPython implementation, but also causes code to act much more closely to how it was defined, which is good for new and advanced users alike. More importantly, since Python supports lexical scopes, a function defined in a loop could be different each time it is defined, e.g. def getadders(to): for i in range(to): def adder(amount): return i + amount yield adder Reinhold -- http://mail.python.org/mailman/listinfo/python-list
Re: wxPython and window sizing
Ville Voipio wrote: I have a small problem; I would like to have a reasonable minimum size for a wx.Window. A simplified version of my code: s = wx.SplitterWindow(self, -1) curves = wx.Notebook(s) curve = wx.Window(curves, ID_BLANKCURVE, style=wx.SUNKEN_BORDER, size=(300,200)) curves.AddPage(curve, Blank) textbox = wx.TextCtrl(s, ID_TEXTBOX, style=wx.TE_MULTILINE, size=(-1,50)) s.SetMinimumPaneSize(50) s.SplitHorizontally(curves, textbox) s.SetSashGravity(0.8) Here 'self' is the main window class, i.e. inherited from wx.Frame. What I would like to happen is that both the curve area and the textbox would have an absolute minimum size when moving the sash or resizing the window. How to get this behaviour? I have tried setting the minimum sizes of the curve and the textbox by using the SetMinSize() method, but this does not seem to affect anything. Already when the window is shown the upper pane (i.e. the notebook curves) is smaller than (300,200) set in the code. TIA, - Ville Couldn't you register for a handler? It would be called on changing size or on moving the sash's slider. And w/i that handler you could resize the window to its min dims. HTH Franz GEIGER -- http://mail.python.org/mailman/listinfo/python-list
Re: python optimization
Reinhold Birkenfeld [EMAIL PROTECTED] writes: David Wilson wrote: For the most part, CPython performs few optimisations by itself. You may be interested in psyco, which performs several heavy optimisations on running Python code. http://psyco.sf.net/ Defining a function inside a loop in CPython will cause a new function object to be created each and every time the loop runs. No such automatic optimisation is performed there. For the most part, this lack of opimisation not only simplifies the CPython implementation, but also causes code to act much more closely to how it was defined, which is good for new and advanced users alike. More importantly, since Python supports lexical scopes, a function defined in a loop could be different each time it is defined, e.g. def getadders(to): for i in range(to): def adder(amount): return i + amount yield adder Hehe. Dangerous code. def getadders(to): ... for i in range(to): ... def adder(amount): ... return i + amount ... yield adder ... for f in getadders(3): ... print f(42) ... 42 43 44 Seems to work. But observe this: def getadders(to): ... for i in range(to): ... def adder(amount): ... return i + amount ... yield adder ... funcs = [x for x in getadders(3)] for f in funcs: ... print f(42) ... 44 44 44 Thomas -- http://mail.python.org/mailman/listinfo/python-list
Re: python optimization
Reinhold Birkenfeld wrote: David Wilson wrote: For the most part, CPython performs few optimisations by itself. You may be interested in psyco, which performs several heavy optimisations on running Python code. http://psyco.sf.net/ I might be, if it supported x86_64, but AFAICT, it doesn't. -- http://mail.python.org/mailman/listinfo/python-list
Re: Removing duplicates from a list
Rubinho napisal(a): I've a list with duplicate members and I need to make each entry unique. hi, other possibility (my newest discovery:) ) a = [1,2,2,4,2,1,3,4] unique = d.fromkeys(a).keys() unique [1, 2, 3, 4] regards przemek -- http://mail.python.org/mailman/listinfo/python-list
Re: Removing duplicates from a list
Look at the code below def unique(s): return list(set(s)) def unique2(keys): unique = [] for i in keys: if i not in unique:unique.append(i) return unique tmp = [0,1,2,4,2,2,3,4,1,3,2] print tmp print unique(tmp) print unique2(tmp) -- [0, 1, 2, 4, 2, 2, 3, 4, 1, 3, 2] [0, 1, 2, 3, 4] [0, 1, 2, 4, 3] As you can see the end result is not the same. I must get the end result [0, 1, 2, 4, 3] and not [0, 1, 2, 3, 4]. Thats why I use unique2() -- http://mail.python.org/mailman/listinfo/python-list
Thread safe object cache without locking
I'm trying to make a thread safe object cache without locking. The objects are cached by the id of the data dict given in __new__. Objects are removed from the cache as soon as they are no longer referenced. The type of the data must be a Python dict (comes from an external source). Here's what I've got so far: import time from weakref import ref cache = {} # {id(data): ref_to_Foo(data), ...} class Foo(object): __slots__ = ('__weakref__', '_data') def __new__(cls, data): new_self = object.__new__(cls) def remove(wr, _cache=cache, _data=data): try: del _cache[id(_data)] except KeyError: pass # should never happen while 1: self = cache.setdefault(id(data), ref(new_self, remove))() try: self._data = data return self # this is new_self or a cached instance except AttributeError: # happens rarely: got a 'dead' cached instance time.sleep(0) # small delay before retrying # Usage example: data = {'a':1, 'b':2} a = Foo(data) b = Foo(data) assert a is b I've got couple of assumptions based on I think the code is working correctly: a) Python's dict is thread safe, i.e. setdefault can't replace an existing value until the key has been removed - no matter how many threads are calling it simultaneously. Additionally, only one thread succeeds in setting the new value. b) Unreferenced ref(new_self, remove) objects are garbage collected without the callbacks being called. c) The remove() keeps a reference to the data dict. That should prevent Python from reusing the object id too soon. Are these assumptions correct? Do you have ideas for improvements (especially regarding speed)? I'm restricted to Py2.3+ compatibility. Thanks, Timo -- http://mail.python.org/mailman/listinfo/python-list
brain cramp: emulating cgi.FieldStorage
I can't be the first person to want to do this, but I also can't seem to find a solution. (Perhaps my Google skills are poor today.) How can I emulate cgi.FieldStorage() for my unit tests so that I don't have to put a web server in the way? what I'd like to do is something like fs = cgi.FieldStorage() fs[foo] = bar functionToBeTested(fs) Any hints/leads/suggestions? -- http://mail.python.org/mailman/listinfo/python-list
MySQL Python
Just migrating now from ASP/to MySQL and Python. I am trying to create a simple script to access a MySQL DB. The Module for MySQL looks very easy, however I do not understand one thing ... In ASP, you can just create a new DB with Access. In MySQL, how do I create a database to start playing with? I see all of the commands to edits tables and values and move a cursor, but I do not see how I actually create THE INITIAL DB, any help would be appreciated. thanks. -- edward hotchkiss -- http://mail.python.org/mailman/listinfo/python-list
Re: wxPython and window sizing
In article [EMAIL PROTECTED], Franz GEIGER wrote: Couldn't you register for a handler? Oui, mais... I can figure out a few ugly workarounds. However, my question is if there is a nice and clean way to make wxPython set the minimum size. I'd really hate to start calculating the sizes myself or making any extra handlers, if the existing infrastructure can handle what I want. - Ville -- Ville Voipio, Dr.Tech., M.Sc. (EE) -- http://mail.python.org/mailman/listinfo/python-list
Re: Removing duplicates from a list
there wasn't any information about ordering... maybe i'll find something better which don't destroy original ordering regards przemek -- http://mail.python.org/mailman/listinfo/python-list
Re: MySQL Python
Connect to the database as root. create database databasename; Now grant priveleges accordingly: grant all on databasename to super_user; (I may have the grant syntax screwed up, but you get the idea.) jw On 9/15/05, Ed Hotchkiss [EMAIL PROTECTED] wrote: Just migrating now from ASP/to MySQL and Python. I am trying to create a simple script to access a MySQL DB. The Module for MySQL looks very easy, however I do not understand one thing ... In ASP, you can just create a new DB with Access. In MySQL, how do I create a database to start playing with? I see all of the commands to edits tables and values and move a cursor, but I do not see how I actually create THE INITIAL DB, any help would be appreciated. thanks. -- edward hotchkiss -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Removing duplicates from a list
i suppose this one is faster (but in most cases efficiency doesn't matter) def stable_unique(s): e = {} ret = [] for x in s: if not e.has_key(x): e[x] = 1 ret.append(x) return ret cheers, przemek -- http://mail.python.org/mailman/listinfo/python-list
help for conversion of NUMARRAY to PIL object
hi, everybody here, I am a newbie to python. I encounter a problem that how to convert an array of numarray to pil object. For example, the data in an image is extracted using Image.getdata, then the data are converted into an array in numarray. But when the array is needed to convert to the pil object, I lose my mind. Could somebody here provide some solutions to this problem? (In other words, all I need is the interface between reading/writing image data and NUMARRAY.) Thanks in advance. -- http://mail.python.org/mailman/listinfo/python-list
Re: MySQL Python
On 9/15/05, Ed Hotchkiss [EMAIL PROTECTED] wrote: I am trying to create a simple script to access a MySQL DB. The Module for MySQL looks very easy, however I do not understand one thing ... In ASP, you can just create a new DB with Access. In MySQL, how do I create a database to start playing with? I see all of the commands to edits tables and values and move a cursor, but I do not see how I actually create THE INITIAL DB, any help would be appreciated. thanks. If you connect as a user who has database creation privileges on the server, running: cursor.execute(CREATE DATABASE FooBar) will create a new database named 'FooBar' on the server. You will then need to call: cnnct.select_db(FooBar) to change your connection to the new database. -- # p.d. -- http://mail.python.org/mailman/listinfo/python-list
32bit install on 64bit system
Hello, I could really use some help. I'm trying to install a python program on centos4 x86_64. When I run 'python setup.py' it ends up in /usr/lib64/python2.3/site-packages/ instead of /usr/lib/python2.3/site-packages. It's a problem because the program I'm trying to install is a dependency for something that is only 32bit. How can I specify a 32bit install?What I've tried so far: When I try 'python setup.py build --build-lib /usr/lib/python2.3/site-packages' and 'python setup.py install --install-lib /usr/lib/python2.3/site-packages', it installs the 64bit version into the 32bit library.Can anyone help me? Thanks, Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Removing duplicates from a list
Ow thanks , i'm I newbie and I did this test. (don't know if this is the best way to do a small speed test) import timeit def unique2(keys): unique = [] for i in keys: if i not in unique:unique.append(i) return unique def unique3(s): e = {} ret = [] for x in s: if not e.has_key(x): e[x] = 1 ret.append(x) return ret tmp = [0,1,2,4,2,2,3,4,1,3,2] s = \ try: str.__nonzero__ except AttributeError: pass t = timeit.Timer(stmt=s) print %.2f usec/pass % (100 * t.timeit(number=10)/10) print tmp print %.2f usec/pass % (100 * t.timeit(number=10)/10) print unique2(tmp) print %.2f usec/pass % (100 * t.timeit(number=10)/10) print unique3(tmp) print %.2f usec/pass % (100 * t.timeit(number=10)/10) - 5.80 usec/pass [0, 1, 2, 4, 2, 2, 3, 4, 1, 3, 2] 7.51 usec/pass [0, 1, 2, 4, 3] 6.93 usec/pass [0, 1, 2, 4, 3] 6.45 usec/pass --- your code unique2(s): -- http://mail.python.org/mailman/listinfo/python-list
Re: Self reordering list in Python
Am Thu, 15 Sep 2005 15:14:09 +0200 schrieb Laszlo Zsolt Nagy: Hello, Do you know how to implement a really efficient self reordering list in Python? (List with a maximum length. When an item is processed, it becomes the first element in the list.) I would like to use this for caching of rendered images. Of course I could implement this in pure Python, I just wonder if there is a faster implementation that uses some cool feature of the standard library. (Maybe a C implementation could be added to the collections module?) Hi, Maybe the bisect module is what you need: This module provides support for maintaining a list in sorted order without having to sort the list after each insertion. HTH, Thomas -- Thomas Güttler, http://www.thomas-guettler.de/ E-Mail: guettli (*) thomas-guettler + de Spam Catcher: [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: global interpreter lock
It looks like I am reinventing Twisted and/or Kamelia. This is code I wrote just today to simulate Python 2.5 generator in current Python: import Queue class coroutine(object): def __init__(self, *args, **kw): self.queue = Queue.Queue() self.it = self.__cor__(*args, **kw) def start(self): return self.it.next() def next(self): return self.send(None) def __iter__(self): return self def send(self, *args): self.queue.put(args) return self.it.next() def recv(self): return self.queue.get() @classmethod def generator(cls, gen): return type(gen.__name__, (cls,), dict(__cor__=gen)) @coroutine.generator def consumer(self, N): for i in xrange(N): yield i cmd = self.recv() if cmd == exit: break c = consumer(100) print c.start() for cmd in [, , , , exit]: print c.send(cmd) Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: re and escape character
Am Thu, 15 Sep 2005 14:36:38 +0300 schrieb Sinan Nalkaya: i re-format incoming messages like this, command = re.findall(^\002(.{2})\|.*\003$, response)[0] it works well but when response comes with escape characters , my command variable crashes, i cannot parse if response variable is like , response = '\002AB|TIasdasdasd asdasdasd xzczxc qwewer werwer|\003' ps:there must be \002 at the start and \003 at the end. thanks. Hi, I don't know what you mean with escape characters. The dot does not match a newline. You have to use the re.DOTALL option if you want this. HTH, Thomas -- Thomas Güttler, http://www.thomas-guettler.de/ E-Mail: guettli (*) thomas-guettler + de Spam Catcher: [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: brain cramp: emulating cgi.FieldStorage
Chris Curvey wrote: I can't be the first person to want to do this, but I also can't seem to find a solution. (Perhaps my Google skills are poor today.) How can I emulate cgi.FieldStorage() for my unit tests so that I don't have to put a web server in the way? what I'd like to do is something like fs = cgi.FieldStorage() fs[foo] = bar functionToBeTested(fs) Any hints/leads/suggestions? Can't you just pass the FieldStorage some dummy data to parse? It looks pretty simple. class FieldStorage: def __init__(self, fp=None, headers=None, outerboundary=, environ=os.environ, keep_blank_values=0, strict_parsing=0): Constructor. Read multipart/* until last part. Arguments, all optional: fp : file pointer; default: sys.stdin (not used when the request method is GET) headers : header dictionary-like object; default: taken from environ as per CGI spec outerboundary : terminating multipart boundary (for internal use only) environ : environment dictionary; default: os.environ keep_blank_values: flag indicating whether blank values in URL encoded forms should be treated as blank strings. A true value indicates that blanks should be retained as blank strings. The default false value indicates that blank values are to be ignored and treated as if they were not included. strict_parsing: flag indicating what to do with parsing errors. If false (the default), errors are silently ignored. If true, errors raise a ValueError exception. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science -- http://mail.python.org/mailman/listinfo/python-list
Re: brain cramp: emulating cgi.FieldStorage
figured it out... os.environ[QUERY_STRING] = foo=bar fs = cgi.FieldStorage() functionToBeTested(fs) -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Search Engine app
Am Wed, 14 Sep 2005 07:39:35 -0700 schrieb Harlin Seritt: Hi, Is anyone aware of an available open-source/free search engine app (something similar to HTDig) written in Python that is out there? Googling has turned up nothing. Thought maybe I'd mine some of you guys' minds on this. Hi, I use ZODB (not ZOPE) with ZCTextIndex. HTH, Thomas -- Thomas Güttler, http://www.thomas-guettler.de/ E-Mail: guettli (*) thomas-guettler + de Spam Catcher: [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Creating Pie Chart from Python
Let's say I have the following data: 500 objects: -100 are red -300 are blue -the rest are green Is there some python package which can represent the above information in a pie chart? Thanks Thierry -- http://mail.python.org/mailman/listinfo/python-list
Example of signaling and creating a python daemon
Hi. I am running a zope server. Zope runs 4 threads and I have a document processing method that can require minutes to run so I do not want to run out of threads. A solution to this is to run this process asynchronously. What I am hoping to do is send a signal to a python deamon to run a process and then go back to sleep. I am hoping to find a clear example of: * sending a signal from a python script to start a python daemon somewhere on the filesystem * a python daemon that utilizes the signal to wake up from sleep and run a method, then go back to sleep. I have no experience daemonizing a script so this help would be much appreciated. I have found a couple of scripts googling on creating a deemon but not work in this way. Regards, David -- http://mail.python.org/mailman/listinfo/python-list
Re: Creating Pie Chart from Python
Thierry Lam wrote: Let's say I have the following data: 500 objects: -100 are red -300 are blue -the rest are green Is there some python package which can represent the above information in a pie chart? I wrote a wxPython control to render pretty 3D pie charts (see attached piechartwindow.py). It can also be used to pre-generate images such as this.. http://www.foodfileonline.com/static/piecharts/pie01009.jpg Code is public domain. Will McGugan -- http://www.willmcgugan.com .join({'*':'@','^':'.'}.get(c,0) or chr(97+(ord(c)-84)%26) for c in jvyy*jvyyzpthtna^pbz) # Pie Chart Window # 2005 Will McGugan ([EMAIL PROTECTED]) import wx from wx import glcanvas from OpenGL.GL import * import math import time sin = math.sin cos = math.cos PI = math.pi def DegToRad(deg): return deg*PI/180. class PieSegment(object): def __init__(self, radius, angle1, angle2, colour, depth): self.display_list = glGenLists(1) glNewList(self.display_list, GL_COMPILE) self.angle1 = angle1 self.angle2 = angle2 self.explode_angle = DegToRad( (angle2 + angle1) / 2.) DrawPieSegment(radius, angle1, angle2, colour, depth) glEndList() def __del__(self): glDeleteLists(self.display_list, 1) def Draw(self, angle1, angle2, explode): glPushMatrix() glRotate(angle1, 1.0, 0.0, 0.0); glRotate(angle2, 0.0, 0.0, 1.0); glTranslatef( sin(self.explode_angle)*explode, cos(self.explode_angle)*explode, 0. ) glCallList(self.display_list) glPopMatrix() def DrawPieSegment(radius, angle1, angle2, colour, depth): angle1 = DegToRad(angle1) angle2 = DegToRad(angle2) # Number of divisions in 360 degrees RES = 100. fan2D = [] step_degree = ((2*PI)/RES) step_count = int( (angle2 - angle1) / step_degree ) + 1 step_degree = ( angle2 - angle1 ) / float(step_count) # Precalculate the trig sina1 = sin(angle1) cosa1 = cos(angle1) sina2 = sin(angle2) cosa2 = cos(angle2) # Calculate the points in an arc for p in xrange(step_count+1): a = angle1 + p * step_degree x = sin(a) y = cos(a) fan2D.append( (x,y) ) z1 = +depth/2. z2 = -depth/2. glMaterial(GL_FRONT, GL_DIFFUSE, [colour[0], colour[1], colour[2], 1.0]) # Create a fan for the top and bottom of the pie segment glNormal(0, 0, +1.) glBegin(GL_TRIANGLE_FAN) glVertex(0, 0, z1) for x, y in fan2D: glVertex(x*radius, y*radius, z1) glEnd() glNormal(0, 0, -1.) glBegin(GL_TRIANGLE_FAN) glVertex(0, 0, z2) for x, y in fan2D: glVertex(x*radius, y*radius, z2) glEnd() # A strip for the curved edge glBegin(GL_TRIANGLE_STRIP) for x, y in fan2D: glNormal(x, y, 0.) xr = x * radius yr = y * radius glVertex(xr, yr, z1) glVertex(xr, yr, z2) glEnd() n1 = -cosa1, sina1, 0. n2 = cosa2, -sina2, 0. x1, y1 = sina1 * radius, cosa1 * radius x2, y2 = sina2 * radius, cosa2 * radius # Two quads for the radius edges glNormal(n1) glBegin(GL_QUADS) glVertex(0, 0, z1) glVertex(x1, y1, z1) glVertex(x1, y1, z2) glVertex(0, 0, z2) glEnd() glNormal(n2) glBegin(GL_QUADS) glVertex(0, 0, z1) glVertex(x2, y2, z1) glVertex(x2, y2, z2) glVertex(0, 0, z2) glEnd() class PieChartWindow(glcanvas.GLCanvas): def __init__(self, parent): attriblist = None glcanvas.GLCanvas.__init__(self, parent, -1, wx.DefaultPosition, wx.DefaultSize, 0, GLCanvas, attriblist, wx.NullPalette) self.init = False self.segments = [] self.animating = False self.angle = 0. self.explode = 0. self.downx = 0 self.rot = 0. self.captured_mouse = False self.timer = wx.Timer(self) self.Bind(wx.EVT_TIMER, self.OnTimer) self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftButtonDown) self.Bind(wx.EVT_LEFT_UP, self.OnLeftButtonUp) self.Bind(wx.EVT_MOTION, self.OnMouseMove) self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground) self.Bind(wx.EVT_SIZE, self.OnSize) self.Bind(wx.EVT_PAINT, self.OnPaint) def Animate(self): self.animating = True self.start_animate = time.clock() self.timer.Start(1000/20) def OnTimer(self, event): if self.IsShown(): self.Refresh() if not self.animating: self.timer.Stop(); def SetSegments(self, segments, angle=0., radius=150., depth=50.): self.segments = [] First = True if len(segments): angle = -(segments[0][0]/2. *360./100.) for seg in segments: seg_percent, colour = seg if seg_percent == 0: continue if seg_percent .2: angle = angle +
Re: improvements for the logging package
[EMAIL PROTECTED] wrote] Changed now in CVS. When 2.4.2 is released it should be there. Trent Is this the same kind of thing as the (generally ill-regarded) Trent change in Python 2.2.x (for some x != 0) that added: No, I just backported the documentation bit that marked the keyword parameter change to basicConfig() as happening in 2.4. I didn't change any code. Duh. Sorry. Trent -- Trent Mick [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Creating Pie Chart from Python
There are many. One choice would be Tkinter's Canvas. def frac(n): return 360. * n / 500 import Tkinter c = Tkinter.Canvas(width=100, height=100); c.pack() c.create_arc((2,2,98,98), fill=red, start=frac(0), extent = frac(100)) c.create_arc((2,2,98,98), fill=blue, start=frac(100), extent = frac(400)) c.create_arc((2,2,98,98), fill=green, start=frac(400), extent = frac(100)) c.mainloop() Jeff pgpAfjUXdmJWm.pgp Description: PGP signature -- http://mail.python.org/mailman/listinfo/python-list
Re: Self reordering list in Python
Laszlo Zsolt Nagy wrote: Do you know how to implement a really efficient self reordering list in Python? (List with a maximum length. When an item is processed, it becomes the first element in the list.) I would like to use this for caching of rendered images. did you check the cheeseshop? http://www.python.org/pypi/lrucache/0.2 /F -- http://mail.python.org/mailman/listinfo/python-list
Re: Python in C integration and WxPython
Hi David, Thanks for your answer, but I don't think the problem comes from which Python version I use. I installed the Python from cygwin, but this didn't change everything. Finally, I fullfill the PYTHONPATH environment variable to make the system finding the wx module. It is now able to find it. But after that, the mode _core is called, and finally, the module _core_, which is not found. The only _core_ file that I have is the _core_.pyd which is in the wx directory. Of course, I added this directory path to PYTHONPATH, but without any success is it because this is a .pyd file ? Here are the logs I get: Traceback (most recent call last): File Dialog.py, line 2, in ? import wx File C:\Python24\Lib\site-packages\wx-2.6-msw-ansi\wx\__init__.py, line 42, in ? from wx._core import * File /cygdrive/c/Python24/Lib/site-packages/wx-2.6-msw-ansi/wx/_core.py, line 4, in ? import _core_ Here is the result of the Py_GetPath() function: /cygdrive/c/Python24/Lib/site-packages/:/cygdrive/c/Python24/Lib/site-packages /wx-2.6-msw-ansi/:/cygdrive/c/Python24/Lib/site-packages/wx-2.6-msw-ansi/wxPython:/cygdriv e/c/Python24/Lib/site-packages/wx-2.6-msw-ansi/wx:.:/usr/bin/lib/python24.zip:/usr/bin/lib /python2.4/:/usr/bin/lib/python2.4/plat-cygwin:/usr/bin/lib/python2.4/lib-tk:/usr/bin/lib/ python2.4/lib-dynload Any hints ?? Thanks. N.B: Same problem when I run the script directly with python -v Dialog.py. David Wilson wrote: It sounds like your C program and Python script are running under different interpreters. Your C program almost certainly is using a Python version that comes with Cygwin, while the script is probably using a native win32 Python that has wxPython installed. Assuming this is true, then compiling your C program natively on Windows should solve the problem. Alternatively, if wxPython is available for cygwin (possibly via cygwin's X server) then installing it would also help. David. Alain Paschoud wrote: Hi all, I made a small dialog in WxPython. I can run the python script with a double-click or through command line, and everything goes fine (dialog appears, which means that wx module has been found). Then, I decided to write a C program (under Windows, with Cygwin) that will read my script (through PyRun_SimpleFile() function) and run it. But the system doesn't find the wx module to import... Traceback (most recent call last): File Dialog.py, line 2, in ? import wx ImportError: No module named wx How can I say to my program where to search for this module ? I tried to set $PYTHONPATH and $PYTHONHOME, but this doesn't change anything. More generally : Does a C program that embedded python run an external executable (interpreter), or does it only load libraries ? Thank you very much for any help on this topic. Best regards. -- http://mail.python.org/mailman/listinfo/python-list
Re: ddd or eclipse with mod_python
[Sakcee wrote] Hi I am using mod_python for web development, I am in need of some ide , can i use ddd or eclipse with pydev with mod_python. can these ide's handle requests from mod_python and run server side scripts You should be able to debug with Komodo(*): Using the Python Remote Debugger http://aspn.activestate.com/ASPN/docs/Komodo/3.1/komodo-doc-debugpython.html#Using_the_Python_Remote_Debugger You can get a trial here: www.activestate.com/Komodo/Trial Cheers, Trent (*) Disclaimer: I work on Komodo. -- Trent Mick [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Example of signaling and creating a python daemon
Here's a program I use to control volume. Run one way, it waits for a Unix signal and adjusts the volume according to the signal received. Run another way, the PID of the daemon process is determined and a signal is sent according to a commandline argument. #!/usr/bin/env python import pyosd, ossaudiodev, sys, signal, time import os, optparse, signal, atexit, errno FONT = -*-helvetica-*-r-normal--34-*-*-*-*-*-*-* CHANNEL = pcm DEVICE = /dev/mixer def constrain(value, low, high): if value low: return low if value high: return high return value class VolumeControl: def __init__(self, channel=CHANNEL, font=FONT): p = self.p = pyosd.osd(font, colour=#4040ff, shadow=2) p.set_shadow_offset(2) p.set_vertical_offset(64) p.set_align(pyosd.ALIGN_CENTER) m = self.m = ossaudiodev.openmixer() self.i = ossaudiodev.control_names.index(channel) print i, self.i, ossaudiodev.control_names, print m.get(self.i) self.level = m.get(self.i)[0] or 75 self.muted = m.get(self.i)[0] == 0 def volume_change(self, delta): self.level = constrain(self.level + delta, 0, 100) self.muted = False self.m.set(self.i, (self.level, self.level)) self.show() def volume_up(self): if self.level 10 or self.level 85: self.volume_change(1) else: self.volume_change(5) def volume_down(self): if self.level = 10 or self.level 85: self.volume_change(-1) else: self.volume_change(-5) def mute(self): if self.muted: self.muted = False self.m.set(self.i, (self.level, self.level)) else: self.muted = True self.m.set(self.i, (0,0)) self.show() def show(self): s = %d%% % self.level if self.muted: s = (%s) % s self.p.display(Volume: %s % s) self.p.show() def owner(self): return os.access(DEVICE, os.W_OK) def quit(self): raise SystemExit def run(self): atexit.register(unlink) f = open(pidfile, w) f.write(%d % os.getpid()) f.close() signal.signal(signal.SIGUSR1, lambda *args: self.volume_up()) signal.signal(signal.SIGUSR2, lambda *args: self.volume_down()) signal.signal(signal.SIGHUP, lambda *args: self.mute()) signal.signal(signal.SIGINT, lambda *args: self.quit()) signal.signal(signal.SIGQUIT, lambda *args: self.quit()) while self.owner(): time.sleep(1) def findpid(): f = open(pidfile) p = f.read() f.close() return int(p) def main(): from optparse import OptionParser parser = OptionParser() parser.add_option(-d, --no-daemon, action=store_false, dest=daemon, default=True, help=Do not run in background) parser.add_option(-e, --eject, dest=eject, action=store_true, default=False, help=Eject the cdrom) parser.add_option(-q, --quit, dest=quit, action=store_true, default=False, help=Cause the daemon to exit) opts, args = parser.parse_args() #print opts if opts.quit: if not os.path.exists(pidfile): raise SystemExit, pidfile does not exist os.kill(findpid(), signal.SIGQUIT) return if opts.eject: os.kill(findpid(), signal.SIGHUP) return if os.path.exists(pidfile): p = findpid() try: os.kill(p, 0) except os.error, detail: if detail.errno == errno.ESRCH: print stale pidfile exists. removing it. os.unlink(pidfile) else: raise SystemExit, valid pidfile exists. Exiting. print Starting cddoor, if opts.daemon: print as daemon daemonize() else: print daemon() def unlink(): print unlinking, pidfile os.unlink(pidfile) def daemonize (stdin='/dev/null', stdout='/dev/null', stderr='/dev/null'): '''This forks the current process into a daemon. The stdin, stdout, and stderr arguments are file names that will be opened and be used to replace the standard file descriptors in sys.stdin, sys.stdout, and sys.stderr. These arguments are optional and default to /dev/null. Note that stderr is opened unbuffered, so if it shares a file with stdout then interleaved output may not appear in the order that you expect. ''' # Do first fork. try: pid = os.fork() if pid 0: sys.exit(0) # Exit first parent. except OSError, e: sys.stderr.write (fork #1 failed: (%d) %s\n % (e.errno, e.strerror) ) sys.exit(1) # Decouple from parent environment. os.chdir(/) os.umask(0) os.setsid() # Do second fork. try: pid = os.fork() if pid 0: sys.exit(0) # Exit second parent. except OSError, e: sys.stderr.write (fork
Re: Removing duplicates from a list
thanks, nice job. but this benchmark is pretty deceptive: try this: (definition of unique2 and unique3 as above) import timeit a = range(1000) t = timeit.Timer('unique2(a)','from __main__ import unique2,a') t2 = timeit.Timer('stable_unique(a)','from __main__ import stable_unique,a') t2.timeit(2000) 1.8392596235778456 t.timeit(2000) 51.52945844819817 unique2 has quadratic complexity unique3 has amortized linear complexity what it means? it means that speed of your algorithm strongly depends on len(unique2(a)). the greater distinct elements in a the greater difference in execution time of both implementations regards przemek -- http://mail.python.org/mailman/listinfo/python-list
Re: Creating Pie Chart from Python
Thierry Lam wrote: Let's say I have the following data: 500 objects: -100 are red -300 are blue -the rest are green Is there some python package which can represent the above information in a pie chart? on a screen? in a web browser? on a printer? /F -- http://mail.python.org/mailman/listinfo/python-list
Re: Britney Spears nude
[john basha] send me the britney nude photos Because they're a new feature, you'll have to wait for Python 2.5 to be released. -- http://mail.python.org/mailman/listinfo/python-list
Re: Creating Pie Chart from Python
In a web browser, having a pie chart in some image format will be great. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python CSV writer confusion.
The someiterable should be something that has a .next method. That would be a list or any object with such a method. In your case it would be the images list. The writer method will iterate over the list and write everything out for you. Don't put it inside a loop yourself. More like (not tested): import csv . . . outfile=open(r'D:\path\to\filename_sort1.csv', 'w') CSVwriter=csv.writer(outfile, dialect='excel', delimiter='|') CSVwriter.writerows(images) Larry Bates if __name__ == '__main__': images = read_images(rD:\path\to\imagespipe.csv) def get_key(*attr_names): def key(image): return [getattr(image, name) for name in attr_names] return key images.sort(key = get_key(filename)) t = open(r'D:\path\to\filename_sort1.csv', 'w') for image in images: print book #t.write('%s\n' % book) %Before I needed | delimited, this worked #csv.writer(t, dialect='excel', delimiter='|') output = csv.writer(t, dialect='excel', delimiter='|') output.writerows() #output.writerows(image) #output.writerow(image) t.close() -Larry Bates googleboy wrote: Hi. I am trying to write out a csv file with | instead of comma, because I have a field that may have many commas in it. I read in a csv file, sort it, and want to write it out again. I read the example that says: import csv writer = csv.writer(open(some.csv, wb)) writer.writerows(someiterable) The someiterable is what is confusing me. class Image(object): def __init__(self, title, date, genre, data, value, filename): params = locals() del params['self'] self.__dict__.update(params) def __repr__(self): all_items = self.__dict__.items() return '%s,%s,%s,%s,%s, %s' % (self.title, self.date, self.genre, self.data, self.value, self.filename) def read_images(filename): csv_file = open(filename, rb) reader = csv.reader(csv_file, dialect='excel', delimiter='|') images = [Image(*[field.strip() for field in row]) for row in reader] csv_file.close() return books def sort_images(filename, *attr_names): csv_file = open(filename, rb) reader = csv.reader(csv_file, dialect='excel', delimiter='|') if __name__ == '__main__': images = read_images(rD:\path\to\imagespipe.csv) def get_key(*attr_names): def key(image): return [getattr(image, name) for name in attr_names] return key images.sort(key = get_key(filename)) t = open(r'D:\path\to\filename_sort1.csv', 'w') for image in images: print book #t.write('%s\n' % book) %Before I needed | delimited, this worked #csv.writer(t, dialect='excel', delimiter='|') output = csv.writer(t, dialect='excel', delimiter='|') output.writerows() #output.writerows(image) #output.writerow(image) t.close() This returns an error that says Error: sequence expected My understanding of this is that I am creating a list of lists and I am iterating over it (for image in images), and that image is a list, and is therefore iterable...? I am a bit new at this, and would greatly appreciate any assistance. TIA googleboy -- http://mail.python.org/mailman/listinfo/python-list
Re: Creating Pie Chart from Python
ReportLab Graphics. -Larry Bates Thierry Lam wrote: Let's say I have the following data: 500 objects: -100 are red -300 are blue -the rest are green Is there some python package which can represent the above information in a pie chart? Thanks Thierry -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter add_cascade option_add
Eric Brunel wrote in reply to Bob Greschke: I'm still not sure what your exact requirements are. Do you want to have a different font for the menu bar labels and the menu items and to set them via an option_add? If it is what you want, I don't think you can do it: the menus in the menu bar are just ordinary items for tk, and you can't control separately the different kind of menu items. I guess he has the same problem as I have. See sample code: from Tkinter import * class App(Tk): def __init__(self): Tk.__init__(self) self.option_add('*Menu.font', 'helvetica 24 bold') self.menuBar=Menu(self) self.fileMenu=Menu(self.menuBar,tearoff=0) self.subMenu=Menu(self.fileMenu) self.fileMenu.add_cascade(label='foo', menu=self.subMenu) self.subMenu.add_command(label='bar',command=self.foo) self.subMenu.add_command(label='baz',command=self.foo) self.fileMenu.add_command(label='Quit',command=self.quit) self.menuBar.add_cascade(label='File',menu=self.fileMenu) self.config(menu=self.menuBar) def foo(self): pass app=App() app.mainloop() What happens on my WinXP-box when I run this code is that the menu bar still is displayed in the standard font, which seems to be Helvetica 8. I.e. The text 'File' is still small, while everything else in the menus is displayed in Helvetica 24 bold. Adding font=... to any of the commands above does not change the appearance of 'File'. I have no problems changing the appearance of any individual text in the menu except for the mentioned 'File'. I can change the appearance of 'foo' in the self.fileMenu.add_cascade row, but nothing happens to 'File' if I try to specify a font in the self.menuBar.add_cascade row. Doesn't that seem a bit peculiar? But... The example you gave does not change the appearance of the menus at all on my machine. I guess it was supposed to? Is this simply a Windows-issue that cannot easily be solved? Or is it possibly so that this just happens to be a problem on a few ill-configured computers? Or am I possibly blind? /MiO -- http://mail.python.org/mailman/listinfo/python-list
Re: Britney Spears nude
Tim Peters wrote: [john basha] send me the britney nude photos Because they're a new feature, you'll have to wait for Python 2.5 to be released. She has just spawned a child process. Give her to Python 2.6 to get back in shape. Will McGugan -- http://www.willmcgugan.com .join({'*':'@','^':'.'}.get(c,0) or chr(97+(ord(c)-84)%26) for c in jvyy*jvyyzpthtna^pbz) -- http://mail.python.org/mailman/listinfo/python-list
Re: O'Reilly book on Twisted
On 14 Sep 2005 13:36:53 -0700 Steve M wrote: Does anybody know: What is the relationship between the primary developers of Twisted and the book? Looks like the primary developers will get a copy from the author, at least. :) Having a book is nice, of course, but I'd rather rely on the mailing list and the sources. But I'd buy a book as well, and its cover gives it a +1 point. -- jk -- http://mail.python.org/mailman/listinfo/python-list
Re: read stdout/stderr without blocking
In article [EMAIL PROTECTED], Peter Hansen [EMAIL PROTECTED] wrote: Jacek Pop³awski wrote: Grant Edwards wrote: On 2005-09-12, Jacek Pop?awski [EMAIL PROTECTED] wrote: ready = select.select(tocheck, [], [], 0.25) ##continues after 0.25s for file in ready[0]: try: text = os.read(file, 1024) How do you know here, that you should read 1024 characters? What will happen when output is shorter? It will return however much data is available. My tests showed, that it will block. Not if you use non-blocking sockets, as I believe you are expected to when using select(). On the contrary, you need non-blocking sockets only if you don't use select. select waits until a read [write] would not block - it's like if dict.has_key(x): instead of try: val = dict[x] ; except KeyError:. I suppose you knew that, but have read some obscure line of reasoning that makes non-blocking out to be necessary anyway. Who knows, but it certainly isn't in this case. I don't recall the beginning of this thread, so I'm not sure if this is the usual wretched exercise of trying to make this work on both UNIX and Windows, but there are strong signs of the usual confusion over os.read (a.k.a. posix.read), and file object read. Let's hopefully forget about Windows for the moment. The above program looks fine to me, but it will not work reliably if file object read() is substituted for os.read(). In this case, C library buffering will read more than 1024 bytes if it can, and then that data will not be visible to select(), so there's no guarantee it will return in a timely manner even though the next read() would return right away. Reading one byte at a time won't resolve this problem, obviously it will only make it worse. The only reason to read one byte at a time is for data-terminated read semantics, specifically readline(), in an unbuffered file. That's what happens -- at the system call level, where it's expensive -- when you turn off stdio buffering and then call readline(). In the C vs. Python example, read() is os.read(), and file object read() is fread(); so of course, C read() works where file object read() doesn't. Use select, and os.read (and UNIX) and you can avoid blocking on a pipe. That's essential if as I am reading it there are supposed to be two separate pipes from the same process, since if one is allowed to fill up, that process will block, causing a deadlock if the reading process blocks on the other pipe. Hope I'm not missing anything here. I just follow this group to answer this question over and over, so after a while it gets sort of automatic. Donn Cave, [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter add_cascade option_add
On Thu, Sep 15, 2005 at 06:11:18PM +0200, Mikael Olofsson wrote: Is this simply a Windows-issue that cannot easily be solved? Or is it possibly so that this just happens to be a problem on a few ill-configured computers? Or am I possibly blind? Here's a section from the menu(n) manpage for Tcl. It would appear that the font for the menubar is one of the things which happens 'according to the interface guidelines of their platforms' on win32-family systems. MENUBARS Any menu can be set as a menubar for a toplevel window (see toplevel command for syntax). On the Macintosh, whenever the toplevel is in front, this menu's cascade items will appear in the menubar across the top of the main monitor. On Windows and Unix, this menu's items will be displayed in a menubar accross the top of the window. These menus will behave according to the interface guidelines of their platforms. For every menu set as a menubar, a clone menu is made. See the CLONES sec- tion for more information. As noted, menubars may behave differently on different platforms. One example of this concerns the handling of checkbuttons and radiobuttons within the menu. While it is permitted to put these menu elements on menubars, they may not be drawn with indicators on some platforms, due to system restrictions. On Windows, the font used for the menu can be ajusted by the user for all applications (except those which go out of their way to ignore the user's preferences) using the Display item in Control Panel. Jeff pgpsDs8fAwgrc.pgp Description: PGP signature -- http://mail.python.org/mailman/listinfo/python-list
Re: Creating Pie Chart from Python
Thierry Lam wrote: In a web browser, having a pie chart in some image format will be great. here's a variation of jepler's tkinter example, using aggdraw to do the drawing and PIL to generate the image. tweak as necessary. # http://effbot.org/zone/draw-agg.htm from aggdraw import * # http://www.pythonware.com/products/pil/index.htm import Image def drawchart(size, data, range): draw = Draw(RGB, size, white) bbox = 10, 10, size[0]-10, size[1]-10 for lo, hi, ink in data: lo = 360.0 * lo / range hi = 360.0 * hi / range draw.pieslice(bbox, lo, hi, Brush(ink)) return Image.fromstring(draw.mode, draw.size, draw.tostring()) data = ( (0, 100, red), (100, 400, blue), (400, 500, green) ) im = drawchart((250, 250), data, 500) im.save(chart.png) /F -- http://mail.python.org/mailman/listinfo/python-list