Dr. Dobb's Python-URL! - weekly Python news and links (Nov 13)
QOTW: It is humbling to see how simple yet powerfull python`s view on things is - Ãric Daigneault http://groups.google.com/group/comp.lang.python/msg/bbd842715bb5b6eb [I]f a machine is expected to be infallible, it cannot also be intelligent. - Alan Turing, 20 February 1947, lecture to London Mathematical Socity on ACE URL: http://en.wikipedia.org/wiki/ACE_(computer) Stefan Schukat illustrates an instructive use of COM in a multi-threaded context which manages a MATLAB instance: http://groups.google.com/group/comp.lang.python/browse_thread/thread/c13315f002ab025/ Someone should capture the scattered but valuable observations of this report on Windows-hosted extending into a more enduring document: http://groups.google.com/group/comp.lang.python/browse_frm/thread/36c13e238e6e3bb4 Paul Boddie provides references on concurrency in Python: http://groups.google.com/group/comp.lang.python/msg/4a507814e704b782 Microsoft publicizes IronPython's ASP.Net capabilities: http://www.infoworld.com/archives/emailPrint.jsp?R=printThisA=/article/06/11/07/HNvsiron_1.html http://www.eweek.com/article2/0,1895,2053498,00.asp?kc=EWWHNEMNL110906EOAD The latest release of eric3 supports QScintilla autocompletion, and more: http://www.die-offenbachs.de/detlev/eric.html Is a parameter-holding class reasonable? Probably so, at least on occasion: http://groups.google.com/group/comp.lang.python/browse_thread/thread/64d84ae1de8bd74/ Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. For far, FAR more Python reading than any one mind should absorb, much of it quite interesting, several pages index much of the universe of Pybloggers. http://lowlife.jp/cgi-bin/moin.cgi/PythonProgrammersWeblog http://www.planetpython.org/ http://mechanicalcat.net/pyblagg.html comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/groups?oi=djqas_ugroup=comp.lang.python.announce Python411 indexes podcasts ... to help people learn Python ... Updates appear more-than-weekly: http://www.awaretek.com/python/index.html Steve Bethard continues the marvelous tradition early borne by Andrew Kuchling, Michael Hudson, Brett Cannon, Tony Meyer, and Tim Lesher of intelligently summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/python/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donate.html Kurt B. Kaiser publishes a weekly report on faults and patches. http://www.google.com/groups?as_usubject=weekly%20python%20patch Although unmaintained since 2002, the Cetus collection of Python hyperlinks retains a few gems. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://aspn.activestate.com/ASPN/Cookbook/Python Among several Python-oriented RSS/RDF feeds available are http://www.python.org/channews.rdf http://bootleg-rss.g-blog.net/pythonware_com_daily.pcgi http://python.de/backend.php For more, see
ANN: ludevit 1 available
ludevít is a simple program translating standard Slovak language into the L. Štúr version. The program is probably interesting only to Slovak speakers. Requirements: Python at least version 2.3, only standard library modules are used. The program is intended to be used in Unix environments with UTF-8 locale, but should work everywhere python runs, if you provide UTF-8 input and are content with UTF-8 output. License: GPL =2.0 Where to download: http://kassiopeia.juls.savba.sk/~garabik/software/ludevit/ Online demo: http://vvv.juls.savba.sk/ludevit/ This is an initial release. -- --- | Radovan Garabík http://kassiopeia.juls.savba.sk/~garabik/ | | __..--^^^--..__garabik @ kassiopeia.juls.savba.sk | --- Antivirus alert: file .signature infected by signature virus. Hi! I'm a signature virus! Copy me into your signature file to help me spread! -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
[ANN] httpy 1.0a1 -- smooths out WSGI's worst warts
Greetings, program! I'm pleased to announce version 1.0a1 of httpy, middleware to smooth out WSGI's worst warts. With httpy in your stack, you can return a string, or return or raise an httpy.Response object, instead of mucking with start_response and iterables. This version marks a major change of scope for httpy, from WSGI competitor to itty-bitty middleware. I'm late to the party, but it turns out Kool-Aid is still good warm. Help yourself: http://www.zetadev.com/software/httpy/ Thanks. Chad Whitacre http://www.zetadev.com/ -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
Re: Data structure for ordered sequence
Fredrik Lundh [EMAIL PROTECTED] wrote: [EMAIL PROTECTED] wrote: unless this is homework because the pil people will not let you distribute pils. I'm not sure I can parse this sentence fragment. What do you mean? oh come on! - you of all people should know that pils means mushroom... - Hendrik -- http://mail.python.org/mailman/listinfo/python-list
Re: Python development time is faster.
Chris Brat [EMAIL PROTECTED] wrote: I've seen a few posts, columns and articles which state that one of the advantages of Python is that code can be developed x times faster than languages such as Insert popular language name here. Does anyone have any comments on that statement from personal experience? How is this comparison measured? I don't think it can be, objectively - comparing two teams, one using language a, and the other python, to do a task, is simply comparing the skill levels of the two teams - and using the same team to do the same task in two different languages is also misleading, because of the experience gained in the first iteration. Python is actually astonishing - it seems to fit the brain of a large number of people - it is very easy to get started with, and is rich enough to keep surprising you - even after considerable time hacking around with it. It can do OO, but you can also write procedures in it, and you can even mix the two in the same module, and most of the time it just works - and when it doesn't, it is normally very easy to teach yourself what you are doing wrong by playing at the interactive interpreter prompt. This makes for productivity, as you can write quite complex things in a day or so, from scratch, such as: A single pass assembler for a virtual machine with 33 instructions - from nothing to running, fully debugged, in two days. A simple sliding window protocol - coded up from nothing in four days - mostly spent staring into space, imagining problems, instead of coding... so the design time is included... but its not working yet, as I have to write the other side in assembler on a very small machine, which would normally have taken me almost a month, but that will now probably take about two weeks, as I have the Python code to translate... And I am not a guru on this group, and I have just idly mucked around with Python for about a year in real time, not doing it full time, or making any real effort to study the language formally beyond lurking here - there are other people here on this group who, I am sure, could beat the hell out of these times, both for the design and the coding. So to sum up my personal perspective - it is very worth while to know a little python, even if you just use it as a prototyping language - it gets you going rapidly... - Hendrik -- http://mail.python.org/mailman/listinfo/python-list
Re: Py3K idea: why not drop the colon?
Simon Brunning [EMAIL PROTECTED] Wrote: On 11/11/06, Fredrik Lundh [EMAIL PROTECTED] wrote: Hendrik van Rooyen wrote: blue is red or green or yellow *grin* - this can be construed as a weakness in Python - it's boolean logic, and it's incompatible with human use of the same terms in all contexts, not just Python. Indeed. The other day, I way showing my eight year old, Freja, what a program looks like: your_name = raw_input(What's your name? ) if your_name.lower() == freja: print You're very stinky,, your_name else: print You smell lovely, , your_name After running it a couple of times, she dove in and changed the 2nd line to: if your_name.lower() == daddy or ella: (Ella is my other daughter's name.) That's pretty close to correct, I'd say - but you don't get anything for being close in a programming language. This is true - and it is actually also an intractable problem - if you look at what your daughter wrote, you get the feeling that you should be able to write an interpreter that can implement what she meant, because it is quite clear to you - until you try to write the specs... Your daughter, btw, will go far if she already has the guts to do that... - Hendrik -- http://mail.python.org/mailman/listinfo/python-list
Re: Py3K idea: why not drop the colon?
Robert Kern [EMAIL PROTECTED] wrote: Michael Hobbs wrote: True enough. Although, I have to ask how many times you define a new function only to have Python spit a syntax error out at you saying that you forgot a colon. It happens to me all the time. (Usually after an else) If you'd never notice that the colon was missing if the compiler didn't point it out, is it really that readable? For me, I tend to get annoyed at language features that I'm constantly tripping over. Never. I confess I find myself in the position of a Yorkshire Youngster - I don't believe you! - Hendrik -- http://mail.python.org/mailman/listinfo/python-list
Re: handling many default values
Gabriel Genellina wrote: At Monday 13/11/2006 13:33, Michele Simionato wrote: Alan Isaac wrote: Also, as an aside, no one objected to using self.__dict__.update(kwargs) in the __init__ function of the parameter holding class. It is a common trick, also shown in the Python cookbook, IIRC. If you are anal about double underscores, you can also use vars(self).update(kwargs) Not good - that relies on vars() returning the actual __dict__. From http://docs.python.org/lib/built-in-funcs.html: The returned dictionary should not be modified: the effects on the corresponding symbol table are undefined. I believe the issue is with classes, where vars(klass) returns a dictproxy which is read only. In the case of instances (i.e. the OP' case) vars(self) returns the instance dictionary and my suggestion is correct. However you was right to point out this subtility, it is always worth to know. Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
deleteing item from a copy of a list
i make a copy of a list, and delete an item from it and it deletes it from the orginal as well, what the hell is going on?!?!?! #create the staff copy of the roster Roster2 = [] for ShiftLine in Roster: #delete phone number from staff copy Roster2.append(ShiftLine) del Roster2[len(Roster2)-1][1] Roster2 should have nothing to do with Roster, right??? doing a print of both lists confirms that the phone number has been removed from both -- http://mail.python.org/mailman/listinfo/python-list
Re: deleteing item from a copy of a list
timmy wrote: i make a copy of a list, and delete an item from it and it deletes it from the orginal as well, what the hell is going on?!?!?! #create the staff copy of the roster Roster2 = [] for ShiftLine in Roster: #delete phone number from staff copy Roster2.append(ShiftLine) del Roster2[len(Roster2)-1][1] Roster2 should have nothing to do with Roster, right??? doing a print of both lists confirms that the phone number has been removed from both you're not removing something from Roster2, you're removing something from the last item in Roster2. the append methods adds a reference to an object to a list; it doesn't copy the object. /F -- http://mail.python.org/mailman/listinfo/python-list
Re: __cmp__ between dissimilar objects
When the rich comparison methods raise NotImplementedError, the comparison logic inside the interpreter tries reversing the operands. Can you point me to a description of this algorithm? It doesn't seem to be described in the documentation for the rich comparison or __cmp__ methods... -Ben -- http://mail.python.org/mailman/listinfo/python-list
Re: Is python for me?
On Mon, 13 Nov 2006 09:11:13 -0800, lennart wrote: Hi, I'm planning to learn a language for 'client' software. Until now, i 'speak' only some web based languages, like php. As a kid i programmed in Basic (CP/M, good old days :'-) ) Now i want to start to learn a (for me) new computer language. I like Python. Its free, easy to learn and some favorite programs of my are written in Python / can understand Python (like OpenOffice) etc. But I'm not a full-time programmer. I know, that I've only time possibility to learn one (= 1) language good. So i ask myself is python the language I'm looking for? ... I've been hesitant to write this in the past but seems like a good time. I'm at the same stage, but (and this is NOT a troll) I'm tossing up between Python and Ruby. I know this has been discussed numerous times but I'd like to come at it from a different angle. I've been 'playing' with both languages and to be honest it's a case of 6 of one, half a dozen of the other. If I'm using python I 'think' python and if I'm using Ruby I 'think' ruby (if that makes sense). Ie I don't find I'm more productive in one over the other to any great extent (pretty unproductive in both ATM to be honest ;-)) . In the foreseeable future I suspect I'll stick with one and just use it for things I personally will use/need. But (and here's where I finally get to a question) I use Linux, I love the whole idea of open source and contributing in some way. So if I ever get to the stage where I can give something back is one preferred over the other? I would have thought no but I read on the Ubuntu site somewhere that they prefer contributions written in Python/ pyGTK?? Is this just a 'preference' or because python is installed by default? (whereas Ruby isn't)? Is it just Ubuntu or Linux distros in general? I hope you can see where I'm coming from here. I don't want to start a Python/Ruby flame war. That's not the question. The question is is one preferred over the other when contributing software and is this just a particular distros preference? cheers, -- Mark -- http://mail.python.org/mailman/listinfo/python-list
Re: deleteing item from a copy of a list
timmy timothy at open-networks.net wrote: i make a copy of a list, and delete an item from it and it deletes it from the orginal as well, what the hell is going on?!?!?! #create the staff copy of the roster Roster2 = [] for ShiftLine in Roster: #delete phone number from staff copy Roster2.append(ShiftLine) del Roster2[len(Roster2)-1][1] Roster2 should have nothing to do with Roster, right??? doing a print of both lists confirms that the phone number has been removed from both You seem to have a list of lists and are making a new outer list. The lists inside that outer list are not copied. You can copy them by calling list(item) or copy.copy(item): roster = [ ... [Tim, 12345, some more], ... [Jack, 54321, whatever], ... ] roster2 = [] for item in roster: ... item = list(item) ... del item[1] ... roster2.append(item) ... roster [['Tim', '12345', 'some more'], ['Jack', '54321', 'whatever']] roster2 [['Tim', 'some more'], ['Jack', 'whatever']] Peter -- http://mail.python.org/mailman/listinfo/python-list
Seeking assistance - string processing.
I've been working on some code to search for specific textstrings and act upon them insome way. I've got the conversion sorted however there is 1 problem remaining. I am trying to work out how to make it find a string like this === and when it has found it, I want it to add === to the end of the line. For example. The text file contains this: ===Heading and I am trying to make it be processed and outputted as a .dat file with the contents ===Heading=== Here's the code I have got so far. import string import glob import os mydir = os.getcwd() newdir = mydir#+\\Test\\; for filename in glob.glob1(newdir,*.txt): #print This is an input file: + filename fileloc = newdir+\\+filename #print fileloc outputname = filename outputfile = string.replace(outputname,'.txt','.dat') #print filename #print a print This is an input file: + filename + . Output file: +outputfile #temp = newdir + \\ + outputfile #print temp fpi = open(fileloc); fpo = open(outputfile,w+); output_lines = [] lines = fpi.readlines() for line in lines: if line.rfind() is not -1: new = line.replace(,) elif line.rfind(img:) is not -1: new = line.replace(img:,[[Image:) elif line.rfind(.jpg) is not -1: new = line.replace(.jpg,.jpg]]) elif line.rfind(.gif) is not -1: new = line.replace(.gif,.gif]]) else: output_lines.append(line); continue output_lines.append(new); for line in output_lines: fpo.write(line) fpi.close() fpo.flush() fpo.close() I hope this gets formatted correctly :-p Cheers, hope you can help. -- http://mail.python.org/mailman/listinfo/python-list
Re: Data structure for ordered sequence
Hendrik van Rooyen wrote: Fredrik Lundh [EMAIL PROTECTED] wrote: [EMAIL PROTECTED] wrote: unless this is homework because the pil people will not let you distribute pils. I'm not sure I can parse this sentence fragment. What do you mean? oh come on! - you of all people should know that pils means mushroom... Cue yet another appearance of badgerbadgerbadger? regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden -- http://mail.python.org/mailman/listinfo/python-list
Re: Seeking assistance - string processing.
[EMAIL PROTECTED] wrote: Thanks so much, a really elegant solution indeed. I have another question actually which I'm praying you can help me with: with regards to the .jpg conversion to .jpg]] and .gif - .gif]] this works, but only when .jpg/.gif is on it's own line. i.e: .jpg will get converted to: .jpg]] but Image:test.jpg gets converted to: [[Image:test.jpg rather than [[Image:test.jpg]] -- Hope you can help again! Cheers It does not do the right thing in all cases, but maybe you can get away with for line in lines: if line.startswith(===): line = line.rstrip() + ===\n line = line.replace(,) line = line.replace(img:,[[Image:) line = line.replace(.jpg,.jpg]]) line = line.replace(.gif,.gif]]) output_lines.append(line) Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Seeking assistance - string processing.
Cheers for the reply. But I'm still having a spot of bother with the === addition it would seem that if there is no whitespace after the ===test then the new === gets added to the next line e.g file contains: ===test (and then no whitesapace/carriage returns or anything) and the result is: ===test === I tried fidding aruond trying to make it add whitespace but it didnt work. What do you think I should do? Cheers -- http://mail.python.org/mailman/listinfo/python-list
Re: Using signal.alarm to terminate a thread
Nick Craig-Wood wrote: Adrian Casey [EMAIL PROTECTED] wrote: I have a multi-threaded python application which uses pexpect to connect to multiple systems concurrently. Each thread within my application is a connection to a remote system. The problem is when one of the child threads runs a command which generates an unlimited amount of output. The classic example of this is the yes command. If you execute pexpect.run('yes'), your cpu will sit at 100% forever. Here is a simple multi-threaded program using pexpect which demonstrates the problem. The command 'yes' is run in a thread. The parent says that when the alarm goes off, run the handler function. The thread sets the alarm to trigger after 5 seconds. 1) Don't ever mix threads and signals - you are heading for trouble! 2) pexpect has a timeout parameter exactly for this case import os, pexpect, threading def runyes(): print Running yes command... pexpect.run('yes', timeout=5) t = threading.Thread(target=runyes) t.start() t.join() The timeout parameter will not work in this case. If you run the sample code above, it will run forever. The 'yes' command presents a class of command which can not be easily be handled by pexpect. As far as I know, mixing threads and signals is OK provided the parent creates the alarm. Adrian. -- http://mail.python.org/mailman/listinfo/python-list
Re: Py3K idea: why not drop the colon?
Antoon Pardon wrote: Why not? My impression is that removing redundancy is considered a positive thing here in c.p.l. so why are you still here? /F -- http://mail.python.org/mailman/listinfo/python-list
Re: Python 2.5 Core Dump on Solaris 8
Hi Melissa, I run into similar problems after compiling python-ldap 2.2.0 for Python 2.5 on SuSE Linux 9.3 and running a small commandline application *** glibc detected *** double free or corruption (out): 0x40180788 *** I realy suspect the _ldap.so file. I have not found a solution yet, but will let you know if I do. Did you compile python-ldap yourself for Python 2.5? Which version of python-ldap? Which compiler? Regards Anthon Melissa Evans wrote: Hi. I'm new to Python. :) I've modified grappy.py, http://www.stacken.kth.se/~mattiasa/projects/grappy/, a postfix policy daemon for greylisting. to use LDAP as a backend instead of SQL (with python-ldap.) The daemon runs fine when testing but when I put it under load it core dumps quickly. What little analysis I know how to do shows similar information every time. Any advice on where to go from here? Thanks! Melissa -- http://mail.python.org/mailman/listinfo/python-list
Re: Seeking assistance - string processing.
[EMAIL PROTECTED] wrote: I am trying to work out how to make it find a string like this === and when it has found it, I want it to add === to the end of the line. how about if line.startswith(===): line = line + === or if === in line: # anywhere line = line + === ? if line.rfind() is not -1: new = line.replace(,) it's not an error to use replace on a string that doesn't contain the pattern, so that rfind is rather unnecessary. (and for cases where you need to look first, searching from the left is usually faster than searching backwards; use pattern in line or line.find(pattern) instead of rfind. /F -- http://mail.python.org/mailman/listinfo/python-list
Re: Is python for me?
Mark Woodward wrote: On Mon, 13 Nov 2006 09:11:13 -0800, lennart wrote: Hi, I'm planning to learn a language for 'client' software. Until now, i 'speak' only some web based languages, like php. As a kid i programmed in Basic (CP/M, good old days :'-) ) Now i want to start to learn a (for me) new computer language. I like Python. Its free, easy to learn and some favorite programs of my are written in Python / can understand Python (like OpenOffice) etc. But I'm not a full-time programmer. I know, that I've only time possibility to learn one (= 1) language good. So i ask myself is python the language I'm looking for? I've been hesitant to write this in the past but seems like a good time. I'm at the same stage, but (and this is NOT a troll) I'm tossing up between Python and Ruby. I know this has been discussed numerous times but I'd like to come at it from a different angle. I've been 'playing' with both languages and to be honest it's a case of 6 of one, half a dozen of the other. If I'm using python I 'think' python and if I'm using Ruby I 'think' ruby (if that makes sense). Ie I don't find I'm more productive in one over the other to any great extent (pretty unproductive in both ATM to be honest ;-)) . In the foreseeable future I suspect I'll stick with one and just use it for things I personally will use/need. But (and here's where I finally get to a question) I use Linux, I love the whole idea of open source and contributing in some way. So if I ever get to the stage where I can give something back is one preferred over the other? I would have thought no but I read on the Ubuntu site somewhere that they prefer contributions written in Python/ pyGTK?? Is this just a 'preference' or because python is installed by default? (whereas Ruby isn't)? Is it just Ubuntu or Linux distros in general? I hope you can see where I'm coming from here. I don't want to start a Python/Ruby flame war. That's not the question. The question is is one preferred over the other when contributing software and is this just a particular distros preference? Ubuntu is pretty much a Python-oriented distribution. A lot of people like it because you always get a fairly up-to-date Python with lots of extras available. I don't know that much about Ruby, but the best approach to software development has always been to choose the best language for solving the problem, so you seem to be doing OK. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden -- http://mail.python.org/mailman/listinfo/python-list
Re: deleteing item from a copy of a list
timmy wrote: i make a copy of a list, and delete an item from it and it deletes it from the orginal as well, what the hell is going on?!?!?! #create the staff copy of the roster Roster2 = [] for ShiftLine in Roster: #delete phone number from staff copy Roster2.append(ShiftLine) del Roster2[len(Roster2)-1][1] Roster2 should have nothing to do with Roster, right??? doing a print of both lists confirms that the phone number has been removed from both First of all, you could have said del Roster2[-1][1] since negative indices count backwards from the end of the list. This has nothing to do with your problem, though. Fredrik has already given you a correct, somewhat condensed, answer. Let me elaborate. I guess that Roster is a list of lists. Then actually, it is a list of references to lists (really a reference to a list of references to lists). Your for-loop makes Roster2 a shallow copy of Roster, i.e. Roster2 is a new list with references to the _same_ sublists as in Roster. So, Roster2[-1] references the same object as Roster[-1], not a copy of it. To get copies, you could change your .append-line to Roster2.append(ShiftLine[:]) which gives you shallow copies of the sublists. If there are mutables in the sublists, you may still get into trouble. In that case, maybe you should take a look at copy.deepcopy. HTH /MiO -- http://mail.python.org/mailman/listinfo/python-list
Re: Multithreaded C API Python questions
Hi! I think I've found the bug, but I need to confirm this behavior. My findings is that if you use PyEval_InitThreads(), it is crucial to release the GIL with PyEval_ReleaseThread() afterwards. The API docs states that you can release the GIL with PyEval_ReleaseLock() or PyEval_ReleaseThread() AFAICS. http://docs.python.org/api/threads.html under docs of void PyEval_InitThreads(). However, if I do use PyEval_ReleaseLock() it will crash shortly after with Fatal Python error: ceval: tstate mix-up in a multithreaded C environment. If I use PyEval_ReleaseThread() to release the GIL, my app seems stable. I release the GIL like this: PyThreadState *pts = PyGILState_GetThisThreadState(); PyEval_ReleaseThread(pts); Now, is this a feature or expected behavior in python (i.e. unclear API documentation), or is this a bug in python itself? Regards, Svein PS: For reference I did something like this in pseudo-code: Py_Initialize(); PyEval_InitThreads(); other_py_inits(); // Load py modules, etc. PyEval_ReleaseLock();// -- MAKES THE APP UNSTABLE create_c_thread(); PyGILState_STATE gstate; gstate = PyGILState_Ensure(); call_py_function_main(); // Py main() wont return PyGILState_Release(gstate); And the main of the C thread function looks like this: while(1) { PyGILState_STATE gstate; gstate = PyGILState_Ensure(); call_py_function_send(); PyGILState_Release(gstate); } -- http://mail.python.org/mailman/listinfo/python-list
Re: to setattr or def setProp()
[EMAIL PROTECTED] wrote: I have a class for rectangle and it has two points in its __slots__ . However, we can derive a number of properties like width, height, centerPoint etc from these two points. Now, I want to be able to set and get these properties directly from the instances. I can either def __setattr__ , __getattr__ But this won't help with introspection... or I can define function for each property like setWidth(), setHeight() . Which one would be faster? You mean faster performances or faster to implement ? I would prefer doing through __setattr__, __getattr__ because it makes the code more readable. You mean the client code ? However, speed is a concern I would have to do these operations in few thousand iterations for about 50-100 rectangles. The canonical solution is to use either properties or custom descriptors[1]. Custom descriptors should be a bit faster than properties (since you save a couple function calls), but I have not done any benchmark... It should also be a bit faster than __getattr__, which is only used as a fallback when all other lookup rules have failed (here again, don't take me on words and do some benchmarking). As a last point, descriptors show up as class and instance attributes, which helps with introspection. class Height(object): def __get__(self, instance, cls): if instance is None: return self return instance.bottomright.y - instance.topleft.y def __set__(self, instance, value): instance.bottomright.y = instance.topleft.y + value class Width(object): def __get__(self, instance, cls): if instance is None: return self return instance.bottomright.x - instance.topleft.x def __set__(self, instance, value): instance.bottomright.x = instance.topleft.x + value class Rectangle(object): def __init__(self): self.topleft = Point(10, 10) self.bottomright = Point(20, 30) height = Height() width = Width() r = Rectangle() r.with = 40 (not tested) [1] : * http://docs.python.org/ref/descriptors.html * http://users.rcn.com/python/download/Descriptor.htm My 2 cents... -- 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: Py3K idea: why not drop the colon?
On 2006-11-14, Fredrik Lundh [EMAIL PROTECTED] wrote: Antoon Pardon wrote: Why not? My impression is that removing redundancy is considered a positive thing here in c.p.l. so why are you still here? Because I have a different opinion and I don't need your permission. -- Antoon Pardon -- http://mail.python.org/mailman/listinfo/python-list
PyFAQ: help wanted with thread article
this FAQ item talks about using sleep to make sure that threads run properly: http://effbot.org/pyfaq/none-of-my-threads-seem-to-run-why.htm I suspect it was originally written for the thread module, but as far as I know, the threading module takes care of the issues described here all by itself. so, should this item be removed? or can anyone suggest a rewrite that's more relevant for threading users. feel free to post suggestions (or better, an updated text) to this thread, or over at the PyFAQ staging site. /F -- http://mail.python.org/mailman/listinfo/python-list
RE: sqlite3 views, if not exists clause
[Josh] | I'm running into a problem when trying to create a view in my sqlite | database in python. I think its a bug in the sqlite3 api that | comes with python 2.5. | THIS DOES NOT WORK, but it should! | conn = sqlite3.connect(':memory:') | conn.execute(create table foo (a int,b int)) | conn.execute('create view if not exists bar as select * from foo') | it fails with exception sqlite3.OperationalError: near | not: syntax error Not a bug with the sqlite3 api that comes with python 2.5. as such, since .execute pretty much passes its parameters through to the database engine. Rather, the syntax you're using is a relatively late addition to the sqlite libs -- at least it fails on my 3.2.1 version of the sqlite3 commmand-line tool, but succeeds on the latest download (3.3.8). I presume therefore that you build of Python is linked against an older version of the sqlite libraries / DLL. TJG This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk -- http://mail.python.org/mailman/listinfo/python-list
sqlite3 views, if not exists clause
Hi, I'm running into a problem when trying to create a view in my sqlite database in python. I think its a bug in the sqlite3 api that comes with python 2.5. This works as expected: conn = sqlite3.connect(':memory:') conn.execute(create table foo (a int,b int)) conn.execute('create view bar as select * from foo') This fails as expected: conn = sqlite3.connect(':memory:') conn.execute(create table foo (a int,b int)) conn.execute('create view bar as select * from foo') conn.execute('create view bar as select * from foo') with exception sqlite3.OperationalError: table bar already exists. Weird that it fails with TABLE bar already exists, but this is the message that sqlite actually returns so it is not python's fault. THIS DOES NOT WORK, but it should! conn = sqlite3.connect(':memory:') conn.execute(create table foo (a int,b int)) conn.execute('create view if not exists bar as select * from foo') it fails with exception sqlite3.OperationalError: near not: syntax error Can anyone confirm, or pass this on to the appropriate person? Thanks! Josh -- http://mail.python.org/mailman/listinfo/python-list
Re: sqlite3 views, if not exists clause
Josh wrote: THIS DOES NOT WORK, but it should! Python 2.5 was released on September 19th, 2006, and support for CREATE VIEW IF NOT EXISTS was added to sqlite on October 9th, 2006: http://www.sqlite.org/changes.html /F -- http://mail.python.org/mailman/listinfo/python-list
Using ctypes with Windows API to get FileVersion of a file
Hi, I need to get the FileVersion of some files on Windows. The best way look like to use function GetFileVersionInfo from the Windows API. I first try with pywin32 and it work well, but with ctypes now included in Python 2.5, use it look like a good idea. So I write the code below that work fine, but I'm not sure it's the best way to do what I want. My main concern is about the codepages extraction: could I use a struct to make the job ? Codepages is actually an array of struct, how could I use ctypes to extract it ? Thanks for your comments and advices. import array from ctypes import * def get_file_info(filename, info): Extract information from a file. # Get size needed for buffer (0 if no info) size = windll.version.GetFileVersionInfoSizeA(filename, None) # If no info in file - empty string if not size: return '' # Create buffer res = create_string_buffer(size) # Load file informations into buffer res windll.version.GetFileVersionInfoA(filename, None, size, res) r = c_uint() l = c_uint() # Look for codepages windll.version.VerQueryValueA(res, '\\VarFileInfo\\Translation', byref(r), byref(l)) # If no codepage - empty string if not l.value: return '' # Take the first codepage (what else ?) codepages = array.array('H', string_at(r.value, l.value)) codepage = tuple(codepages[:2].tolist()) # Extract information windll.version.VerQueryValueA(res, ('\\StringFileInfo\\%04x%04x\\' + info) % codepage, byref(r), byref(l)) return string_at(r.value, l.value) print get_file_info(r'C:\WINDOWS\system32\calc.exe', 'FileVersion') -- http://mail.python.org/mailman/listinfo/python-list
Re: Programmatically finding significant data points
erikcw wrote: I have a collection of ordered numerical data in a list. The numbers when plotted on a line chart make a low-high-low-high-high-low (random) pattern. I need an algorithm to extract the significant high and low points from this data. Here is some sample data: data = [0.10, 0.50, 0.60, 0.40, 0.39, 0.50, 1.00, 0.80, 0.60, 1.20, 1.10, 1.30, 1.40, 1.50, 1.05, 1.20, 0.90, 0.70, 0.80, 0.40, 0.45, 0.35, 0.10] silly solution: for i in range(1, len(data)-1): if data[i-1] data[i] data[i+1] or data[i-1] data[i] data[i+1]: print i (the above doesn't handle the edges, but that's easy to fix) /F -- http://mail.python.org/mailman/listinfo/python-list
Re: Programmatically finding significant data points
erikcw [EMAIL PROTECTED] wrote: I have a collection of ordered numerical data in a list. The numbers when plotted on a line chart make a low-high-low-high-high-low (random) pattern. I need an algorithm to extract the significant high and low points from this data. I am not sure, what you mean by 'ordered' in this context. As pointed out by Jeremy, you need to find an appropriate statistical test. The appropriateness depend on how your data is (presumably) distributed and what exactly you are trying to test. E.g. do te data pints come from differetn groupos of some kind? Or are you just looking for extreme values (outliers maybe?)? So it's more of statistical question than a python one. cu Philipp -- Dr. Philipp Pagel Tel. +49-8161-71 2131 Dept. of Genome Oriented BioinformaticsFax. +49-8161-71 2186 Technical University of Munich http://mips.gsf.de/staff/pagel -- http://mail.python.org/mailman/listinfo/python-list
graphical class diagram tool?
Hi all Some years ago I saw a graphical class diagram generated by examining a python program. I *thought* that this was done with Boa Constructor, but I may be wrong. I've download a recent version of BC and can't find reference to this feature. Can anyone point me at other tools to do this? Thanks J^n -- http://mail.python.org/mailman/listinfo/python-list
Re: __init__.py
km wrote: what is the use of __init__.py file in a module dir ? it tells Python that the directory is a package directory. if you have mydir/foo/__init__.py mydir/foo/module.py and mydir is on the path, you can do import foo.module or from foo import module. if you remove the __init__.py file, Python will no longer look for submodules inside that directory. Is it used to initialize variables that could be shared across sub modules if set in __init__.py at root dir of module ? it's usually empty, or used to export selected portions of the package under more convenient names. given the example above, the contents of the __init__ module can be accessed via: import foo /F -- http://mail.python.org/mailman/listinfo/python-list
Re: Programmatically finding significant data points
Jeremy Sanders [EMAIL PROTECTED] writes: How do I sort through this data and pull out these points of significance? Get a book on statistics. One idea is as follows. If you expect the points to be centred around a single value, you can calculate the median or mean of the points, calculate their standard deviation (aka spread), and remove points which are more than N-times the standard deviation from the median. Standard deviation was the first thought that jumped to my mind too. However, that's not what the OP is after. He's seems to be looking for points when the direction changes. Ganesan -- Ganesan Rajagopal -- http://mail.python.org/mailman/listinfo/python-list
Re: Using signal.alarm to terminate a thread
Adrian Casey [EMAIL PROTECTED] wrote: Adrian Casey [EMAIL PROTECTED] wrote: import os, pexpect, threading def runyes(): print Running yes command... pexpect.run('yes', timeout=5) t = threading.Thread(target=runyes) t.start() t.join() The timeout parameter will not work in this case. If you run the sample code above, it will run forever. The above runs just fine for me, stopping after 5 seconds. Did you try it? The 'yes' command presents a class of command which can not be easily be handled by pexpect. Worked for me under Debian/testing. As far as I know, mixing threads and signals is OK provided the parent creates the alarm. There are so many pitfalls here that I advise you not to try. From the linuxthreads FAQ J.3: How shall I go about mixing signals and threads in my program? The less you mix them, the better. Notice that all pthread_* functions are not async-signal safe, meaning that you should not call them from signal handlers. This recommendation is not to be taken lightly: your program can deadlock if you call a pthread_* function from a signal handler! The only sensible things you can do from a signal handler is set a global flag, or call sem_post on a semaphore, to record the delivery of the signal. The remainder of the program can then either poll the global flag, or use sem_wait() and sem_trywait() on the semaphore. Another option is to do nothing in the signal handler, and dedicate one thread (preferably the initial thread) to wait synchronously for signals, using sigwait(), and send messages to the other threads accordingly. Note also that the signal can be delivered to any thread which complicates things. -- Nick Craig-Wood [EMAIL PROTECTED] -- http://www.craig-wood.com/nick -- http://mail.python.org/mailman/listinfo/python-list
Re: Programmatically finding significant data points
If the order doesn't matter, you can sort the data and remove x * 0.5 * n where x is the proportion of numbers you want. If you have too many similar values though, this falls down. I suggest you check out quantiles in a good statistics book. Alan. Peter Otten wrote: erikcw wrote: Hi all, I have a collection of ordered numerical data in a list. The numbers when plotted on a line chart make a low-high-low-high-high-low (random) pattern. I need an algorithm to extract the significant high and low points from this data. Here is some sample data: data = [0.10, 0.50, 0.60, 0.40, 0.39, 0.50, 1.00, 0.80, 0.60, 1.20, 1.10, 1.30, 1.40, 1.50, 1.05, 1.20, 0.90, 0.70, 0.80, 0.40, 0.45, 0.35, 0.10] In this data, some of the significant points include: data[0] data[2] data[4] data[6] data[8] data[9] data[13] data[14] How do I sort through this data and pull out these points of significance? I think you are looking for extrema: def w3(items): items = iter(items) view = None, items.next(), items.next() for item in items: view = view[1:] + (item,) yield view for i, (a, b, c) in enumerate(w3(data)): if a b c: print i+1, min, b elif a b c: print i+1, max, b else: print i+1, ---, b Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Seeking assistance - string processing.
[EMAIL PROTECTED] wrote: Cheers for the reply. But I'm still having a spot of bother with the === addition it would seem that if there is no whitespace after the ===test then the new === gets added to the next line e.g file contains: ===test (and then no whitesapace/carriage returns or anything) and the result is: ===test === You'd get the above with Fredrik's solution if there is a newline. That's why I put in the rstrip() method call (which removes trailing whitespace) and added an explicit \n (the Python way to spell newline). With my approach if line.startswith(===): line = line.rstrip() + ===\n you should always get ===test===(and then a newline) Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: PyFAQ: help wanted with thread article
Fredrik Lundh a écrit : this FAQ item talks about using sleep to make sure that threads run properly: http://effbot.org/pyfaq/none-of-my-threads-seem-to-run-why.htm I suspect it was originally written for the thread module, but as far as I know, the threading module takes care of the issues described here all by itself. so, should this item be removed? or can anyone suggest a rewrite that's more relevant for threading users. feel free to post suggestions (or better, an updated text) to this thread, or over at the PyFAQ staging site. Maybe it could be modified to indicate (for threading) existence of daemon and non-daemon threads. /F -- http://mail.python.org/mailman/listinfo/python-list
Re: __init__.py
Hi, I have a structure like this : foo/__init__.py foo/bar/__init__.py foo/bar/firstmodule.py foo/abc/__init__.py foo/abc/secondmodule.py now i have some variables (paths to data files) common, to be used in first module and second modules respectively. can i set those variables in foo/__init__.py so that i can access them by foo.mypath1 in first and second submodule class definitions? if not anyother way out ? regards, KMOn 11/14/06, Fredrik Lundh [EMAIL PROTECTED] wrote: km wrote: what is the use of __init__.py file in a module dir ?it tells Python that the directory is a package directory.if you have mydir/foo/__init__.py mydir/foo/module.py and mydir is on the path, you can do import foo.module or from fooimport module.if you remove the __init__.py file, Python will nolonger look for submodules inside that directory. Is it used to initialize variablesthat could be shared across sub modulesif set in __init__.py at root dirof module ?it's usually empty, or used to export selected portions of the packageunder more convenient names.given the example above, the contents of the __init__ module can be accessed via: import foo/F--http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Seeking assistance - string processing.
[EMAIL PROTECTED] wrote: But I'm still having a spot of bother with the === addition it would seem that if there is no whitespace after the ===test then the new === gets added to the next line e.g file contains: ===test (and then no whitesapace/carriage returns or anything) and the result is: ===test === that's probably because it *does* contain a newline. try printing the line with print repr(line) before and after you make the change, to see what's going on. I tried fidding aruond trying to make it add whitespace but it didnt work. peter's complete example contains one way to solve that: if line.startswith(===): line = line.rstrip() + ===\n What do you think I should do? reading the chapter on strings in your favourite Python tutorial once again might help, I think. python have plenty of powerful tools for string processing, and most of them are quite easy to learn and use; a quick read of the tutorial and a little more trial and error before posting should be all you need. /F -- http://mail.python.org/mailman/listinfo/python-list
Re: Seeking assistance - string processing.
[EMAIL PROTECTED] wrote: I've been working on some code to search for specific textstrings and act upon them insome way. I've got the conversion sorted What does that mean? There is no sort in the computer sense, and if you mean as in done ... however there is 1 problem remaining. I am trying to work out how to make it find a string like this === and when it has found it, I want it to add === to the end of the line. The answer is at the end. Now take a deep breath, and read on carefully and calmly: For example. The text file contains this: ===Heading and I am trying to make it be processed and outputted as a .dat file with the contents ===Heading=== Here's the code I have got so far. import string Not needed for this task. In fact the string module has only minimal use these days. From what book or tutorial did you get the idea to use result = string.replace(source_string, old, new) instead of result = source_string.replace(old, new) sometimes? You should be using the result = source_string.replace(old, new) way all the time. What version of Python are you using? import glob import os mydir = os.getcwd() newdir = mydir#+\\Test\\; Try and make a real comment obvious; don't do what you did -- *delete* unwanted code; alternatively if it may be wanted in the future, put in a real comment to say why. What was the semicolon for? Consider using os.path.join() -- it's portable. Don't say But my code will only ever be run on Windows. If you write code like that, it will be a self-fulfilling prophecy -- no-one will want try to run it anywhere else. for filename in glob.glob1(newdir,*.txt): #print This is an input file: + filename No it isn't; it's a *name* of a file fileloc = newdir+\\+filename #print fileloc outputname = filename outputfile = string.replace(outputname,'.txt','.dat') No again, it's not a file. Try outputname = filename.replace('.txt', '.dat') Also consider what happens if the name of the input file is foo.txt.txt [can happen] #print filename #print a print This is an input file: + filename + . Output file: +outputfile No it isn't. #temp = newdir + \\ + outputfile #print temp fpi = open(fileloc); fpo = open(outputfile,w+); Why the +? Semi-colons? output_lines = [] Why not just write as you go? What happens with a 1GB file? How much memory do you have on your computer? lines = fpi.readlines() Whoops. That's now 2GB min of memory you need for line in lines: No, use for line in fpi if line.rfind() is not -1: Quick, somebody please count the - signs in there; we'd really like to know what this program is doing. If there are more identical characters than you have fingers on your hand, don't do that. Use character.repeat(count). Then consider giving it a name. Consider putting in a comment to explain what your code is doing. If you can, like why use rfind instead of find -- both will give the same result if there are 0 or 1 occurrences of the sought string, and you aren't using the position if there are 1 or more occurences. Then consider that if you need a a comment for code like that, then maybe your variable names are not very meaningful. new = line.replace(--,) Is that the same number of -? Are you sure? elif line.rfind(img:) is not -1: new = line.replace(img:,[[Image:) elif line.rfind(.jpg) is not -1: new = line.replace(.jpg,.jpg]]) That looks like a pattern to me. Consider setting up a list of (old, new) tuples and looping over it. elif line.rfind(.gif) is not -1: new = line.replace(.gif,.gif]]) else: output_lines.append(line); continue output_lines.append(new); Try this: else: new = line fpo.write(new) for line in output_lines: fpo.write(line) fpi.close() fpo.flush() News to me that close() doesn't automatically do flush() on a file that's been open for writing. fpo.close() I hope this gets formatted correctly :-p Cheers, hope you can help. Answer to your question: string1 in string2 beats string2.[r]find(string1) for readability and (maybe) for speed too elif === in line: # should be same to assume your audience can count to 3 new = line[:-1] + ===\n HTH, John -- http://mail.python.org/mailman/listinfo/python-list
Re: graphical class diagram tool?
nic a écrit : Hi all Some years ago I saw a graphical class diagram generated by examining a python program. I *thought* that this was done with Boa Constructor, but I may be wrong. I've download a recent version of BC and can't find reference to this feature. Can anyone point me at other tools to do this? Maybe pyreverse : http://www.logilab.org/view?rql=Any%20X%20WHERE%20X%20eid%202560 I have other links here: http://www.limsi.fr/Individu/pointal/python.html#liens-metaprog A+ -- http://mail.python.org/mailman/listinfo/python-list
Re: Research Master 0.1 (GPL/Python)
[EMAIL PROTECTED] wrote: ResearchMaster has been designed to simplify management of research literature. It is a GUI interface to a system of folders and records. Each record contains notes, meta info and BibTex info about an associated file. Instances of the single copy of a record can occur throughout the folder system, as specified through a membership list. A single button creates a recursive bibliography of all records containing BibTex information which are children of the currently selected parent node. One click launching of files by an associated application is also supported. A tutorial document is included. http://www.asymptopia.org The Windows version seems to offer a great way to burn cycles but not much else. Colin W. PS What's the connection to Python? -- http://mail.python.org/mailman/listinfo/python-list
Re: Seeking assistance - string processing.
Thanks so much, a really elegant solution indeed. I have another question actually which I'm praying you can help me with: with regards to the .jpg conversion to .jpg]] and .gif - .gif]] this works, but only when .jpg/.gif is on it's own line. i.e: .jpg will get converted to: .jpg]] but Image:test.jpg gets converted to: [[Image:test.jpg rather than [[Image:test.jpg]] -- Hope you can help again! Cheers -- http://mail.python.org/mailman/listinfo/python-list
Re: PyFAQ: anyone seen aahz' thread tutorial ?
Paul Boddie wrote: they have disappeared from the starship? any ideas where to look for them ? The Internet Archive (the rewind button of the Internet): http://web.archive.org/web/20050729075144/http://starship.python.net/crew/aahz/OSCON2001/ but of course. I didn't even bother to look there, because I was sure they didn't cache PDF files. oh well, you learn something every day ;-) thanks /F -- http://mail.python.org/mailman/listinfo/python-list
Re: mod_python installation problem ..severity High
boney wrote: On doing this and duly following the installation and testing instructions at www.modpython.org and then pointing the url as http://localhost/test/mptest.py, i get the following error on the server log file: [Tue Nov 14 15:17:47 2006] [error] make_obcallback: could not import mod_python.apache.\n [Tue Nov 14 15:17:47 2006] [error] make_obcallback: Python path being used ['C:Program FilesApache GroupApache2binpython24.zip', '.DLLs', '.lib', '.libplat-win', '.liblib-tk', 'C:Program FilesApache GroupApache2bin']. [Tue Nov 14 15:17:47 2006] [error] python_handler: no interpreter callback found. [Tue Nov 14 15:17:47 2006] [error] [client 127.0.0.1] python_handler: Can't get/create interpreter. Your registry settings for Python do not include the site-packages directory where mod_python typically gets installed. Thus, trying updating the registry to add the site-packages directory. As a guide, see the following post from the mod_python mailing list archive as a guide. http://www.modpython.org/pipermail/mod_python/2006-September/021979.html This is for Python 2.5, but should give an indicator of what to look for. Update the PythonPath entry. For any mod_python help in the future, suggest you subscribe to the mod_python mailing list and ask your question there as there is a higher concentration of people there who are familiar with the software. Details of the mod_python mailing list are on the mod_python web site. Graham -- http://mail.python.org/mailman/listinfo/python-list
Re: Programmatically finding significant data points
erikcw wrote: Hi all, I have a collection of ordered numerical data in a list. Called a time series in statistics. The numbers when plotted on a line chart make a low-high-low-high-high-low (random) pattern. I need an algorithm to extract the significant high and low points from this data. Here is some sample data: data = [0.10, 0.50, 0.60, 0.40, 0.39, 0.50, 1.00, 0.80, 0.60, 1.20, 1.10, 1.30, 1.40, 1.50, 1.05, 1.20, 0.90, 0.70, 0.80, 0.40, 0.45, 0.35, 0.10] In this data, some of the significant points include: data[0] data[2] data[4] data[6] data[8] data[9] data[13] data[14] How do I sort through this data and pull out these points of significance? The best place to ask about an algorithm for this is not comp.lang.python -- maybe sci.stat.math would be better. Once you have an algorithm, coding it in Python should not be difficult. I'd suggest using the NumPy array rather than the native Python list, which is not designed for crunching numbers. -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter: Strange behavior using place() and changing cursors
Wojciech Mula wrote: Mudcat wrote: [...] You have to set cursor once, Tk change it automatically: def buildFrame(self): self.f = Frame(self.master, height=32, width=32, relief=RIDGE, borderwidth=2) self.f.place(relx=.5,rely=.5) #self.f.bind( 'Enter', self.enterFrame ) #self.f.bind( 'Leave', self.leaveFrame ) self.f.configure(cursor = 'sb_h_double_arrow') The problem is I need the ability to change it dynamically. I don't want the cursor to be the double_arrow the whole time the mouse hovers inside that frame. It's supposed to be a resize arrow when the mouse is on the frame border, and regular cursor once it passes to the inner part of the frame. Unless there is a better way to do this, I have written code to determine if the mouse is on the edge or not. There doesn't seem to be a 'mouseover' type event to determine if the mouse is currently on the frame border itself. As a result, I calculate the position of the mouse and set the cursor appropriately. I have also determined that this is not a problem if the button is not packed inside the frame. So somehow the interaction of the internal button is causing this problem. -- http://mail.python.org/mailman/listinfo/python-list
RE: Noob | datetime question
Perfect. Thanks a million. .strftime was the method I was looking for. -Jeff -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of Kevin Kelley Sent: Tuesday, November 14, 2006 9:34 AM To: python-list@python.org Subject: Re: Noob | datetime question import time FORMAT='%Y%m%d' time.strftime(FORMAT,time.gmtime(time.time()+8380800)) output = '20070219' -- Kevin Kelley On 11/14/06, Demel, Jeff [EMAIL PROTECTED] wrote: I'm having trouble finding exactly what I need by googling, so thought I'd try to get a quick answer from the group. This seems like something that should be dead simple. I need to generate a string value of a date in the format MMDD that is 97 days in the future. The datetime module is brand new to me, and I'm not sure how to do this. Can someone help me out here? TIA -Jeff This email is intended only for the individual or entity to which it is addressed. This email may contain information that is privileged, confidential or otherwise protected from disclosure. Dissemination, distribution or copying of this e-mail or any attachments by anyone other than the intended recipient, or an employee or agent responsible for delivering the message to the intended recipient, is prohibited. If you are not the intended recipient of this message or the employee or agent responsible for delivery of this email to the intended recipient, please notify the sender by replying to this message and then delete it from your system. Any use, dissemination, distribution, or reproduction of this message by unintended recipients is strictly prohibited and may be unla! wful. -- http://mail.python.org/mailman/listinfo/python-list This email is intended only for the individual or entity to which it is addressed. This email may contain information that is privileged, confidential or otherwise protected from disclosure. Dissemination, distribution or copying of this e-mail or any attachments by anyone other than the intended recipient, or an employee or agent responsible for delivering the message to the intended recipient, is prohibited. If you are not the intended recipient of this message or the employee or agent responsible for delivery of this email to the intended recipient, please notify the sender by replying to this message and then delete it from your system. Any use, dissemination, distribution, or reproduction of this message by unintended recipients is strictly prohibited and may be unlawful. -- http://mail.python.org/mailman/listinfo/python-list
Re: Noob | datetime question
import timeFORMAT='%Y%m%d'time.strftime(FORMAT,time.gmtime(time.time()+8380800))output = '20070219'--Kevin KelleyOn 11/14/06, Demel, Jeff [EMAIL PROTECTED] wrote: I'm having trouble finding exactly what I need by googling, so thoughtI'd try to get a quick answer from the group.This seems like somethingthat should be dead simple.I need to generate a string value of a date in the format MMDD that is 97 days in the future.The datetime module is brand new to me, andI'm not sure how to do this.Can someone help me out here?TIA-JeffThis email is intended only for the individual or entity to which it is addressed.This email may contain information that is privileged, confidential or otherwise protected from disclosure. Dissemination, distribution or copying of this e-mail or any attachments by anyone other than the intended recipient, or an employee or agent responsible for delivering the message to the intended recipient, is prohibited. If you are not the intended recipient of this message or the employee or agent responsible for delivery of this email to the intended recipient, please notify the sender by replying to this message and then delete it from your system.Any use, dissemination, distribution, or reproduction of this message by unintended recipients is strictly prohibited and may be unla! wful. --http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Python speed on Solaris 10
I have found that the sunfreeware.com build of Python 2.4.3 for Solaris 10 is faster than one I can build myself, on the same system. sunfreeware.com doesn't bother showing the options they used to configure and build the software, so does anyone know what the optimal build options are for Solaris 10 (x86)? Here are some pybench/pystone results, and I include the same comparison of Python2.4.3 running on CentOS 4.3 on the same hardware (which is what prompted me to find a faster Python build in the first place). Python 2.4.3: System pybench Pystone (pystones/s) Sol10 my build 3836.00 ms 37313.4 Sol10 sunfreeware3235.00 ms 43859.6 CentOS 3569.00 ms 44247.8 My build: Python 2.4.3 (#1, Oct 15 2006, 16:00:33) [GCC 3.4.3 (csl-sol210-3_4-branch+sol_rpath)] on sunos5 sunfreeware.com build: Python 2.4.3 (#1, Jul 31 2006, 05:14:51) [GCC 3.4.6] on sunos5 My build on CentOS 4.3: Python 2.4.3 (#1, Jul 19 2006, 17:52:43) [GCC 3.4.5 20051201 (Red Hat 3.4.5-2)] on linux2 is the difference purely gcc minor version? -- http://chrismiles.info/ -- http://mail.python.org/mailman/listinfo/python-list
VLC-python bindings
Hi, Has anyone succeeded in compiling the vlc-python bindings on Windows? (as discussed in the vlc development wiki). I have found several compiled bindings, but none were updated for Python 2.4 (or 2.5 for that matter). As I am a complete layman for everything that is C compilation on any platform, could anyone point me to vlc-python bindings that work out of the box? Many thanks in advance, Mathieu -- http://mail.python.org/mailman/listinfo/python-list
Re: PyFAQ: anyone seen aahz' thread tutorial ?
Fredrik Lundh wrote: and yes, has anyone seen Aahz or his OSCON2001 thread tutorial slides lately ? as noticed here: http://effbot.org/pyfaq/how-do-i-program-using-threads.htm they have disappeared from the starship? any ideas where to look for them ? The Internet Archive (the rewind button of the Internet): http://web.archive.org/web/20050729075144/http://starship.python.net/crew/aahz/OSCON2001/ Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Seeking assistance - string processing.
Thanks Fredrik, Peter and John for your help. John, I especially enjoyed your line by line assasination of my code, keep it up. I'm not a programmer, I dislike programming, I'm bad at it. I just agreed to do this to help someone out, I didn't even know what python was 3 days ago. In case you were wondering about all the crazyness with the ---'s - it's because I am trying to batch convert 1600 files into new versions with slightly altered syntax. It all works for now, hurrah, now it's time to break it again. Cheerio fellas (for now, I'll be back I'm sure ;-D) -- http://mail.python.org/mailman/listinfo/python-list
Re: __init__.py
km wrote: I have a structure like this : foo/__init__.py foo/bar/__init__.py foo/bar/firstmodule.py foo/abc/__init__.py foo/abc/secondmodule.py now i have some variables (paths to data files) common, to be used in first module and second modules respectively. can i set those variables in foo/__init__.py so that i can access them by foo.mypath1 in first and second submodule class definitions? looks ok to me, as long as you remember to actually import foo into your submodules. have you tried it? /F -- http://mail.python.org/mailman/listinfo/python-list
Re: Using signal.alarm to terminate a thread
Nick Craig-Wood wrote: The only sensible things you can do from a signal handler is set a global flag, or call sem_post on a semaphore, to record the delivery of the signal. The remainder of the program can then either poll the global flag, or use sem_wait() and sem_trywait() on the semaphore. but that's exactly what Python's signal handlers do, right ? (the interpreter uses a pending call queue to collect events, and executes them from the interpreter main loop in a controlled fashion). /F -- http://mail.python.org/mailman/listinfo/python-list
Re: modules and generated code
Nigel Rantor wrote: Peter Otten wrote: Nigel Rantor wrote: So, if I have a tool that generates python code for me (in my case, CORBA stubs/skels) in a particular package is there a way of placing my own code under the same package hierarchy without all the code living in the same directory structure. http://docs.python.org/lib/module-pkgutil.html Yep, looks like that should work, but it doesn't. :-/ Do you have any idea whether other __init__.py scripts from the same logical module will still be run in this case? I don't think it will. The generated code uses its init script to pull in other code. You could invoke it explicitly via execfile(/path/to/generated/package/__init__.py) in the static package/__init__.py. Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Python 2.5 Core Dump on Solaris 8
You can set an environment variable MALLOC_CHECK_ to influence the behaviour of glibc 0 - no error message program continues 1 - error message, program continues 2 - no error message, kills program 3 - error message, kills program Since the message only occured with my two programs at exit time, I set the environment var to 0 HTH Anthon -- http://mail.python.org/mailman/listinfo/python-list
Re: __cmp__ between dissimilar objects
[EMAIL PROTECTED] wrote: I have a class that has, as an attribute, an instance of datetime.datetime(). I would like to be able to compare my class directly to instances of datetime.datetime in addition to other instances of my class. The value used for the comparison in either case should be the value of the datetime attribute of the class: from datetime import datetime class GeneralizedTime(object): def __init__(self, time=None): if time is None: self.datetime = datetime.now() def __cmp__(self, x): if isinstance(x, GeneralizedTime): return cmp(self.datetime, x.datetime) if isinstance(x, datetime): return cmp(self.datetime, x) import datetime GeneralizedTime() datetime.now() Traceback (most recent call last): File stdin, line 1, in ? TypeError: can't compare datetime.datetime to GeneralizedTime Clearly I'm misunderstanding something, here. As I understand my code, I'm directly comparing an instance of datetime (self.datetime) to another instance of datetime. sure looks like you're comparing a datetime instance against a GeneralizeTime instance to me. why not just inherit from datetime instead? or read footnote 4 under supported operations on this page for info on how to implement mixed-type comparisions: http://docs.python.org/lib/datetime-datetime.html /F -- http://mail.python.org/mailman/listinfo/python-list
Re: Py3K idea: why not drop the colon?
On 2006-11-13, Steve Holden [EMAIL PROTECTED] wrote: John Salerno wrote: Fredrik Lundh wrote: John Salerno wrote: Anyway, the FAQ answer seems to be a weak argument to me. I agree. I was expecting something more technical to justify the colon, not just that it looks better. yeah, the whole idea of treating programming languages as an interface between people and computers is really lame. no wonder nobody's using Python for anything. /F personally, i don't mind the colon and see no need to lose it, but if we are talking in the realm of aesthetics, it actually seems like it would be cleaner if it weren't there...sure, at first everyone who is used to it might feel like something is missing, or the line is hanging open, but overall the less characters, the better, right? isn't that why the braces are gone? No. The braces are gone because they don't assist a reader's determination of block structure like indentation does. IMO this works both ways. Otherwise why would people write indenting pretty printers for C and the like? Try to follow an indentation marked structure when the structure crosses a page boundary and you can't view the whole structure at once. Sensible placed markers can greatly assist in getting a feel for a structure even if the structure is already properly indented. -- Antoon Pardon -- http://mail.python.org/mailman/listinfo/python-list
Re: Py3K idea: why not drop the colon?
On 2006-11-13, Ben Finney [EMAIL PROTECTED] wrote: Michael Hobbs [EMAIL PROTECTED] writes: To be clear, this is the actual thrust of my argument. It seems redundant to have *both* line continuations and colons in compound statements. Why are you trying to remove redundancy? Why not? My impression is that removing redundancy is considered a positive thing here in c.p.l. The language is designed for communication between people (programmers) primarily. Redundancy is often the best way to be explicit and readable. Except if you argue for blockmarkers. Then you get the response that indentation is clear enough and such markers are redundant. And there have been other subjects where redundancy was seen as something negative. -- Antoon Pardon -- http://mail.python.org/mailman/listinfo/python-list
Re: CORBA: Fnorb Problems
Traceback (most recent call last): File C:\Python24\Lib\site-packages\Fnorb\script\cpp.py, line 53, in -toplevel- raise No C/C++ pre-processor found in your PATH! No C/C++ pre-processor found in your PATH! You don't say *when* this error occurs, i.e. what is the command that returns the exception. Assuming it's when you try to compile an IDL file with fnidl, just try: fnidl --internal-cpp ... Sorry you are right I did not say, but you guessed correctly. However even when I try your advice I still receive the same error. Best, rod -- http://mail.python.org/mailman/listinfo/python-list
PYTHON + EXCEL
I write my code : #inizializzazioni varie che tralascio #mi connetto al mio db mysql e recupero i dati che volgio inserire nel file excel conn = MySQLdb.connect(host = XXX, port = XXX, user = XXX, passwd = XXX, db= XXX) cursor = conn.cursor() cursor.execute(SELECT * FROM XXX) allFields = cursor.description allRecords = cursor.fetchall() cursor.close() conn.close() #inizializzo gli strumenti per lavorare in python con excel xlApp = Dispatch(Excel.Application) #xlApp.Visible = 1 xlApp.Workbooks.Add() #specifico che file utilizzare xlbook = xlApp.Workbooks.Open('C:/view.xls') i = 1 j = 1 #popolo il mio file excel for field in allFields : xlApp.ActiveSheet.Cells(i, j).Value = field[0] j = j + 1 for records in allRecords : i = i + 1 j = 1 for item in records : xlApp.ActiveSheet.Cells(i, j).Value = item j = j + 1 #salvo le modifiche effettuate xlbook.SaveAs('C:/view.xls') #scrivo le istruzioni che mi permettereanno di aprirlo in una pagina html size = os.path.getsize('C:/view.xls') of = open(C:/view.xls,rb) content = of.read() of.close() printContent-Type:application7vnd.ms-excel printcontent-disposition:inline;filename=view.xls printContent-length:%d \r\n%size print content I want open an excel document in an apache page. I want write in excel document the information of a database mySQL and after open the excel documen in a broswer page Where is the problem? Sorry for my english but I'm not speak english very well, I write in this group because I think that in this forum there are very very good programmer -- http://mail.python.org/mailman/listinfo/python-list
Re: __init__.py
km wrote: wow ! i tried it and it works like charm! could access variables declared at root module dir in submodules. also i would like to know if i can have an abstract class declared in __init__.py with common variables ? you don't really need our permission to try things out, you know ;-) /F -- http://mail.python.org/mailman/listinfo/python-list
Re: __init__.py
Hi, wow ! i tried it and it works like charm! could access variables declared at root module dir in submodules. also i would like to know if i can have an abstract class declared in __init__.py with common variables ? regards, KMOn 11/14/06, Fredrik Lundh [EMAIL PROTECTED] wrote: km wrote: I have a structure like this : foo/__init__.py foo/bar/__init__.py foo/bar/firstmodule.py foo/abc/__init__.py foo/abc/secondmodule.py now i have some variables (paths to data files) common, to be used in first module and second modules respectively. can i set those variables in foo/__init__.py so that i can access them by foo.mypath1 in first and second submodule class definitions?looks ok to me, as long as you remember to actually import foo into your submodules.have you tried it?/F--http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: modules and generated code
Peter Otten wrote: Nigel Rantor wrote: So, if I have a tool that generates python code for me (in my case, CORBA stubs/skels) in a particular package is there a way of placing my own code under the same package hierarchy without all the code living in the same directory structure. http://docs.python.org/lib/module-pkgutil.html Ooh, thanks for that. Yep, looks like that should work, but it doesn't. :-/ Do you have any idea whether other __init__.py scripts from the same logical module will still be run in this case? The generated code uses its init script to pull in other code. Off, to tinker some more with this. n -- http://mail.python.org/mailman/listinfo/python-list
Re: Noob | datetime question
On Tue, 2006-11-14 at 09:33 -0600, Kevin Kelley wrote: import time FORMAT='%Y%m%d' time.strftime(FORMAT,time.gmtime(time.time()+8380800)) output = '20070219' While the above works, the following variation using datetime is more readable: import datetime someday = datetime.date.today() + datetime.timedelta(days=97) print someday.strftime(%Y%m%d) 20070219 -Carsten -- http://mail.python.org/mailman/listinfo/python-list
Re: PyFAQ: anyone seen aahz' thread tutorial ?
In article [EMAIL PROTECTED], Fredrik Lundh [EMAIL PROTECTED] wrote: and yes, has anyone seen Aahz or his OSCON2001 thread tutorial slides lately ? as noticed here: http://effbot.org/pyfaq/how-do-i-program-using-threads.htm they have disappeared from the starship? any ideas where to look for them ? Just a public note that I'm aware of the problem and have sent e-mail privately to Fredrik, just haven't had enough cycles to fix it -- Aahz ([EMAIL PROTECTED]) * http://www.pythoncraft.com/ In many ways, it's a dull language, borrowing solid old concepts from many other languages styles: boring syntax, unsurprising semantics, few automatic coercions, etc etc. But that's one of the things I like about it. --Tim Peters on Python, 16 Sep 1993 -- http://mail.python.org/mailman/listinfo/python-list
refactoring so that multiple changes can be made with one variable?
My code is below. For now I'm focusing on the lines where health (and armor) are increased in each character class. Let's say I decided to change the amount of increase in the future. As it is now, I'd have to go to each character class and change the number so that each is still in a good relation to the other (right now: 3, 2, 1; later: perhaps 4, 3, 2, 1, if I added a new class -- i.e., change Fighter from 3 to 4, Thief from 2 to 3, in other words increase them all by 1). So instead of changing each one, is there a simple, clean way of just changing a single number so that this change is reflected in all classes? Hope that makes sense. class Character(object): def __init__(self, name, strength, dexterity, intelligence): self.name = name self.health = 10 self.armor = self.attack = self.defense = self.magic_attack = \ self.magic_defense = 0 self.strength = strength self.dexterity = dexterity self.intelligence = intelligence self.adjust_attributes() def adjust_attributes(self): pass class Fighter(Character): def adjust_attributes(self): self.health += 3 self.armor += 3 self.attack += 2 self.defense += 2 self.strength += 1 class Thief(Character): def adjust_attributes(self): self.health += 2 self.armor += 2 self.attack += 1 self.defense += 1 self.magic_defense += 1 self.dexterity += 1 class Mage(Character): def adjust_attributes(self): self.health += 1 self.armor += 1 self.magic_attack += 2 self.magic_defense += 2 self.intelligence += 1 -- http://mail.python.org/mailman/listinfo/python-list
Re: Programmatically finding significant data points
erikcw wrote: I have a collection of ordered numerical data in a list. The numbers when plotted on a line chart make a low-high-low-high-high-low (random) pattern. I need an algorithm to extract the significant high and low points from this data. In calculus, you identify high and low points by looking where the derivative changes its sign. When working with discrete samples, you can look at the sign changes in finite differences: data = [...] diff = [data[i + 1] - data[i] for i in range(len(data))] map(str, diff) ['0.4', '0.1', '-0.2', '-0.01', '0.11', '0.5', '-0.2', '-0.2', '0.6', '-0.1', '0.2', '0.1', '0.1', '-0.45', '0.15', '-0.3', '-0.2', '0.1', '-0.4', '0.05', '-0.1', '-0.25'] The high points are those where diff changes from + to -, and the low points are those where diff changes from - to +. HTH, -- Roberto Bonvallet -- http://mail.python.org/mailman/listinfo/python-list
Programmatically finding significant data points
Hi all, I have a collection of ordered numerical data in a list. The numbers when plotted on a line chart make a low-high-low-high-high-low (random) pattern. I need an algorithm to extract the significant high and low points from this data. Here is some sample data: data = [0.10, 0.50, 0.60, 0.40, 0.39, 0.50, 1.00, 0.80, 0.60, 1.20, 1.10, 1.30, 1.40, 1.50, 1.05, 1.20, 0.90, 0.70, 0.80, 0.40, 0.45, 0.35, 0.10] In this data, some of the significant points include: data[0] data[2] data[4] data[6] data[8] data[9] data[13] data[14] How do I sort through this data and pull out these points of significance? Thanks for your help! Erik -- http://mail.python.org/mailman/listinfo/python-list
Re: Programmatically finding significant data points
erikcw wrote: I have a collection of ordered numerical data in a list. The numbers when plotted on a line chart make a low-high-low-high-high-low (random) pattern. I need an algorithm to extract the significant high and low points from this data. ... How do I sort through this data and pull out these points of significance? Get a book on statistics. One idea is as follows. If you expect the points to be centred around a single value, you can calculate the median or mean of the points, calculate their standard deviation (aka spread), and remove points which are more than N-times the standard deviation from the median. Jeremy -- Jeremy Sanders http://www.jeremysanders.net/ -- http://mail.python.org/mailman/listinfo/python-list
Re: modules and generated code
Nigel Rantor wrote: So, if I have a tool that generates python code for me (in my case, CORBA stubs/skels) in a particular package is there a way of placing my own code under the same package hierarchy without all the code living in the same directory structure. http://docs.python.org/lib/module-pkgutil.html Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Programmatically finding significant data points
erikcw [EMAIL PROTECTED] wrote: I have a collection of ordered numerical data in a list. The numbers when plotted on a line chart make a low-high-low-high-high-low (random) pattern. I need an algorithm to extract the significant high and low points from this data. I think you want a control chart. A good place to start might be http://en.wikipedia.org/wiki/Control_chart. Even if you don't actually graph the data, understanding the math behind control charts might help you with your analysis. Wow. I think this is the first time I'm actually used something I learned by sitting though those stupid Six Sigma training classes :-) -- http://mail.python.org/mailman/listinfo/python-list
Re: Programmatically finding significant data points
erikcw wrote: Hi all, I have a collection of ordered numerical data in a list. The numbers when plotted on a line chart make a low-high-low-high-high-low (random) pattern. I need an algorithm to extract the significant high and low points from this data. Here is some sample data: data = [0.10, 0.50, 0.60, 0.40, 0.39, 0.50, 1.00, 0.80, 0.60, 1.20, 1.10, 1.30, 1.40, 1.50, 1.05, 1.20, 0.90, 0.70, 0.80, 0.40, 0.45, 0.35, 0.10] In this data, some of the significant points include: data[0] data[2] data[4] data[6] data[8] data[9] data[13] data[14] How do I sort through this data and pull out these points of significance? I think you are looking for extrema: def w3(items): items = iter(items) view = None, items.next(), items.next() for item in items: view = view[1:] + (item,) yield view for i, (a, b, c) in enumerate(w3(data)): if a b c: print i+1, min, b elif a b c: print i+1, max, b else: print i+1, ---, b Peter -- http://mail.python.org/mailman/listinfo/python-list
matplotlib and zope
Hello All, I've been using zope and matplotlib for some time now, and I want to connect them. I'am using the example code from page: http://www.scipy.org/Cookbook/Matplotlib/Matplotlib_and_Zope , but whenever I try to import matplotlib, and/or pylab packages i get this error from zope: Error Type: RuntimeError Error Value: '/' is not a writable dir; you must set environment variable HOME to be a writable dir Have You got any ideas, on what might go wrong? Is it a problem with matplotlib itself? Have anyone had the same issue? I'am using matplotlib 0.87.4, and zope 2.9.5 with python 2.4.3 on gentoo linux box. Thanks in advance for any help. Marek Szczypinski Here is the traceback: Traceback (innermost last): Module ZPublisher.Publish, line 115, in publish Module ZPublisher.mapply, line 88, in mapply Module ZPublisher.Publish, line 41, in call_object Module Products.ExternalMethod.ExternalMethod, line 59, in manage_addExternalMethod Module Products.ExternalMethod.ExternalMethod, line 111, in __init__ Module Products.ExternalMethod.ExternalMethod, line 134, in manage_edit Module Products.ExternalMethod.ExternalMethod, line 141, in getFunction Module App.Extensions, line 148, in getObject - __traceback_info__: ('/var/lib/zope/zope-markacy/Extensions/mpl.py', 'mpl') Module /var/lib/zope/zope-markacy/Extensions/mpl.py, line 1, in ? Module None, line 1011, in ? Module None, line 968, in rc_params Module None, line 914, in matplotlib_fname Module None, line 273, in wrapper Module None, line 324, in _get_configdir RuntimeError: '/' is not a writable dir; you must set environment variable HOME to be a writable dir -- http://mail.python.org/mailman/listinfo/python-list
Re: refactoring so that multiple changes can be made with one variable?
John Salerno wrote: My code is below. For now I'm focusing on the lines where health (and armor) are increased in each character class. Let's say I decided to change the amount of increase in the future. As it is now, I'd have to go to each character class and change the number so that each is still in a good relation to the other (right now: 3, 2, 1; later: perhaps 4, 3, 2, 1, if I added a new class -- i.e., change Fighter from 3 to 4, Thief from 2 to 3, in other words increase them all by 1). So instead of changing each one, is there a simple, clean way of just changing a single number so that this change is reflected in all classes? Hope that makes sense. You could keep a handle on all object instances created then go through the objects making appropriate changes, e.g: class Character(object): instances = [] def __init__(self, name, strength, dexterity, intelligence): instances.append(self) # as before ... def mod_instances(self): for inst in instances: inst.some_property += 1 # or whatever # (Untested) - Paddy. -- http://mail.python.org/mailman/listinfo/python-list
Re: CORBA: Fnorb Problems
On Tue, 14 Nov 2006 13:13:42 +0100, rodmc [EMAIL PROTECTED] wrote: Traceback (most recent call last): File C:\Python24\Lib\site-packages\Fnorb\script\cpp.py, line 53, in -toplevel- raise No C/C++ pre-processor found in your PATH! No C/C++ pre-processor found in your PATH! You don't say *when* this error occurs, i.e. what is the command that returns the exception. Assuming it's when you try to compile an IDL file with fnidl, just try: fnidl --internal-cpp ... Sorry you are right I did not say, but you guessed correctly. However even when I try your advice I still receive the same error. I took a look at the Fnorb sources and it appears you're right: even if the --internal-cpp flag is used, fnidl still tests if the MS compiler exists and breaks if it can't be called or if it doesn't return what fnidl expects. The actual test is whether the cl output contains the string /link, whatever the character case. So as you said in your original post that cl can be run, but doesn't print anything, this seems to be the problem. What you can do is the following: go to Fnorb's source directory and edit scripts/cpp.py; on line 53, replace the raise ... by: COMMAND = None with the same indent. Then run fnidl again with the --internal-cpp flag. This should work and produce the expected files. Note that this is a dirty hack: if you forget to specify the --internal-cpp flag, you'll get a nasty traceback. But it should work in your case. HTH -- python -c print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-']) -- http://mail.python.org/mailman/listinfo/python-list
Re: A question on Encoding and Decoding.
kath wrote: Also python IDLE is able to output the same character corretly when I say print and why not I? probably because IDLE's interactive window is Unicode-aware, but your terminal is not. /F -- http://mail.python.org/mailman/listinfo/python-list
Re: sqlite3 views, if not exists clause
Fredrik Lundh wrote: Josh wrote: THIS DOES NOT WORK, but it should! Python 2.5 was released on September 19th, 2006, and support for CREATE VIEW IF NOT EXISTS was added to sqlite on October 9th, 2006: So? from __future__ import ... should have supported this! :o) -- Roberto Bonvallet -- http://mail.python.org/mailman/listinfo/python-list
modules and generated code
Hi all, Python newbie here with what I hope is a blindingly obvious question that I simply can't find the answer for in the documentation. So, if I have a tool that generates python code for me (in my case, CORBA stubs/skels) in a particular package is there a way of placing my own code under the same package hierarchy without all the code living in the same directory structure. Ideally I would like something like the following: package_dir/ top_level_package/ generated_code_package/ implementation_code_package/ but have two distinct directories that hold them so that I can simply delete the generated code and regenerate it without worrying that anything got left behind. So, I want something like: generated_package_dir/ top_level_package/ generated_code_package/ implementation_package_dir/ top_level_package/ implementation_code_package/ Whilst I can create this structure, and add 'generated_package_dir' and 'implementation_package_dir' to PYTHONPATH the fact that both directories contain 'top_level_package' seems to be causing clashes, perhaps because there are multiple __init__.py files for 'top_level_package'? I know that this is possible in Java, Perl and C++ so I am finding it hard to believe I can't do the same in Python, I just think I'm too new to know how. I have spent most of this morning searching through all the docs I can find, searching on USENET and the web to no avail. Any help or pointers greatly appreciated. Regards, n -- http://mail.python.org/mailman/listinfo/python-list
Re: Py3K idea: why not drop the colon?
Hendrik van Rooyen wrote: This is true - and it is actually also an intractable problem - if you look at what your daughter wrote, you get the feeling that you should be able to write an interpreter that can implement what she meant, because it is quite clear to you - until you try to write the specs... Unfortunately natural language is completely riddled with ambiguities about negation and conjunction. It doesn't seem like a good idea for programming languages to emulate these too closely, even if it does make for more natural constructions. For example: You must not go there. means You are forbidden to go there. You do not have to go there. means You are not required to go there. Similar negations of two English verbs with virtually identical meaning makes quite a difference in the semantics of the complete sentence! Likewise, double negation is perfectly equivalent to single negation in many languages, including in some dialects of English: I ain't got time. means I don't have time. I ain't got no time. means I don't have time. Another problem is that the English word or sometimes means inclusive or and sometimes means exclusive or: Do you have any brothers or sisters? (inclusive or) You can carry on a briefcase or a backpack. (exclusive or) I think part of learning to think like a computer is learning to stop associating computer logic too strongly with the natural language meanings of and, or, and not. Dan -- http://mail.python.org/mailman/listinfo/python-list
Noob | datetime question
I'm having trouble finding exactly what I need by googling, so thought I'd try to get a quick answer from the group. This seems like something that should be dead simple. I need to generate a string value of a date in the format MMDD that is 97 days in the future. The datetime module is brand new to me, and I'm not sure how to do this. Can someone help me out here? TIA -Jeff This email is intended only for the individual or entity to which it is addressed. This email may contain information that is privileged, confidential or otherwise protected from disclosure. Dissemination, distribution or copying of this e-mail or any attachments by anyone other than the intended recipient, or an employee or agent responsible for delivering the message to the intended recipient, is prohibited. If you are not the intended recipient of this message or the employee or agent responsible for delivery of this email to the intended recipient, please notify the sender by replying to this message and then delete it from your system. Any use, dissemination, distribution, or reproduction of this message by unintended recipients is strictly prohibited and may be unlawful. -- http://mail.python.org/mailman/listinfo/python-list
Re: Py3K idea: why not drop the colon?
Hendrik van Rooyen wrote: Robert Kern [EMAIL PROTECTED] wrote: Michael Hobbs wrote: True enough. Although, I have to ask how many times you define a new function only to have Python spit a syntax error out at you saying that you forgot a colon. It happens to me all the time. (Usually after an else) If you'd never notice that the colon was missing if the compiler didn't point it out, is it really that readable? For me, I tend to get annoyed at language features that I'm constantly tripping over. Never. I confess I find myself in the position of a Yorkshire Youngster - I don't believe you! Okay, not often enough or annoyingly enough for me to remember having done so. Perhaps seven years ago when I started using Python, but not any time recent. -- Robert Kern I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth. -- Umberto Eco -- http://mail.python.org/mailman/listinfo/python-list
another newbie question
Hello everyone, I have a question that google couldnt answer for me and thought that the brains on here might be able to help. I am trying to upload a file to a database using a (cgi) form and am having trouble doing this. I think that I need some way of escaping the file contents or making it so that mysql/python (not sure which) will ignore the files actual contents and store it in the db regardless of what is actually in the file. I hope that made sense. Thanks in advance for any help. Regards, MJ -- http://mail.python.org/mailman/listinfo/python-list
Re: Random image text generation?
Paul == Paul Rubin http://phr.cx@NOSPAM.invalid writes: Paul Steven D'Aprano [EMAIL PROTECTED] writes: Instead of displaying an obfuscated image of a nonsense word, display six randomly chosen photos, where five are of the same thing but not the same image. E.g. you might show five different kittens and a horse. The user has to click on the image that is not the same as the others. State-of-the-art horse-recognition software is not yet in widespread use by spammers *wink* Paul No need to recognize the horse. Just pick one of the pictures at Paul random and you'll get the right one 1/6th of the time. Repeat ad Paul infinitum--they're spammers and like to repeat stuff after all. Paul That's why those conventional captcha images make you recognize a Paul multi-character string: so the guessing chance is low. Actually, the ones I saw that used a set of one of these things is not like the other images gave you a pop-up menu of maybe 100-200 words. The user needed to choose the name of the different object from that list. That makes it a bit harded to guess. Of course, these sorts of tests suffer from the same shortcoming as the randomly generated string. Visually impaired people have trouble with it. I finally settled on just reusing the SpamBayes engine to detect/reject spam submissions. Skip -- http://mail.python.org/mailman/listinfo/python-list
wxpython - wxtoolbar font size
Hi all i want to set wx.toolbar font size and i use this code: self.tb1 = wx.ToolBar(self, -1, style=wx.TB_HORIZONTAL| wx.TB_TEXT) self.tb1.SetFont(wx.Font(9, wx.DEFAULT, wx.NORMAL,0)) self.SetToolBar(self.tb1) but i obtain nothing. Is possibile? where i wrong? I use wxpython 2.6.3 on ubuntu edgy thanks Ghido -- http://mail.python.org/mailman/listinfo/python-list
Re: another newbie question
Lots of smart, patient people here, but they can't help you until you provide a lot more information and the actual error messages you are getting and whether they are spawned by Python or MySQL, if that is indeed the db you are using. Where did you get the idea that Python might be involved? Read this and it will serve you well for this inquiry and any others you may have. http://catb.org/esr/faqs/smart-questions.html Good luck rd Give a man a fire and keep him warm for a day. Light a man on fire and he will be warm for rest of his life. --Terry Pratchett -- http://mail.python.org/mailman/listinfo/python-list
Re: another newbie question
Mary Jane Boholst wrote: I am trying to upload a file to a database using a (cgi) form and am having trouble doing this. I think that I need some way of escaping the file contents or making it so that mysql/python (not sure which) will ignore the files actual contents and store it in the db regardless of what is actually in the file. http://effbot.org/pyfaq/how-do-i-escape-sql-values-when-using-the-db-api /F -- http://mail.python.org/mailman/listinfo/python-list
Re: Decimal() instead of float?
Michael B. Trausch wrote: On Mon, 2006-11-13 at 03:45 -0600, Steve Holden wrote: Michael B. Trausch wrote: Is there a way to use Decimal() by default in Python instead of float? No. You'll just have to be explicit. That's kinda what I figured. :-( It /would/ be nice to see Decimal() become the default. I cannot imagine why in an otherwise human enough language, math wouldn't be included in that without going out of one's way to do it. :-) Speed has a lot to do with it. Have you timed some decimal operations against their floating-point counterparts? It might be possible to build a version of Python that used decimal instead of floating-point but it certainly wouldn't be trivial: consider the use of C language libraries that know nothing of Python's decimal representation. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden -- http://mail.python.org/mailman/listinfo/python-list
mod_python installation problem ..severity High
hello All, I am totally unknown to python language.. i need to install mod_python to embed python interpreter with the Apache server, in order to use Trac with Apache Web Server i am using : Python 2.4.3, apache 2.0.50 for windows, mod_python-3.2.10.win32-py2.4-apache2.0 (windows installer) after installing the packages i added the following lines to the httpd.conf file : LoadModule python_module modules/mod_python.so in order to test mod_python installation i added to following line to the httpd.conf file Directory C:/Program Files/Apache Group/Apache2/htdocs/test AddHandler mod_python .py PythonHandler mptest PythonDebug On /Directory within the htdocs/test folder there is mptest.py file with the following contents from mod_python import apache def handler(req): req.content_type = 'text/plain' req.write(Hello World!) return apache.OK On doing this and duly following the installation and testing instructions at www.modpython.org and then pointing the url as http://localhost/test/mptest.py, i get the following error on the server log file: [Tue Nov 14 15:17:47 2006] [error] make_obcallback: could not import mod_python.apache.\n [Tue Nov 14 15:17:47 2006] [error] make_obcallback: Python path being used ['C:Program FilesApache GroupApache2binpython24.zip', '.DLLs', '.lib', '.libplat-win', '.liblib-tk', 'C:Program FilesApache GroupApache2bin']. [Tue Nov 14 15:17:47 2006] [error] python_handler: no interpreter callback found. [Tue Nov 14 15:17:47 2006] [error] [client 127.0.0.1] python_handler: Can't get/create interpreter. On one of the forum i got the following feedback regarding this error:- This one seems to occur on all platforms with similar frequency, and is usually related to having python multiple versions on the same system.The solution is to adjust that PATH apache uses so it finds the correct python version. But i donot have multiple versions of python installed. Can anybody give some insight to what can be the problem and hw to reach to the solution ?? Thanks in Advance Boney -- http://mail.python.org/mailman/listinfo/python-list
Re: Random image text generation?
Steven D'Aprano [EMAIL PROTECTED] writes: Instead of displaying an obfuscated image of a nonsense word, display six randomly chosen photos, where five are of the same thing but not the same image. E.g. you might show five different kittens and a horse. The user has to click on the image that is not the same as the others. State-of-the-art horse-recognition software is not yet in widespread use by spammers *wink* No need to recognize the horse. Just pick one of the pictures at random and you'll get the right one 1/6th of the time. Repeat ad infinitum--they're spammers and like to repeat stuff after all. That's why those conventional captcha images make you recognize a multi-character string: so the guessing chance is low. -- http://mail.python.org/mailman/listinfo/python-list
__init__.py
Hi all, what is the use of __init__.py file in a module dir ? Is it used to initialize variables that could be shared across sub modules if set in __init__.py at root dir of module ? regards, KM -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter: Strange behavior using place() and changing cursors
Mudcat wrote: [...] You have to set cursor once, Tk change it automatically: def buildFrame(self): self.f = Frame(self.master, height=32, width=32, relief=RIDGE, borderwidth=2) self.f.place(relx=.5,rely=.5) #self.f.bind( 'Enter', self.enterFrame ) #self.f.bind( 'Leave', self.leaveFrame ) self.f.configure(cursor = 'sb_h_double_arrow') -- http://mail.python.org/mailman/listinfo/python-list
PyFAQ: anyone seen aahz' thread tutorial ?
and yes, has anyone seen Aahz or his OSCON2001 thread tutorial slides lately ? as noticed here: http://effbot.org/pyfaq/how-do-i-program-using-threads.htm they have disappeared from the starship? any ideas where to look for them ? /F -- http://mail.python.org/mailman/listinfo/python-list
Re: Seeking assistance - string processing.
John Machin wrote: new = line[:-1] + ===\n To allow for cases where the last line in the file is not terminated [can happen], this should be: new = line.rstrip(\n) + ===\n # assuming you want to fix the unterminated problem. Cheers, John -- http://mail.python.org/mailman/listinfo/python-list
Re: __cmp__ between dissimilar objects
why not just inherit from datetime instead? I'll probably do that in the next iteration. or read footnote 4 under supported operations on this page for info on how to implement mixed-type comparisions: http://docs.python.org/lib/datetime-datetime.html OK. I added a 'timetuple' attribute to my class. Now comparisons seem to just work. This has made it even more obvious to me that I don't understand how comparisons function: If the GeneralizedTime instance is on the LHS of the comparison and the datetime instance on the RHS, why would datetime's __cmp__ method be called? I assume its being called since GeneralizedTime sure doesn't care whether or not it has a timetuple attribute... I've read through the Basic customization section of the language reference, which doesn't seem to describe a scenario where the __cmp__ method on the RHS is called. Thanks... -Ben -- http://mail.python.org/mailman/listinfo/python-list
Re: Py3K idea: why not drop the colon?
Michael Hobbs wrote: True enough. Although, I have to ask how many times you define a new function only to have Python spit a syntax error out at you saying that you forgot a colon. It happens to me all the time. I confess I find myself in the position of a Yorkshire Youngster - I don't believe you! Robert Okay, not often enough or annoyingly enough for me to remember Robert having done so. Perhaps seven years ago when I started using Robert Python, but not any time recent. If your editor knows about Python's block structure (as Emacs's python-mode does), when you forget the colon it's immediately obvious because the next line doesn't autoindent properly. Skip -- http://mail.python.org/mailman/listinfo/python-list